-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpaths.mjs
More file actions
632 lines (588 loc) · 21.6 KB
/
Copy pathpaths.mjs
File metadata and controls
632 lines (588 loc) · 21.6 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
/**
* Shared path constants for agent installation/uninstallation scripts.
*
* This module provides the common directory paths used by postinstall.mjs
* and preuninstall.mjs to locate agent files.
*/
import { readFileSync } from "node:fs"
import { homedir } from "node:os"
import { dirname, join } from "node:path"
import { fileURLToPath } from "node:url"
// Import checkVersionCompatibility for internal use
import { checkVersionCompatibility as _checkVersionCompatibility } from "./semver.mjs"
// Re-export semver utilities for backwards compatibility
export {
checkVersionCompatibility,
compareVersions,
parseVersion,
} from "./semver.mjs"
/**
* Default OpenCode version for compatibility checking.
*
* This version string is used to check agent compatibility requirements
* during installation when no override is provided.
*
* Format: Semantic versioning (MAJOR.MINOR.PATCH)
*/
const DEFAULT_OPENCODE_VERSION = "0.1.0"
/**
* OpenCode version used for compatibility checking.
*
* This version string is used to check agent compatibility requirements
* during installation. It can be overridden by setting the `OPENCODE_VERSION`
* environment variable, which is useful for:
* - Testing agents against different OpenCode versions
* - Development environments with pre-release OpenCode builds
* - CI/CD pipelines that need to simulate specific versions
*
* Format: Semantic versioning (MAJOR.MINOR.PATCH)
*
* @example
* import { OPENCODE_VERSION, checkVersionCompatibility } from "./paths.mjs"
*
* // Check if an agent requiring ">=0.1.0" is compatible
* const isCompatible = checkVersionCompatibility(">=0.1.0", OPENCODE_VERSION)
*
* @example
* // Override via environment variable
* // OPENCODE_VERSION=1.0.0 node postinstall.mjs
* // Now OPENCODE_VERSION will be "1.0.0" instead of the default
*/
export const OPENCODE_VERSION = process.env.OPENCODE_VERSION || DEFAULT_OPENCODE_VERSION
/**
* List of expected agent names (without .md extension).
*
* This is the single source of truth for agent filenames used during
* installation and uninstallation. Each name maps directly to a `.md`
* file in the `agents/` directory.
*
* **Agent roles:**
* - `opencoder` - Main orchestrator that coordinates the Plan-Build-Commit loop
* - `opencoder-planner` - Analysis subagent that examines codebases and creates prioritized task lists
* - `opencoder-builder` - Execution subagent that implements individual tasks and verifies changes
*
* The array is frozen via `Object.freeze()` to prevent accidental mutation,
* ensuring consistency across the codebase.
*
* @example
* import { AGENT_NAMES } from "./paths.mjs"
*
* // Iterate over agent names to process files
* for (const name of AGENT_NAMES) {
* const filename = `${name}.md`
* console.log(`Processing ${filename}`)
* }
*
* @example
* // Check if a name is a valid agent
* const isValidAgent = AGENT_NAMES.includes("opencoder") // true
* const isInvalid = AGENT_NAMES.includes("unknown") // false
*/
export const AGENT_NAMES = Object.freeze(["opencoder", "opencoder-planner", "opencoder-builder"])
/** Minimum character count for valid agent files */
export const MIN_CONTENT_LENGTH = 100
/**
* Keywords that must appear in valid agent files for content validation.
*
* Used by {@link validateAgentContent} to verify that a file actually contains
* agent-related content rather than arbitrary text. The validation is
* case-insensitive, so "Agent", "TASK", or "task" all match.
*
* **Keyword purposes:**
* - `"agent"` - Identifies the file as defining or describing an agent persona
* - `"task"` - Indicates the file contains task execution logic or instructions
*
* At least one of these keywords must be present for validation to pass.
* This acts as a sanity check to catch corrupted or incorrectly-named files.
*
* @example
* import { REQUIRED_KEYWORDS } from "./paths.mjs"
*
* // Manual keyword check (validateAgentContent does this internally)
* const content = "# My Agent\nThis agent handles tasks..."
* const lowerContent = content.toLowerCase()
* const hasKeyword = REQUIRED_KEYWORDS.some(kw => lowerContent.includes(kw))
* console.log(hasKeyword) // true (contains "agent" and "tasks")
*
* @example
* // Invalid content missing keywords
* const badContent = "# Random File\nThis is just some notes."
* const lowerBad = badContent.toLowerCase()
* const isValid = REQUIRED_KEYWORDS.some(kw => lowerBad.includes(kw))
* console.log(isValid) // false (no "agent" or "task")
*
* @see {@link validateAgentContent} - The function that uses these keywords
*/
export const REQUIRED_KEYWORDS = ["agent", "task"]
/**
* Required fields in YAML frontmatter.
* Frozen to prevent accidental mutation.
*/
export const REQUIRED_FRONTMATTER_FIELDS = Object.freeze(["version", "requires"])
/**
* Get the package root directory from a module's import.meta.url
* @param {string} importMetaUrl - The import.meta.url of the calling module
* @returns {string} The package root directory path
* @throws {TypeError} If importMetaUrl is not a non-empty string
*/
export function getPackageRoot(importMetaUrl) {
if (typeof importMetaUrl !== "string") {
throw new TypeError(
`getPackageRoot: importMetaUrl must be a string, got ${importMetaUrl === null ? "null" : typeof importMetaUrl}`,
)
}
if (importMetaUrl.trim() === "") {
throw new TypeError("getPackageRoot: importMetaUrl must not be empty")
}
const __filename = fileURLToPath(importMetaUrl)
const __dirname = dirname(__filename)
// Both postinstall.mjs and preuninstall.mjs are in the package root
return __dirname
}
/**
* Get the source directory containing agent markdown files.
* @param {string} packageRoot - The package root directory
* @returns {string} Path to the agents source directory
* @throws {TypeError} If packageRoot is not a non-empty string
*/
export function getAgentsSourceDir(packageRoot) {
if (typeof packageRoot !== "string") {
throw new TypeError(
`getAgentsSourceDir: packageRoot must be a string, got ${packageRoot === null ? "null" : typeof packageRoot}`,
)
}
if (packageRoot.trim() === "") {
throw new TypeError("getAgentsSourceDir: packageRoot must not be empty")
}
return join(packageRoot, "agents")
}
/**
* The target directory where agents are installed.
* Located at ~/.config/opencode/agents/
*/
export const AGENTS_TARGET_DIR = join(homedir(), ".config", "opencode", "agents")
/**
* Returns a user-friendly error message based on the error code.
*
* Translates Node.js filesystem error codes into human-readable messages
* that help users understand and resolve installation issues.
*
* @param {Error & {code?: string}} error - The error object from a failed fs operation
* @param {string} file - The filename being processed
* @param {string} targetPath - The target path for the file
* @returns {string} A helpful error message describing the issue and potential solution
*
* @example
* // Permission denied error
* const err = Object.assign(new Error(), { code: 'EACCES' })
* getErrorMessage(err, 'agent.md', '/home/user/.config/opencode/agents/agent.md')
* // Returns: "Permission denied. Check write permissions for /home/user/.config/opencode/agents"
*
* @example
* // File not found error
* const err = Object.assign(new Error(), { code: 'ENOENT' })
* getErrorMessage(err, 'missing.md', '/target/missing.md')
* // Returns: "Source file not found: missing.md"
*/
export function getErrorMessage(error, file, targetPath) {
if (typeof file !== "string") {
throw new TypeError(
`getErrorMessage: file must be a string, got ${file === null ? "null" : typeof file}`,
)
}
if (file.trim() === "") {
throw new TypeError("getErrorMessage: file must not be empty")
}
if (typeof targetPath !== "string") {
throw new TypeError(
`getErrorMessage: targetPath must be a string, got ${targetPath === null ? "null" : typeof targetPath}`,
)
}
if (targetPath.trim() === "") {
throw new TypeError("getErrorMessage: targetPath must not be empty")
}
const code = error.code
switch (code) {
case "EACCES":
return `Permission denied. Check write permissions for ${dirname(targetPath)}. Try: chmod u+w ${dirname(targetPath)} or run with sudo`
case "EPERM":
return "Operation not permitted. The file may be in use or locked. Try: lsof <file> to check what process is using it"
case "ENOSPC":
return "Disk full. Free up space and try again. Try: df -h to check disk usage"
case "ENOENT":
return `Source file not found: ${file}`
case "EROFS":
return "Read-only file system. Cannot write to target directory. Try: mount -o remount,rw <device> <mountpoint>"
case "EMFILE":
case "ENFILE":
return "Too many open files. Close some applications and try again"
case "EEXIST":
return `Target already exists: ${targetPath}`
case "EISDIR":
return `Expected a file but found a directory: ${targetPath}`
case "EAGAIN":
return "Resource temporarily unavailable. Try again"
case "EBUSY":
return "File is busy or locked. Try again later"
default:
return error.message || "Unknown error"
}
}
/** Error codes that indicate transient errors that may succeed on retry */
export const TRANSIENT_ERROR_CODES = ["EAGAIN", "EBUSY"]
/**
* Checks if an error is a transient error that may succeed on retry.
*
* @param {Error & {code?: string}} error - The error to check
* @returns {boolean} True if the error is transient, false for invalid input
*/
export function isTransientError(error) {
if (!error || typeof error.code !== "string") {
return false
}
return TRANSIENT_ERROR_CODES.includes(error.code)
}
/**
* Delays execution for the specified number of milliseconds.
*
* @param {number} ms - Milliseconds to wait
* @returns {Promise<void>}
*/
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
/**
* Retries a function on transient filesystem errors with exponential backoff.
*
* If the function throws a transient error (EAGAIN, EBUSY), it will be retried
* up to the specified number of times with exponentially increasing delays
* between attempts (e.g., 100ms, 200ms, 400ms).
*
* @template T
* @param {() => T | Promise<T>} fn - The function to execute
* @param {{ retries?: number, initialDelayMs?: number }} [options] - Retry options
* @returns {Promise<T>} The result of the function
* @throws {Error} The last error if all retries fail
*
* @example
* // Retry a file copy operation (delays: 100ms, 200ms, 400ms)
* await retryOnTransientError(() => copyFileSync(src, dest))
*
* @example
* // Custom retry options (delays: 50ms, 100ms, 200ms, 400ms, 800ms)
* await retryOnTransientError(
* () => unlinkSync(path),
* { retries: 5, initialDelayMs: 50 }
* )
*/
export async function retryOnTransientError(fn, options = {}) {
const { retries = 3, initialDelayMs = 100 } = options
// Sanitize initialDelayMs: clamp negative to 0, handle NaN by using default
const sanitizedDelayMs = Number.isNaN(initialDelayMs)
? 100
: Math.max(0, initialDelayMs)
// Sanitize retries: clamp negative to 0, handle NaN by using default
const sanitizedRetries = Number.isNaN(retries) ? 3 : Math.max(0, retries)
let lastError
for (let attempt = 0; attempt <= sanitizedRetries; attempt++) {
try {
return await fn()
} catch (err) {
lastError = err
const isTransient = isTransientError(err)
// If not a transient error or last attempt, throw immediately
if (!isTransient || attempt === sanitizedRetries) {
throw err
}
// Calculate exponential backoff delay: sanitizedDelayMs * 2^attempt
const backoffDelay = sanitizedDelayMs * 2 ** attempt
await delay(backoffDelay)
}
}
// This should never be reached, but TypeScript needs it
throw lastError
}
/**
* Parses YAML frontmatter from markdown content.
*
* Expects frontmatter to be delimited by --- at the start of the file.
*
* @param {string} content - The file content to parse
* @returns {{ found: boolean, reason?: "missing" | "unclosed", fields: Record<string, string>, endIndex: number }} Parse result
* @throws {TypeError} If content is not a string
*/
export function parseFrontmatter(content) {
if (typeof content !== "string") {
throw new TypeError(
`parseFrontmatter: content must be a string, got ${content === null ? "null" : typeof content}`,
)
}
// Frontmatter must start at the beginning of the file
if (!content.startsWith("---")) {
return { found: false, reason: "missing", fields: {}, endIndex: 0 }
}
// Find the closing ---
const endMatch = content.indexOf("\n---", 3)
if (endMatch === -1) {
return { found: false, reason: "unclosed", fields: {}, endIndex: 0 }
}
// Extract frontmatter content (between the --- delimiters)
const frontmatterContent = content.slice(4, endMatch)
const fields = {}
// Parse simple key: value pairs
for (const line of frontmatterContent.split("\n")) {
const trimmed = line.trim()
if (!trimmed || trimmed.startsWith("#")) continue
const colonIndex = trimmed.indexOf(":")
if (colonIndex === -1) continue
const key = trimmed.slice(0, colonIndex).trim()
let value = trimmed.slice(colonIndex + 1).trim()
// Remove surrounding quotes if present
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1)
}
fields[key] = value
}
// endIndex points to the character after the closing ---\n
const endIndex = endMatch + 4
return { found: true, fields, endIndex }
}
/**
* Validates that agent content has a valid structure.
*
* Checks that the content:
* 1. Has YAML frontmatter with required fields (version, requires)
* 2. Starts with a markdown header (# ) after frontmatter
* 3. Contains at least MIN_CONTENT_LENGTH characters
* 4. Contains at least one of the expected keywords
*
* @param {string} content - The agent file content to validate
* @returns {{ valid: boolean, error?: string }} Validation result with optional error message
* @throws {TypeError} If content is not a string
*/
export function validateAgentContent(content) {
if (typeof content !== "string") {
throw new TypeError(
`validateAgentContent: content must be a string, got ${content === null ? "null" : typeof content}`,
)
}
// Check minimum length
if (content.length < MIN_CONTENT_LENGTH) {
return {
valid: false,
error: `File too short: ${content.length} characters (minimum ${MIN_CONTENT_LENGTH})`,
}
}
// Check for YAML frontmatter
const frontmatter = parseFrontmatter(content)
if (!frontmatter.found) {
const errorMessage =
frontmatter.reason === "unclosed"
? "Unclosed YAML frontmatter (missing closing ---)"
: "File missing YAML frontmatter (must start with ---)"
return {
valid: false,
error: errorMessage,
}
}
// Check for required frontmatter fields
const missingFields = REQUIRED_FRONTMATTER_FIELDS.filter((field) => !frontmatter.fields[field])
if (missingFields.length > 0) {
return {
valid: false,
error: `Frontmatter missing required fields: ${missingFields.join(", ")}`,
}
}
// Get content after frontmatter
const contentAfterFrontmatter = content.slice(frontmatter.endIndex).trimStart()
// Check for markdown header after frontmatter
if (!contentAfterFrontmatter.startsWith("# ")) {
return {
valid: false,
error: "File does not have a markdown header (# ) after frontmatter",
}
}
// Check for required keywords (case-insensitive)
const lowerContent = content.toLowerCase()
const hasKeyword = REQUIRED_KEYWORDS.some((keyword) => lowerContent.includes(keyword))
if (!hasKeyword) {
return {
valid: false,
error: `File missing required keywords: ${REQUIRED_KEYWORDS.join(", ")}`,
}
}
return { valid: true }
}
/**
* Parses command line flags for install/uninstall scripts.
*
* Recognizes the following flags:
* - `--dry-run`: Simulate the operation without making changes
* - `--verbose`: Enable verbose logging output
* - `--quiet`: Suppress non-error output (for CI environments)
* - `--force`: Overwrite existing files without prompting
* - `--help`: Display help information
*
* @param {string[]} argv - The command line arguments array (typically process.argv)
* @returns {{ dryRun: boolean, verbose: boolean, quiet: boolean, force: boolean, help: boolean }} Parsed flags
*
* @example
* // Parse process.argv
* const flags = parseCliFlags(process.argv)
* if (flags.help) {
* console.log("Usage: ...")
* process.exit(0)
* }
*
* @example
* // Parse custom arguments
* const flags = parseCliFlags(["node", "script.js", "--verbose", "--dry-run"])
* // flags = { dryRun: true, verbose: true, quiet: false, force: false, help: false }
* @throws {TypeError} If argv is not an array
*/
export function parseCliFlags(argv) {
if (!Array.isArray(argv)) {
throw new TypeError(
`parseCliFlags: argv must be an array, got ${argv === null ? "null" : typeof argv}`,
)
}
return {
dryRun: argv.includes("--dry-run"),
verbose: argv.includes("--verbose"),
quiet: argv.includes("--quiet"),
force: argv.includes("--force"),
help: argv.includes("--help"),
}
}
/**
* Creates a logger object with standard and verbose logging methods.
*
* The logger provides three methods:
* - `log(message)`: Logs to console.log unless quiet mode is enabled
* - `verbose(message)`: Only logs when verbose mode is enabled, prefixed with [VERBOSE]
* - `error(message)`: Always logs to console.error (never suppressed)
*
* @param {boolean} verbose - Whether verbose logging is enabled
* @param {boolean} [quiet=false] - Whether quiet mode is enabled (suppresses non-error output)
* @returns {{ log: (message: string) => void, verbose: (message: string) => void, error: (message: string) => void }} Logger object
*
* @example
* const logger = createLogger(true)
* logger.log("Installing agents...") // Always prints
* logger.verbose("Source: /path/to/src") // Prints: [VERBOSE] Source: /path/to/src
* logger.error("Failed to install") // Always prints to stderr
*
* @example
* const logger = createLogger(false)
* logger.log("Installing agents...") // Prints
* logger.verbose("Source: /path/to/src") // Does nothing (verbose disabled)
*
* @example
* const logger = createLogger(false, true) // quiet mode
* logger.log("Installing agents...") // Suppressed (quiet mode)
* logger.error("Failed to install") // Still prints (errors always shown)
*/
export function createLogger(verbose, quiet = false) {
if (typeof verbose !== "boolean") {
throw new TypeError(
`createLogger: verbose must be a boolean, got ${verbose === null ? "null" : typeof verbose}`,
)
}
if (typeof quiet !== "boolean") {
throw new TypeError(
`createLogger: quiet must be a boolean, got ${quiet === null ? "null" : typeof quiet}`,
)
}
return {
log: (message) => {
if (!quiet) {
console.log(message)
}
},
verbose: (message) => {
if (verbose && !quiet) {
console.log(`[VERBOSE] ${message}`)
}
},
error: (message) => console.error(message),
}
}
/**
* Validates an agent file by reading and validating its content,
* including version compatibility checking.
*
* Performs the following validations:
* 1. Content structure validation (frontmatter, headers, keywords)
* 2. Version compatibility checking against current OpenCode version (unless force=true)
*
* @param {string} filePath - Path to the agent file to validate
* @param {string} [currentVersion] - The current OpenCode version to check against (defaults to OPENCODE_VERSION)
* @param {boolean} [force=false] - When true, skip version compatibility checks
* @returns {{ valid: boolean, error?: string, skippedVersionCheck?: boolean }} Validation result with optional error message
* @throws {Error} If the file does not exist (ENOENT)
* @throws {Error} If permission is denied reading the file (EACCES)
* @throws {Error} If the file is a directory (EISDIR)
* @throws {TypeError} If filePath is not a non-empty string
*
* @example
* // Validate an agent file
* const result = validateAgentFile('/path/to/agent.md')
* if (!result.valid) {
* console.error(`Validation failed: ${result.error}`)
* }
*
* @example
* // Use in a file copy loop
* for (const file of agentFiles) {
* const validation = validateAgentFile(join(sourceDir, file))
* if (validation.valid) {
* copyFileSync(join(sourceDir, file), join(targetDir, file))
* }
* }
*
* @example
* // Validate against a specific version
* const result = validateAgentFile('/path/to/agent.md', '1.0.0')
*
* @example
* // Force install, skipping version compatibility check
* const result = validateAgentFile('/path/to/agent.md', '1.0.0', true)
* if (result.skippedVersionCheck) {
* console.warn('Warning: Version compatibility check was skipped')
* }
*/
export function validateAgentFile(filePath, currentVersion = OPENCODE_VERSION, force = false) {
if (typeof filePath !== "string") {
throw new TypeError(
`validateAgentFile: filePath must be a string, got ${filePath === null ? "null" : typeof filePath}`,
)
}
if (filePath.trim() === "") {
throw new TypeError("validateAgentFile: filePath must not be empty")
}
const content = readFileSync(filePath, "utf-8")
const contentValidation = validateAgentContent(content)
if (!contentValidation.valid) {
return contentValidation
}
// Check version compatibility from frontmatter (unless force is true)
const frontmatter = parseFrontmatter(content)
if (frontmatter.found && frontmatter.fields.requires) {
const requiresVersion = frontmatter.fields.requires
const isCompatible = _checkVersionCompatibility(requiresVersion, currentVersion)
if (!isCompatible) {
if (force) {
// Skip version check when force is enabled, but indicate it was skipped
return { valid: true, skippedVersionCheck: true }
}
return {
valid: false,
error: `Incompatible OpenCode version: requires ${requiresVersion}, but current version is ${currentVersion}`,
}
}
}
return { valid: true }
}