@sockulags/agent-os 0.9.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cli/index.mjs CHANGED
@@ -1,735 +1,735 @@
1
- #!/usr/bin/env node
2
-
3
- import { spawnSync } from 'node:child_process'
4
- import { randomUUID } from 'node:crypto'
5
- import fs from 'node:fs'
6
- import os from 'node:os'
7
- import path from 'node:path'
8
- import { createInterface } from 'node:readline'
9
- import { fileURLToPath, pathToFileURL } from 'node:url'
10
-
11
- const packageRoot = fileURLToPath(new URL('../', import.meta.url))
12
- const packagePath = path.join(packageRoot, 'package.json')
13
- const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'))
14
-
15
- export const VERSION = packageJson.version
16
- export const PACKAGE_NAME = packageJson.name
17
- export const MARKETPLACE_SOURCE = 'sockulags/agent-os'
18
- export const INSTALL_MANIFEST = '.agent-os-install.json'
19
-
20
- const BEGIN_MARKER = '<!-- BEGIN AGENT OS -->'
21
- const END_MARKER = '<!-- END AGENT OS -->'
22
- const PLATFORM_VALUES = ['claude', 'codex', 'both']
23
- const METHOD_VALUES = ['direct', 'plugin']
24
- const SCOPE_VALUES = ['user', 'project', 'local']
25
-
26
- export const PLATFORM_CONFIG = Object.freeze({
27
- claude: Object.freeze({
28
- label: 'Claude Code',
29
- command: 'claude',
30
- marketplace: 'agent-os-marketplace',
31
- installArgs: ['plugin', 'marketplace', 'add', MARKETPLACE_SOURCE],
32
- refreshArgs: ['plugin', 'marketplace', 'update', 'agent-os-marketplace'],
33
- pluginArgs: (scope) => ['plugin', 'install', 'agent-os@agent-os-marketplace', '--scope', scope],
34
- nextStep: 'Restart Claude Code or run /reload-plugins.'
35
- }),
36
- codex: Object.freeze({
37
- label: 'Codex',
38
- command: 'codex',
39
- marketplace: 'agent-os',
40
- installArgs: ['plugin', 'marketplace', 'add', MARKETPLACE_SOURCE],
41
- refreshArgs: ['plugin', 'marketplace', 'upgrade', 'agent-os'],
42
- pluginArgs: () => ['plugin', 'add', 'agent-os@agent-os'],
43
- nextStep: 'Start a new Codex session so the refreshed plugin is loaded.'
44
- })
45
- })
46
-
47
- export class CliError extends Error {}
48
-
49
- function valueAfter(args, index, flag) {
50
- const value = args[index + 1]
51
- if (!value || value.startsWith('-')) throw new CliError(flag + ' requires a value.')
52
- return value
53
- }
54
-
55
- function normalizePlatform(value) {
56
- const normalized = value.toLowerCase()
57
- if (normalized === 'claude-code') return 'claude'
58
- if (!PLATFORM_VALUES.includes(normalized)) {
59
- throw new CliError('Platform must be claude, codex, or both.')
60
- }
61
- return normalized
62
- }
63
-
64
- function normalizeMethod(value) {
65
- const normalized = value.toLowerCase()
66
- if (!METHOD_VALUES.includes(normalized)) {
67
- throw new CliError('Method must be direct or plugin.')
68
- }
69
- return normalized
70
- }
71
-
72
- function normalizeScope(value) {
73
- const normalized = value.toLowerCase()
74
- if (!SCOPE_VALUES.includes(normalized)) {
75
- throw new CliError('Scope must be user, project, or local.')
76
- }
77
- return normalized
78
- }
79
-
80
- export function parseArgs(argv) {
81
- const result = {
82
- command: 'install',
83
- platform: null,
84
- method: null,
85
- scope: null,
86
- policy: null,
87
- yes: false,
88
- dryRun: false,
89
- help: false,
90
- version: false
91
- }
92
-
93
- let index = 0
94
- if (argv[0] && !argv[0].startsWith('-')) {
95
- result.command = argv[0].toLowerCase()
96
- index = 1
97
- }
98
-
99
- if (result.command === 'upgrade') result.command = 'update'
100
- if (!['install', 'update', 'help'].includes(result.command)) {
101
- throw new CliError('Unknown command "' + result.command + '". Use install or update.')
102
- }
103
-
104
- while (index < argv.length) {
105
- const argument = argv[index]
106
- if (argument === '--help' || argument === '-h') {
107
- result.help = true
108
- } else if (argument === '--version' || argument === '-v') {
109
- result.version = true
110
- } else if (argument === '--yes' || argument === '-y') {
111
- result.yes = true
112
- } else if (argument === '--dry-run') {
113
- result.dryRun = true
114
- } else if (argument === '--policy') {
115
- if (result.policy === false) throw new CliError('Use only one of --policy and --no-policy.')
116
- result.policy = true
117
- } else if (argument === '--no-policy') {
118
- if (result.policy === true) throw new CliError('Use only one of --policy and --no-policy.')
119
- result.policy = false
120
- } else if (argument === '--platform' || argument === '-p') {
121
- result.platform = normalizePlatform(valueAfter(argv, index, argument))
122
- index += 1
123
- } else if (argument.startsWith('--platform=')) {
124
- result.platform = normalizePlatform(argument.slice('--platform='.length))
125
- } else if (argument === '--method' || argument === '-m') {
126
- result.method = normalizeMethod(valueAfter(argv, index, argument))
127
- index += 1
128
- } else if (argument.startsWith('--method=')) {
129
- result.method = normalizeMethod(argument.slice('--method='.length))
130
- } else if (argument === '--scope' || argument === '-s') {
131
- result.scope = normalizeScope(valueAfter(argv, index, argument))
132
- index += 1
133
- } else if (argument.startsWith('--scope=')) {
134
- result.scope = normalizeScope(argument.slice('--scope='.length))
135
- } else {
136
- throw new CliError('Unknown option "' + argument + '". Use --help for usage.')
137
- }
138
- index += 1
139
- }
140
-
141
- return result
142
- }
143
-
144
- export function selectedPlatforms(platform) {
145
- if (platform === 'both') return ['claude', 'codex']
146
- return [platform]
147
- }
148
-
149
- export function targetSkillRoot(platform, scope, {
150
- homeDir = os.homedir(),
151
- cwd = process.cwd()
152
- } = {}) {
153
- if (scope === 'user') {
154
- return platform === 'codex'
155
- ? path.join(homeDir, '.codex', 'skills')
156
- : path.join(homeDir, '.claude', 'skills')
157
- }
158
- if (scope === 'project') {
159
- return platform === 'codex'
160
- ? path.join(cwd, '.agents', 'skills')
161
- : path.join(cwd, '.claude', 'skills')
162
- }
163
- throw new CliError('Local scope is available only with --method plugin.')
164
- }
165
-
166
- export function buildPlan(options, pathOptions = {}) {
167
- const { command, platform, method = 'direct', scope = 'user', policy = true } = options
168
- const steps = []
169
- for (const name of selectedPlatforms(platform)) {
170
- const config = PLATFORM_CONFIG[name]
171
- if (method === 'direct') {
172
- const root = targetSkillRoot(name, scope, pathOptions)
173
- steps.push({
174
- platform: name,
175
- kind: command === 'update' ? 'update-skills' : 'install-skills',
176
- command: 'filesystem',
177
- args: [root],
178
- description: (command === 'update' ? 'Update' : 'Install') +
179
- ' Agent OS managed skills for ' + config.label + '.'
180
- })
181
- continue
182
- }
183
-
184
- steps.push({
185
- platform: name,
186
- kind: 'ensure-marketplace',
187
- command: config.command,
188
- args: ['plugin', 'marketplace', 'list', '--json'],
189
- description: 'Check whether the ' + config.label + ' marketplace is registered.'
190
- })
191
- steps.push({
192
- platform: name,
193
- kind: 'add-marketplace-if-missing',
194
- command: config.command,
195
- args: config.installArgs,
196
- description: 'Register the Agent OS marketplace when it is not present.'
197
- })
198
- if (command === 'update') {
199
- steps.push({
200
- platform: name,
201
- kind: 'refresh-marketplace',
202
- command: config.command,
203
- args: config.refreshArgs,
204
- description: 'Refresh the Agent OS Git marketplace when applicable.'
205
- })
206
- }
207
- steps.push({
208
- platform: name,
209
- kind: 'install-plugin',
210
- command: config.command,
211
- args: config.pluginArgs(scope),
212
- description: command === 'update'
213
- ? 'Install the current Agent OS plugin snapshot.'
214
- : 'Install the Agent OS plugin.'
215
- })
216
- }
217
- if (policy) {
218
- steps.push({
219
- platform: 'shared',
220
- kind: 'install-policy',
221
- command: 'node',
222
- args: [],
223
- description: 'Sync the shared global policy for Claude Code and Codex.'
224
- })
225
- }
226
- return steps
227
- }
228
-
229
- function commandExists(command, spawn = spawnSync) {
230
- const lookup = process.platform === 'win32' ? 'where.exe' : 'which'
231
- const result = spawn(lookup, [command], { stdio: 'ignore' })
232
- return result.status === 0
233
- }
234
-
235
- function runExternal(command, args, { capture = false, spawn = spawnSync } = {}) {
236
- const options = capture
237
- ? { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }
238
- : { stdio: 'inherit' }
239
- if (process.platform === 'win32') options.shell = true
240
- const result = spawn(command, args, options)
241
- return {
242
- status: result.status ?? 1,
243
- stdout: result.stdout ?? '',
244
- stderr: result.stderr ?? '',
245
- error: result.error
246
- }
247
- }
248
-
249
- function marketplacePresent(value, marketplaceName) {
250
- if (Array.isArray(value)) return value.some((item) => marketplacePresent(item, marketplaceName))
251
- if (!value || typeof value !== 'object') return false
252
- if (value.name === marketplaceName || value.marketplaceName === marketplaceName) return true
253
- return Object.values(value).some((item) => marketplacePresent(item, marketplaceName))
254
- }
255
-
256
- function marketplaceSourceType(value, marketplaceName) {
257
- if (Array.isArray(value)) {
258
- for (const item of value) {
259
- const result = marketplaceSourceType(item, marketplaceName)
260
- if (result) return result
261
- }
262
- return null
263
- }
264
- if (!value || typeof value !== 'object') return null
265
- if (value.marketplaceName === marketplaceName && value.marketplaceSource?.sourceType) {
266
- return value.marketplaceSource.sourceType
267
- }
268
- for (const item of Object.values(value)) {
269
- const result = marketplaceSourceType(item, marketplaceName)
270
- if (result) return result
271
- }
272
- return null
273
- }
274
-
275
- function formatCommand(command, args) {
276
- return [command, ...args].join(' ')
277
- }
278
-
279
- function assertSuccess(result, command, args) {
280
- if (result.status === 0) return
281
- const detail = result.error?.message || result.stderr?.trim()
282
- throw new CliError(
283
- 'Command failed (' + result.status + '): ' + formatCommand(command, args) +
284
- (detail ? '\n' + detail : '')
285
- )
286
- }
287
-
288
- async function ask(question, { input, output }) {
289
- const readline = createInterface({ input, output })
290
- const answer = await new Promise((resolve) => readline.question(question, resolve))
291
- readline.close()
292
- return answer.trim()
293
- }
294
-
295
- async function choose(question, choices, dependencies) {
296
- dependencies.output.write('\n' + question + '\n')
297
- choices.forEach((choice, index) => {
298
- dependencies.output.write(' ' + (index + 1) + ') ' + choice.label + '\n')
299
- })
300
- while (true) {
301
- const answer = await ask('Choose 1-' + choices.length + ': ', dependencies)
302
- const selected = Number.parseInt(answer, 10)
303
- if (selected >= 1 && selected <= choices.length) return choices[selected - 1].value
304
- dependencies.output.write('Please choose one of the listed numbers.\n')
305
- }
306
- }
307
-
308
- async function confirm(question, dependencies, defaultValue = true) {
309
- const suffix = defaultValue ? ' [Y/n] ' : ' [y/N] '
310
- const answer = (await ask(question + suffix, dependencies)).toLowerCase()
311
- if (!answer) return defaultValue
312
- return answer === 'y' || answer === 'yes'
313
- }
314
-
315
- export async function resolveOptions(parsed, {
316
- input = process.stdin,
317
- output = process.stdout
318
- } = {}) {
319
- const dependencies = { input, output }
320
- const interactive = Boolean(input.isTTY && output.isTTY)
321
- if (!interactive && !parsed.yes && !parsed.dryRun) {
322
- throw new CliError('This command needs a terminal or --yes with explicit options.')
323
- }
324
-
325
- let platform = parsed.platform
326
- if (!platform) {
327
- if (!interactive) throw new CliError('Choose a platform with --platform claude, codex, or both.')
328
- platform = await choose('Where should Agent OS be installed?', [
329
- { value: 'codex', label: 'Codex' },
330
- { value: 'claude', label: 'Claude Code' },
331
- { value: 'both', label: 'Both' }
332
- ], dependencies)
333
- }
334
-
335
- let method = parsed.method
336
- if (!method) {
337
- method = interactive && !parsed.yes
338
- ? await choose('How should Agent OS be installed?', [
339
- { value: 'direct', label: 'Direct skills (recommended; no host CLI required)' },
340
- { value: 'plugin', label: 'Native plugin marketplace' }
341
- ], dependencies)
342
- : 'direct'
343
- }
344
-
345
- let scope = parsed.scope || 'user'
346
- if (!parsed.scope && interactive && !parsed.yes) {
347
- if (method === 'direct') {
348
- scope = await choose('Where should the skill files live?', [
349
- { value: 'user', label: 'User (recommended; available across projects)' },
350
- { value: 'project', label: 'Project (stored in this repository)' }
351
- ], dependencies)
352
- } else if (platform !== 'codex') {
353
- scope = await choose('What Claude Code plugin scope should be used?', [
354
- { value: 'user', label: 'User (recommended; available across projects)' },
355
- { value: 'project', label: 'Project (shared through this repository)' },
356
- { value: 'local', label: 'Local (this repository for you only)' }
357
- ], dependencies)
358
- }
359
- }
360
- if (method === 'direct' && scope === 'local') {
361
- throw new CliError('Local scope is available only with --method plugin. Use user or project.')
362
- }
363
-
364
- let policy = parsed.policy
365
- if (policy === null) {
366
- policy = interactive && !parsed.yes
367
- ? await confirm('Also sync the shared global policy files?', dependencies, true)
368
- : true
369
- }
370
-
371
- return { ...parsed, platform, method, scope, policy }
372
- }
373
-
374
- function packagedSkillsPath() {
375
- return path.join(packageRoot, 'skills')
376
- }
377
-
378
- function packagedPolicyPath() {
379
- return path.join(packageRoot, 'policy.md')
380
- }
381
-
382
- function listPackagedSkills(sourceRoot, fsImpl = fs) {
383
- if (!fsImpl.existsSync(sourceRoot)) {
384
- throw new CliError('Packaged skills directory is missing: ' + sourceRoot)
385
- }
386
- const entries = fsImpl.readdirSync(sourceRoot, { withFileTypes: true })
387
- .filter((entry) => entry.isDirectory() && fsImpl.existsSync(path.join(sourceRoot, entry.name, 'SKILL.md')))
388
- .map((entry) => entry.name)
389
- .sort()
390
- if (entries.length === 0) throw new CliError('No packaged skills were found in ' + sourceRoot)
391
- return entries
392
- }
393
-
394
- function readInstallManifest(root, fsImpl = fs) {
395
- const manifestPath = path.join(root, INSTALL_MANIFEST)
396
- if (!fsImpl.existsSync(manifestPath)) return null
397
- let manifest
398
- try {
399
- manifest = JSON.parse(fsImpl.readFileSync(manifestPath, 'utf8'))
400
- } catch (error) {
401
- throw new CliError('Cannot read Agent OS install manifest at ' + manifestPath + ': ' + error.message)
402
- }
403
- if (manifest.package !== PACKAGE_NAME || !Array.isArray(manifest.skills)) {
404
- throw new CliError('Refusing to use an unrecognized install manifest at ' + manifestPath)
405
- }
406
- return manifest
407
- }
408
-
409
- function directTargets(options, { homeDir, cwd }) {
410
- return selectedPlatforms(options.platform).map((platform) => ({
411
- platform,
412
- scope: options.scope,
413
- root: targetSkillRoot(platform, options.scope, { homeDir, cwd })
414
- }))
415
- }
416
-
417
- function preflightDirectTarget(target, skillNames, fsImpl = fs) {
418
- const manifest = readInstallManifest(target.root, fsImpl)
419
- const managed = new Set(manifest?.skills || [])
420
- const conflicts = skillNames.filter((name) => {
421
- const destination = path.join(target.root, name)
422
- return fsImpl.existsSync(destination) && !managed.has(name)
423
- })
424
- if (conflicts.length > 0) {
425
- throw new CliError(
426
- 'Refusing to overwrite unmanaged skills in ' + target.root + ': ' + conflicts.join(', ') +
427
- '. Move or remove them, then rerun the installer.'
428
- )
429
- }
430
- return manifest
431
- }
432
-
433
- function replaceManagedSkills(target, sourceRoot, skillNames, previousManifest, fsImpl = fs) {
434
- fsImpl.mkdirSync(target.root, { recursive: true })
435
- const token = randomUUID()
436
- const stageRoot = path.join(target.root, '.agent-os-stage-' + token)
437
- const backupRoot = path.join(target.root, '.agent-os-backup-' + token)
438
- const previousNames = previousManifest?.skills || []
439
- const namesToBackup = [...new Set([...previousNames, ...skillNames])]
440
- .filter((name) => fsImpl.existsSync(path.join(target.root, name)))
441
- const installed = []
442
- const backedUp = []
443
- const manifestPath = path.join(target.root, INSTALL_MANIFEST)
444
- const previousManifestText = fsImpl.existsSync(manifestPath)
445
- ? fsImpl.readFileSync(manifestPath, 'utf8')
446
- : null
447
-
448
- try {
449
- fsImpl.mkdirSync(stageRoot, { recursive: true })
450
- for (const name of skillNames) {
451
- fsImpl.cpSync(path.join(sourceRoot, name), path.join(stageRoot, name), { recursive: true })
452
- }
453
-
454
- if (namesToBackup.length > 0) fsImpl.mkdirSync(backupRoot, { recursive: true })
455
- for (const name of namesToBackup) {
456
- fsImpl.renameSync(path.join(target.root, name), path.join(backupRoot, name))
457
- backedUp.push(name)
458
- }
459
-
460
- for (const name of skillNames) {
461
- fsImpl.renameSync(path.join(stageRoot, name), path.join(target.root, name))
462
- installed.push(name)
463
- }
464
-
465
- const manifest = {
466
- schemaVersion: 1,
467
- package: PACKAGE_NAME,
468
- version: VERSION,
469
- platform: target.platform,
470
- scope: target.scope,
471
- skills: skillNames
472
- }
473
- fsImpl.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
474
- } catch (error) {
475
- for (const name of installed.reverse()) {
476
- const destination = path.join(target.root, name)
477
- if (fsImpl.existsSync(destination)) fsImpl.rmSync(destination, { recursive: true, force: true })
478
- }
479
- for (const name of backedUp.reverse()) {
480
- const backup = path.join(backupRoot, name)
481
- if (fsImpl.existsSync(backup)) fsImpl.renameSync(backup, path.join(target.root, name))
482
- }
483
- if (previousManifestText === null) {
484
- if (fsImpl.existsSync(manifestPath)) fsImpl.rmSync(manifestPath, { force: true })
485
- } else {
486
- fsImpl.writeFileSync(manifestPath, previousManifestText)
487
- }
488
- throw new CliError('Failed to update managed skills in ' + target.root + ': ' + error.message)
489
- } finally {
490
- if (fsImpl.existsSync(stageRoot)) fsImpl.rmSync(stageRoot, { recursive: true, force: true })
491
- if (fsImpl.existsSync(backupRoot)) fsImpl.rmSync(backupRoot, { recursive: true, force: true })
492
- }
493
- }
494
-
495
- function executeDirect(options, {
496
- output,
497
- fsImpl,
498
- homeDir,
499
- cwd,
500
- sourceRoot
501
- }) {
502
- const skillNames = listPackagedSkills(sourceRoot, fsImpl)
503
- const targets = directTargets(options, { homeDir, cwd })
504
- const manifests = targets.map((target) => preflightDirectTarget(target, skillNames, fsImpl))
505
-
506
- targets.forEach((target, index) => {
507
- const config = PLATFORM_CONFIG[target.platform]
508
- output.write('\n[' + config.label + ']\n')
509
- output.write((options.command === 'update' ? 'Updating' : 'Installing') +
510
- ' ' + skillNames.length + ' managed skills in ' + target.root + '...\n')
511
- replaceManagedSkills(target, sourceRoot, skillNames, manifests[index], fsImpl)
512
- output.write('Done. Start a new ' + config.label + ' session to load the skills.\n')
513
- })
514
- }
515
-
516
- function isNotGitMarketplace(result) {
517
- return result.status !== 0 && /not configured as a Git marketplace/i.test(result.stderr || '')
518
- }
519
-
520
- function executePlugin(options, { output, execute, exists }) {
521
- const names = selectedPlatforms(options.platform)
522
- const missing = names.filter((name) => !exists(PLATFORM_CONFIG[name].command))
523
- if (missing.length > 0) {
524
- const details = missing.map((name) => {
525
- const config = PLATFORM_CONFIG[name]
526
- const hint = name === 'claude'
527
- ? 'npm install -g @anthropic-ai/claude-code'
528
- : 'npm install -g @openai/codex'
529
- return config.label + ': ' + hint
530
- })
531
- throw new CliError('Native plugin mode requires the selected host CLIs:\n' + details.join('\n'))
532
- }
533
-
534
- for (const name of names) {
535
- const config = PLATFORM_CONFIG[name]
536
- output.write('\n[' + config.label + ']\n')
537
- const listed = execute(config.command, ['plugin', 'marketplace', 'list', '--json'], { capture: true })
538
- let registered = false
539
- if (listed.status === 0) {
540
- try {
541
- registered = marketplacePresent(JSON.parse(listed.stdout), config.marketplace)
542
- } catch {
543
- registered = false
544
- }
545
- }
546
- if (!registered) {
547
- output.write('Registering the Agent OS marketplace...\n')
548
- assertSuccess(execute(config.command, config.installArgs), config.command, config.installArgs)
549
- } else {
550
- output.write('Agent OS marketplace is already registered.\n')
551
- }
552
-
553
- if (options.command === 'update') {
554
- let sourceType = null
555
- if (name === 'codex' && registered) {
556
- const plugins = execute(config.command, ['plugin', 'list', '--json'], { capture: true })
557
- if (plugins.status === 0) {
558
- try {
559
- sourceType = marketplaceSourceType(JSON.parse(plugins.stdout), config.marketplace)
560
- } catch {
561
- sourceType = null
562
- }
563
- }
564
- }
565
- if (sourceType === 'local') {
566
- output.write('Local marketplace detected; skipping Git refresh.\n')
567
- } else {
568
- output.write('Refreshing the Agent OS marketplace...\n')
569
- const refreshed = execute(config.command, config.refreshArgs, { capture: name === 'codex' })
570
- if (isNotGitMarketplace(refreshed)) {
571
- output.write('Local marketplace detected; skipping Git refresh.\n')
572
- } else {
573
- assertSuccess(refreshed, config.command, config.refreshArgs)
574
- }
575
- }
576
- }
577
-
578
- const pluginArgs = config.pluginArgs(options.scope)
579
- output.write(options.command === 'update'
580
- ? 'Installing the current plugin snapshot...\n'
581
- : 'Installing the plugin...\n')
582
- assertSuccess(execute(config.command, pluginArgs), config.command, pluginArgs)
583
- output.write('Done. ' + config.nextStep + '\n')
584
- }
585
- }
586
-
587
- function countOccurrences(content, value) {
588
- return content.split(value).length - 1
589
- }
590
-
591
- export function planPolicyUpdate(content, policy) {
592
- const normalizedPolicy = policy.trimEnd()
593
- const block = BEGIN_MARKER + '\n' + normalizedPolicy + '\n' + END_MARKER
594
- const beginCount = countOccurrences(content, BEGIN_MARKER)
595
- const endCount = countOccurrences(content, END_MARKER)
596
-
597
- if (beginCount === 0 && endCount === 0) {
598
- const separator = content.length === 0 ? '' : content.endsWith('\n') ? '\n' : '\n\n'
599
- return { changed: true, status: 'ADDED', content: content + separator + block + '\n' }
600
- }
601
-
602
- const start = content.indexOf(BEGIN_MARKER)
603
- const endStart = content.indexOf(END_MARKER)
604
- if (beginCount !== 1 || endCount !== 1 || start >= endStart) {
605
- throw new CliError(
606
- 'Malformed Agent OS policy markers (begin=' + beginCount + ' end=' + endCount + '); no files were changed.'
607
- )
608
- }
609
-
610
- const end = endStart + END_MARKER.length
611
- const current = content.slice(start, end)
612
- if (current === block) return { changed: false, status: 'OK', content }
613
- return {
614
- changed: true,
615
- status: 'UPDATED',
616
- content: content.slice(0, start) + block + content.slice(end)
617
- }
618
- }
619
-
620
- function preparePolicyPlans({ fsImpl, homeDir, policyFile }) {
621
- const policy = fsImpl.readFileSync(policyFile, 'utf8')
622
- const targets = [
623
- path.join(homeDir, '.claude', 'CLAUDE.md'),
624
- path.join(homeDir, '.codex', 'AGENTS.md')
625
- ]
626
- return targets.map((target) => {
627
- const content = fsImpl.existsSync(target) ? fsImpl.readFileSync(target, 'utf8') : ''
628
- return { target, ...planPolicyUpdate(content, policy) }
629
- })
630
- }
631
-
632
- function applyPolicyPlans(plans, { output, fsImpl }) {
633
- for (const plan of plans) {
634
- if (plan.changed) {
635
- fsImpl.mkdirSync(path.dirname(plan.target), { recursive: true })
636
- fsImpl.writeFileSync(plan.target, plan.content)
637
- }
638
- output.write(plan.status.padEnd(7) + plan.target + '\n')
639
- }
640
- }
641
-
642
- export async function executeInstall(options, {
643
- output = process.stdout,
644
- spawn = spawnSync,
645
- execute = (command, args, runOptions) => runExternal(command, args, { ...runOptions, spawn }),
646
- exists = (command) => commandExists(command, spawn),
647
- fsImpl = fs,
648
- homeDir = os.homedir(),
649
- cwd = process.cwd(),
650
- sourceRoot = packagedSkillsPath(),
651
- policyFile = packagedPolicyPath()
652
- } = {}) {
653
- const policyPlans = options.policy
654
- ? preparePolicyPlans({ fsImpl, homeDir, policyFile })
655
- : null
656
-
657
- if (options.method === 'plugin') {
658
- executePlugin(options, { output, execute, exists })
659
- } else {
660
- executeDirect(options, { output, fsImpl, homeDir, cwd, sourceRoot })
661
- }
662
-
663
- if (options.policy) {
664
- output.write('\n[Shared policy]\nSyncing the global Claude Code and Codex policy files...\n')
665
- applyPolicyPlans(policyPlans, { output, fsImpl })
666
- }
667
- }
668
-
669
- export function printHelp(output = process.stdout) {
670
- output.write(
671
- 'Agent OS installer ' + VERSION + '\n\n' +
672
- 'Usage:\n' +
673
- ' npx ' + PACKAGE_NAME + ' install\n' +
674
- ' npx ' + PACKAGE_NAME + ' update\n\n' +
675
- 'Direct installation is the default and does not require Codex or Claude Code CLI.\n\n' +
676
- 'Options:\n' +
677
- ' -p, --platform <name> claude, codex, or both\n' +
678
- ' -m, --method <name> direct (default) or plugin\n' +
679
- ' -s, --scope <name> user or project; plugin mode also supports local\n' +
680
- ' --policy Sync ~/.claude/CLAUDE.md and ~/.codex/AGENTS.md\n' +
681
- ' --no-policy Leave global policy files unchanged\n' +
682
- ' -y, --yes Accept defaults; useful in scripts\n' +
683
- ' --dry-run Show the planned flow without running commands\n' +
684
- ' -h, --help Show this help\n' +
685
- ' -v, --version Show the CLI version\n\n' +
686
- 'Examples:\n' +
687
- ' npx ' + PACKAGE_NAME + ' install\n' +
688
- ' npx ' + PACKAGE_NAME + ' install --platform both --yes\n' +
689
- ' npx ' + PACKAGE_NAME + ' update --platform codex --no-policy\n' +
690
- ' npx ' + PACKAGE_NAME + ' install --platform codex --method plugin\n' +
691
- ' npm install --global ' + PACKAGE_NAME + '@latest\n'
692
- )
693
- }
694
-
695
- export function printPlan(options, output = process.stdout, pathOptions = {}) {
696
- output.write('Planned ' + options.command + ':\n')
697
- for (const step of buildPlan(options, pathOptions)) {
698
- const command = step.args.length ? formatCommand(step.command, step.args) : step.command
699
- output.write(' - ' + step.description + ' [' + command + ']\n')
700
- }
701
- }
702
-
703
- export async function run(argv = process.argv.slice(2), dependencies = {}) {
704
- const parsed = parseArgs(argv)
705
- if (parsed.help || parsed.command === 'help') {
706
- printHelp(dependencies.output || process.stdout)
707
- return 0
708
- }
709
- if (parsed.version) {
710
- (dependencies.output || process.stdout).write(VERSION + '\n')
711
- return 0
712
- }
713
- const options = await resolveOptions(parsed, dependencies)
714
- if (options.dryRun) {
715
- printPlan(options, dependencies.output || process.stdout, {
716
- homeDir: dependencies.homeDir,
717
- cwd: dependencies.cwd
718
- })
719
- return 0
720
- }
721
- await executeInstall(options, dependencies)
722
- const output = dependencies.output || process.stdout
723
- output.write('\nAgent OS ' + options.command + ' completed.\n')
724
- output.write('To update later, use npx ' + PACKAGE_NAME + '@latest update.\n')
725
- return 0
726
- }
727
-
728
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
729
- run().then((code) => {
730
- process.exitCode = code
731
- }).catch((error) => {
732
- console.error('Agent OS installer: ' + error.message)
733
- process.exitCode = 1
734
- })
735
- }
1
+ #!/usr/bin/env node
2
+
3
+ import { spawnSync } from 'node:child_process'
4
+ import { randomUUID } from 'node:crypto'
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import { createInterface } from 'node:readline'
9
+ import { fileURLToPath, pathToFileURL } from 'node:url'
10
+
11
+ const packageRoot = fileURLToPath(new URL('../', import.meta.url))
12
+ const packagePath = path.join(packageRoot, 'package.json')
13
+ const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'))
14
+
15
+ export const VERSION = packageJson.version
16
+ export const PACKAGE_NAME = packageJson.name
17
+ export const MARKETPLACE_SOURCE = 'sockulags/agent-os'
18
+ export const INSTALL_MANIFEST = '.agent-os-install.json'
19
+
20
+ const BEGIN_MARKER = '<!-- BEGIN AGENT OS -->'
21
+ const END_MARKER = '<!-- END AGENT OS -->'
22
+ const PLATFORM_VALUES = ['claude', 'codex', 'both']
23
+ const METHOD_VALUES = ['direct', 'plugin']
24
+ const SCOPE_VALUES = ['user', 'project', 'local']
25
+
26
+ export const PLATFORM_CONFIG = Object.freeze({
27
+ claude: Object.freeze({
28
+ label: 'Claude Code',
29
+ command: 'claude',
30
+ marketplace: 'agent-os-marketplace',
31
+ installArgs: ['plugin', 'marketplace', 'add', MARKETPLACE_SOURCE],
32
+ refreshArgs: ['plugin', 'marketplace', 'update', 'agent-os-marketplace'],
33
+ pluginArgs: (scope) => ['plugin', 'install', 'agent-os@agent-os-marketplace', '--scope', scope],
34
+ nextStep: 'Restart Claude Code or run /reload-plugins.'
35
+ }),
36
+ codex: Object.freeze({
37
+ label: 'Codex',
38
+ command: 'codex',
39
+ marketplace: 'agent-os',
40
+ installArgs: ['plugin', 'marketplace', 'add', MARKETPLACE_SOURCE],
41
+ refreshArgs: ['plugin', 'marketplace', 'upgrade', 'agent-os'],
42
+ pluginArgs: () => ['plugin', 'add', 'agent-os@agent-os'],
43
+ nextStep: 'Start a new Codex session so the refreshed plugin is loaded.'
44
+ })
45
+ })
46
+
47
+ export class CliError extends Error {}
48
+
49
+ function valueAfter(args, index, flag) {
50
+ const value = args[index + 1]
51
+ if (!value || value.startsWith('-')) throw new CliError(flag + ' requires a value.')
52
+ return value
53
+ }
54
+
55
+ function normalizePlatform(value) {
56
+ const normalized = value.toLowerCase()
57
+ if (normalized === 'claude-code') return 'claude'
58
+ if (!PLATFORM_VALUES.includes(normalized)) {
59
+ throw new CliError('Platform must be claude, codex, or both.')
60
+ }
61
+ return normalized
62
+ }
63
+
64
+ function normalizeMethod(value) {
65
+ const normalized = value.toLowerCase()
66
+ if (!METHOD_VALUES.includes(normalized)) {
67
+ throw new CliError('Method must be direct or plugin.')
68
+ }
69
+ return normalized
70
+ }
71
+
72
+ function normalizeScope(value) {
73
+ const normalized = value.toLowerCase()
74
+ if (!SCOPE_VALUES.includes(normalized)) {
75
+ throw new CliError('Scope must be user, project, or local.')
76
+ }
77
+ return normalized
78
+ }
79
+
80
+ export function parseArgs(argv) {
81
+ const result = {
82
+ command: 'install',
83
+ platform: null,
84
+ method: null,
85
+ scope: null,
86
+ policy: null,
87
+ yes: false,
88
+ dryRun: false,
89
+ help: false,
90
+ version: false
91
+ }
92
+
93
+ let index = 0
94
+ if (argv[0] && !argv[0].startsWith('-')) {
95
+ result.command = argv[0].toLowerCase()
96
+ index = 1
97
+ }
98
+
99
+ if (result.command === 'upgrade') result.command = 'update'
100
+ if (!['install', 'update', 'help'].includes(result.command)) {
101
+ throw new CliError('Unknown command "' + result.command + '". Use install or update.')
102
+ }
103
+
104
+ while (index < argv.length) {
105
+ const argument = argv[index]
106
+ if (argument === '--help' || argument === '-h') {
107
+ result.help = true
108
+ } else if (argument === '--version' || argument === '-v') {
109
+ result.version = true
110
+ } else if (argument === '--yes' || argument === '-y') {
111
+ result.yes = true
112
+ } else if (argument === '--dry-run') {
113
+ result.dryRun = true
114
+ } else if (argument === '--policy') {
115
+ if (result.policy === false) throw new CliError('Use only one of --policy and --no-policy.')
116
+ result.policy = true
117
+ } else if (argument === '--no-policy') {
118
+ if (result.policy === true) throw new CliError('Use only one of --policy and --no-policy.')
119
+ result.policy = false
120
+ } else if (argument === '--platform' || argument === '-p') {
121
+ result.platform = normalizePlatform(valueAfter(argv, index, argument))
122
+ index += 1
123
+ } else if (argument.startsWith('--platform=')) {
124
+ result.platform = normalizePlatform(argument.slice('--platform='.length))
125
+ } else if (argument === '--method' || argument === '-m') {
126
+ result.method = normalizeMethod(valueAfter(argv, index, argument))
127
+ index += 1
128
+ } else if (argument.startsWith('--method=')) {
129
+ result.method = normalizeMethod(argument.slice('--method='.length))
130
+ } else if (argument === '--scope' || argument === '-s') {
131
+ result.scope = normalizeScope(valueAfter(argv, index, argument))
132
+ index += 1
133
+ } else if (argument.startsWith('--scope=')) {
134
+ result.scope = normalizeScope(argument.slice('--scope='.length))
135
+ } else {
136
+ throw new CliError('Unknown option "' + argument + '". Use --help for usage.')
137
+ }
138
+ index += 1
139
+ }
140
+
141
+ return result
142
+ }
143
+
144
+ export function selectedPlatforms(platform) {
145
+ if (platform === 'both') return ['claude', 'codex']
146
+ return [platform]
147
+ }
148
+
149
+ export function targetSkillRoot(platform, scope, {
150
+ homeDir = os.homedir(),
151
+ cwd = process.cwd()
152
+ } = {}) {
153
+ if (scope === 'user') {
154
+ return platform === 'codex'
155
+ ? path.join(homeDir, '.codex', 'skills')
156
+ : path.join(homeDir, '.claude', 'skills')
157
+ }
158
+ if (scope === 'project') {
159
+ return platform === 'codex'
160
+ ? path.join(cwd, '.agents', 'skills')
161
+ : path.join(cwd, '.claude', 'skills')
162
+ }
163
+ throw new CliError('Local scope is available only with --method plugin.')
164
+ }
165
+
166
+ export function buildPlan(options, pathOptions = {}) {
167
+ const { command, platform, method = 'direct', scope = 'user', policy = true } = options
168
+ const steps = []
169
+ for (const name of selectedPlatforms(platform)) {
170
+ const config = PLATFORM_CONFIG[name]
171
+ if (method === 'direct') {
172
+ const root = targetSkillRoot(name, scope, pathOptions)
173
+ steps.push({
174
+ platform: name,
175
+ kind: command === 'update' ? 'update-skills' : 'install-skills',
176
+ command: 'filesystem',
177
+ args: [root],
178
+ description: (command === 'update' ? 'Update' : 'Install') +
179
+ ' Agent OS managed skills for ' + config.label + '.'
180
+ })
181
+ continue
182
+ }
183
+
184
+ steps.push({
185
+ platform: name,
186
+ kind: 'ensure-marketplace',
187
+ command: config.command,
188
+ args: ['plugin', 'marketplace', 'list', '--json'],
189
+ description: 'Check whether the ' + config.label + ' marketplace is registered.'
190
+ })
191
+ steps.push({
192
+ platform: name,
193
+ kind: 'add-marketplace-if-missing',
194
+ command: config.command,
195
+ args: config.installArgs,
196
+ description: 'Register the Agent OS marketplace when it is not present.'
197
+ })
198
+ if (command === 'update') {
199
+ steps.push({
200
+ platform: name,
201
+ kind: 'refresh-marketplace',
202
+ command: config.command,
203
+ args: config.refreshArgs,
204
+ description: 'Refresh the Agent OS Git marketplace when applicable.'
205
+ })
206
+ }
207
+ steps.push({
208
+ platform: name,
209
+ kind: 'install-plugin',
210
+ command: config.command,
211
+ args: config.pluginArgs(scope),
212
+ description: command === 'update'
213
+ ? 'Install the current Agent OS plugin snapshot.'
214
+ : 'Install the Agent OS plugin.'
215
+ })
216
+ }
217
+ if (policy) {
218
+ steps.push({
219
+ platform: 'shared',
220
+ kind: 'install-policy',
221
+ command: 'node',
222
+ args: [],
223
+ description: 'Sync the shared global policy for Claude Code and Codex.'
224
+ })
225
+ }
226
+ return steps
227
+ }
228
+
229
+ function commandExists(command, spawn = spawnSync) {
230
+ const lookup = process.platform === 'win32' ? 'where.exe' : 'which'
231
+ const result = spawn(lookup, [command], { stdio: 'ignore' })
232
+ return result.status === 0
233
+ }
234
+
235
+ function runExternal(command, args, { capture = false, spawn = spawnSync } = {}) {
236
+ const options = capture
237
+ ? { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }
238
+ : { stdio: 'inherit' }
239
+ if (process.platform === 'win32') options.shell = true
240
+ const result = spawn(command, args, options)
241
+ return {
242
+ status: result.status ?? 1,
243
+ stdout: result.stdout ?? '',
244
+ stderr: result.stderr ?? '',
245
+ error: result.error
246
+ }
247
+ }
248
+
249
+ function marketplacePresent(value, marketplaceName) {
250
+ if (Array.isArray(value)) return value.some((item) => marketplacePresent(item, marketplaceName))
251
+ if (!value || typeof value !== 'object') return false
252
+ if (value.name === marketplaceName || value.marketplaceName === marketplaceName) return true
253
+ return Object.values(value).some((item) => marketplacePresent(item, marketplaceName))
254
+ }
255
+
256
+ function marketplaceSourceType(value, marketplaceName) {
257
+ if (Array.isArray(value)) {
258
+ for (const item of value) {
259
+ const result = marketplaceSourceType(item, marketplaceName)
260
+ if (result) return result
261
+ }
262
+ return null
263
+ }
264
+ if (!value || typeof value !== 'object') return null
265
+ if (value.marketplaceName === marketplaceName && value.marketplaceSource?.sourceType) {
266
+ return value.marketplaceSource.sourceType
267
+ }
268
+ for (const item of Object.values(value)) {
269
+ const result = marketplaceSourceType(item, marketplaceName)
270
+ if (result) return result
271
+ }
272
+ return null
273
+ }
274
+
275
+ function formatCommand(command, args) {
276
+ return [command, ...args].join(' ')
277
+ }
278
+
279
+ function assertSuccess(result, command, args) {
280
+ if (result.status === 0) return
281
+ const detail = result.error?.message || result.stderr?.trim()
282
+ throw new CliError(
283
+ 'Command failed (' + result.status + '): ' + formatCommand(command, args) +
284
+ (detail ? '\n' + detail : '')
285
+ )
286
+ }
287
+
288
+ async function ask(question, { input, output }) {
289
+ const readline = createInterface({ input, output })
290
+ const answer = await new Promise((resolve) => readline.question(question, resolve))
291
+ readline.close()
292
+ return answer.trim()
293
+ }
294
+
295
+ async function choose(question, choices, dependencies) {
296
+ dependencies.output.write('\n' + question + '\n')
297
+ choices.forEach((choice, index) => {
298
+ dependencies.output.write(' ' + (index + 1) + ') ' + choice.label + '\n')
299
+ })
300
+ while (true) {
301
+ const answer = await ask('Choose 1-' + choices.length + ': ', dependencies)
302
+ const selected = Number.parseInt(answer, 10)
303
+ if (selected >= 1 && selected <= choices.length) return choices[selected - 1].value
304
+ dependencies.output.write('Please choose one of the listed numbers.\n')
305
+ }
306
+ }
307
+
308
+ async function confirm(question, dependencies, defaultValue = true) {
309
+ const suffix = defaultValue ? ' [Y/n] ' : ' [y/N] '
310
+ const answer = (await ask(question + suffix, dependencies)).toLowerCase()
311
+ if (!answer) return defaultValue
312
+ return answer === 'y' || answer === 'yes'
313
+ }
314
+
315
+ export async function resolveOptions(parsed, {
316
+ input = process.stdin,
317
+ output = process.stdout
318
+ } = {}) {
319
+ const dependencies = { input, output }
320
+ const interactive = Boolean(input.isTTY && output.isTTY)
321
+ if (!interactive && !parsed.yes && !parsed.dryRun) {
322
+ throw new CliError('This command needs a terminal or --yes with explicit options.')
323
+ }
324
+
325
+ let platform = parsed.platform
326
+ if (!platform) {
327
+ if (!interactive) throw new CliError('Choose a platform with --platform claude, codex, or both.')
328
+ platform = await choose('Where should Agent OS be installed?', [
329
+ { value: 'codex', label: 'Codex' },
330
+ { value: 'claude', label: 'Claude Code' },
331
+ { value: 'both', label: 'Both' }
332
+ ], dependencies)
333
+ }
334
+
335
+ let method = parsed.method
336
+ if (!method) {
337
+ method = interactive && !parsed.yes
338
+ ? await choose('How should Agent OS be installed?', [
339
+ { value: 'direct', label: 'Direct skills (recommended; no host CLI required)' },
340
+ { value: 'plugin', label: 'Native plugin marketplace' }
341
+ ], dependencies)
342
+ : 'direct'
343
+ }
344
+
345
+ let scope = parsed.scope || 'user'
346
+ if (!parsed.scope && interactive && !parsed.yes) {
347
+ if (method === 'direct') {
348
+ scope = await choose('Where should the skill files live?', [
349
+ { value: 'user', label: 'User (recommended; available across projects)' },
350
+ { value: 'project', label: 'Project (stored in this repository)' }
351
+ ], dependencies)
352
+ } else if (platform !== 'codex') {
353
+ scope = await choose('What Claude Code plugin scope should be used?', [
354
+ { value: 'user', label: 'User (recommended; available across projects)' },
355
+ { value: 'project', label: 'Project (shared through this repository)' },
356
+ { value: 'local', label: 'Local (this repository for you only)' }
357
+ ], dependencies)
358
+ }
359
+ }
360
+ if (method === 'direct' && scope === 'local') {
361
+ throw new CliError('Local scope is available only with --method plugin. Use user or project.')
362
+ }
363
+
364
+ let policy = parsed.policy
365
+ if (policy === null) {
366
+ policy = interactive && !parsed.yes
367
+ ? await confirm('Also sync the shared global policy files?', dependencies, true)
368
+ : true
369
+ }
370
+
371
+ return { ...parsed, platform, method, scope, policy }
372
+ }
373
+
374
+ function packagedSkillsPath() {
375
+ return path.join(packageRoot, 'skills')
376
+ }
377
+
378
+ function packagedPolicyPath() {
379
+ return path.join(packageRoot, 'policy.md')
380
+ }
381
+
382
+ function listPackagedSkills(sourceRoot, fsImpl = fs) {
383
+ if (!fsImpl.existsSync(sourceRoot)) {
384
+ throw new CliError('Packaged skills directory is missing: ' + sourceRoot)
385
+ }
386
+ const entries = fsImpl.readdirSync(sourceRoot, { withFileTypes: true })
387
+ .filter((entry) => entry.isDirectory() && fsImpl.existsSync(path.join(sourceRoot, entry.name, 'SKILL.md')))
388
+ .map((entry) => entry.name)
389
+ .sort()
390
+ if (entries.length === 0) throw new CliError('No packaged skills were found in ' + sourceRoot)
391
+ return entries
392
+ }
393
+
394
+ function readInstallManifest(root, fsImpl = fs) {
395
+ const manifestPath = path.join(root, INSTALL_MANIFEST)
396
+ if (!fsImpl.existsSync(manifestPath)) return null
397
+ let manifest
398
+ try {
399
+ manifest = JSON.parse(fsImpl.readFileSync(manifestPath, 'utf8'))
400
+ } catch (error) {
401
+ throw new CliError('Cannot read Agent OS install manifest at ' + manifestPath + ': ' + error.message)
402
+ }
403
+ if (manifest.package !== PACKAGE_NAME || !Array.isArray(manifest.skills)) {
404
+ throw new CliError('Refusing to use an unrecognized install manifest at ' + manifestPath)
405
+ }
406
+ return manifest
407
+ }
408
+
409
+ function directTargets(options, { homeDir, cwd }) {
410
+ return selectedPlatforms(options.platform).map((platform) => ({
411
+ platform,
412
+ scope: options.scope,
413
+ root: targetSkillRoot(platform, options.scope, { homeDir, cwd })
414
+ }))
415
+ }
416
+
417
+ function preflightDirectTarget(target, skillNames, fsImpl = fs) {
418
+ const manifest = readInstallManifest(target.root, fsImpl)
419
+ const managed = new Set(manifest?.skills || [])
420
+ const conflicts = skillNames.filter((name) => {
421
+ const destination = path.join(target.root, name)
422
+ return fsImpl.existsSync(destination) && !managed.has(name)
423
+ })
424
+ if (conflicts.length > 0) {
425
+ throw new CliError(
426
+ 'Refusing to overwrite unmanaged skills in ' + target.root + ': ' + conflicts.join(', ') +
427
+ '. Move or remove them, then rerun the installer.'
428
+ )
429
+ }
430
+ return manifest
431
+ }
432
+
433
+ function replaceManagedSkills(target, sourceRoot, skillNames, previousManifest, fsImpl = fs) {
434
+ fsImpl.mkdirSync(target.root, { recursive: true })
435
+ const token = randomUUID()
436
+ const stageRoot = path.join(target.root, '.agent-os-stage-' + token)
437
+ const backupRoot = path.join(target.root, '.agent-os-backup-' + token)
438
+ const previousNames = previousManifest?.skills || []
439
+ const namesToBackup = [...new Set([...previousNames, ...skillNames])]
440
+ .filter((name) => fsImpl.existsSync(path.join(target.root, name)))
441
+ const installed = []
442
+ const backedUp = []
443
+ const manifestPath = path.join(target.root, INSTALL_MANIFEST)
444
+ const previousManifestText = fsImpl.existsSync(manifestPath)
445
+ ? fsImpl.readFileSync(manifestPath, 'utf8')
446
+ : null
447
+
448
+ try {
449
+ fsImpl.mkdirSync(stageRoot, { recursive: true })
450
+ for (const name of skillNames) {
451
+ fsImpl.cpSync(path.join(sourceRoot, name), path.join(stageRoot, name), { recursive: true })
452
+ }
453
+
454
+ if (namesToBackup.length > 0) fsImpl.mkdirSync(backupRoot, { recursive: true })
455
+ for (const name of namesToBackup) {
456
+ fsImpl.renameSync(path.join(target.root, name), path.join(backupRoot, name))
457
+ backedUp.push(name)
458
+ }
459
+
460
+ for (const name of skillNames) {
461
+ fsImpl.renameSync(path.join(stageRoot, name), path.join(target.root, name))
462
+ installed.push(name)
463
+ }
464
+
465
+ const manifest = {
466
+ schemaVersion: 1,
467
+ package: PACKAGE_NAME,
468
+ version: VERSION,
469
+ platform: target.platform,
470
+ scope: target.scope,
471
+ skills: skillNames
472
+ }
473
+ fsImpl.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\n')
474
+ } catch (error) {
475
+ for (const name of installed.reverse()) {
476
+ const destination = path.join(target.root, name)
477
+ if (fsImpl.existsSync(destination)) fsImpl.rmSync(destination, { recursive: true, force: true })
478
+ }
479
+ for (const name of backedUp.reverse()) {
480
+ const backup = path.join(backupRoot, name)
481
+ if (fsImpl.existsSync(backup)) fsImpl.renameSync(backup, path.join(target.root, name))
482
+ }
483
+ if (previousManifestText === null) {
484
+ if (fsImpl.existsSync(manifestPath)) fsImpl.rmSync(manifestPath, { force: true })
485
+ } else {
486
+ fsImpl.writeFileSync(manifestPath, previousManifestText)
487
+ }
488
+ throw new CliError('Failed to update managed skills in ' + target.root + ': ' + error.message)
489
+ } finally {
490
+ if (fsImpl.existsSync(stageRoot)) fsImpl.rmSync(stageRoot, { recursive: true, force: true })
491
+ if (fsImpl.existsSync(backupRoot)) fsImpl.rmSync(backupRoot, { recursive: true, force: true })
492
+ }
493
+ }
494
+
495
+ function executeDirect(options, {
496
+ output,
497
+ fsImpl,
498
+ homeDir,
499
+ cwd,
500
+ sourceRoot
501
+ }) {
502
+ const skillNames = listPackagedSkills(sourceRoot, fsImpl)
503
+ const targets = directTargets(options, { homeDir, cwd })
504
+ const manifests = targets.map((target) => preflightDirectTarget(target, skillNames, fsImpl))
505
+
506
+ targets.forEach((target, index) => {
507
+ const config = PLATFORM_CONFIG[target.platform]
508
+ output.write('\n[' + config.label + ']\n')
509
+ output.write((options.command === 'update' ? 'Updating' : 'Installing') +
510
+ ' ' + skillNames.length + ' managed skills in ' + target.root + '...\n')
511
+ replaceManagedSkills(target, sourceRoot, skillNames, manifests[index], fsImpl)
512
+ output.write('Done. Start a new ' + config.label + ' session to load the skills.\n')
513
+ })
514
+ }
515
+
516
+ function isNotGitMarketplace(result) {
517
+ return result.status !== 0 && /not configured as a Git marketplace/i.test(result.stderr || '')
518
+ }
519
+
520
+ function executePlugin(options, { output, execute, exists }) {
521
+ const names = selectedPlatforms(options.platform)
522
+ const missing = names.filter((name) => !exists(PLATFORM_CONFIG[name].command))
523
+ if (missing.length > 0) {
524
+ const details = missing.map((name) => {
525
+ const config = PLATFORM_CONFIG[name]
526
+ const hint = name === 'claude'
527
+ ? 'npm install -g @anthropic-ai/claude-code'
528
+ : 'npm install -g @openai/codex'
529
+ return config.label + ': ' + hint
530
+ })
531
+ throw new CliError('Native plugin mode requires the selected host CLIs:\n' + details.join('\n'))
532
+ }
533
+
534
+ for (const name of names) {
535
+ const config = PLATFORM_CONFIG[name]
536
+ output.write('\n[' + config.label + ']\n')
537
+ const listed = execute(config.command, ['plugin', 'marketplace', 'list', '--json'], { capture: true })
538
+ let registered = false
539
+ if (listed.status === 0) {
540
+ try {
541
+ registered = marketplacePresent(JSON.parse(listed.stdout), config.marketplace)
542
+ } catch {
543
+ registered = false
544
+ }
545
+ }
546
+ if (!registered) {
547
+ output.write('Registering the Agent OS marketplace...\n')
548
+ assertSuccess(execute(config.command, config.installArgs), config.command, config.installArgs)
549
+ } else {
550
+ output.write('Agent OS marketplace is already registered.\n')
551
+ }
552
+
553
+ if (options.command === 'update') {
554
+ let sourceType = null
555
+ if (name === 'codex' && registered) {
556
+ const plugins = execute(config.command, ['plugin', 'list', '--json'], { capture: true })
557
+ if (plugins.status === 0) {
558
+ try {
559
+ sourceType = marketplaceSourceType(JSON.parse(plugins.stdout), config.marketplace)
560
+ } catch {
561
+ sourceType = null
562
+ }
563
+ }
564
+ }
565
+ if (sourceType === 'local') {
566
+ output.write('Local marketplace detected; skipping Git refresh.\n')
567
+ } else {
568
+ output.write('Refreshing the Agent OS marketplace...\n')
569
+ const refreshed = execute(config.command, config.refreshArgs, { capture: name === 'codex' })
570
+ if (isNotGitMarketplace(refreshed)) {
571
+ output.write('Local marketplace detected; skipping Git refresh.\n')
572
+ } else {
573
+ assertSuccess(refreshed, config.command, config.refreshArgs)
574
+ }
575
+ }
576
+ }
577
+
578
+ const pluginArgs = config.pluginArgs(options.scope)
579
+ output.write(options.command === 'update'
580
+ ? 'Installing the current plugin snapshot...\n'
581
+ : 'Installing the plugin...\n')
582
+ assertSuccess(execute(config.command, pluginArgs), config.command, pluginArgs)
583
+ output.write('Done. ' + config.nextStep + '\n')
584
+ }
585
+ }
586
+
587
+ function countOccurrences(content, value) {
588
+ return content.split(value).length - 1
589
+ }
590
+
591
+ export function planPolicyUpdate(content, policy) {
592
+ const normalizedPolicy = policy.trimEnd()
593
+ const block = BEGIN_MARKER + '\n' + normalizedPolicy + '\n' + END_MARKER
594
+ const beginCount = countOccurrences(content, BEGIN_MARKER)
595
+ const endCount = countOccurrences(content, END_MARKER)
596
+
597
+ if (beginCount === 0 && endCount === 0) {
598
+ const separator = content.length === 0 ? '' : content.endsWith('\n') ? '\n' : '\n\n'
599
+ return { changed: true, status: 'ADDED', content: content + separator + block + '\n' }
600
+ }
601
+
602
+ const start = content.indexOf(BEGIN_MARKER)
603
+ const endStart = content.indexOf(END_MARKER)
604
+ if (beginCount !== 1 || endCount !== 1 || start >= endStart) {
605
+ throw new CliError(
606
+ 'Malformed Agent OS policy markers (begin=' + beginCount + ' end=' + endCount + '); no files were changed.'
607
+ )
608
+ }
609
+
610
+ const end = endStart + END_MARKER.length
611
+ const current = content.slice(start, end)
612
+ if (current === block) return { changed: false, status: 'OK', content }
613
+ return {
614
+ changed: true,
615
+ status: 'UPDATED',
616
+ content: content.slice(0, start) + block + content.slice(end)
617
+ }
618
+ }
619
+
620
+ function preparePolicyPlans({ fsImpl, homeDir, policyFile }) {
621
+ const policy = fsImpl.readFileSync(policyFile, 'utf8')
622
+ const targets = [
623
+ path.join(homeDir, '.claude', 'CLAUDE.md'),
624
+ path.join(homeDir, '.codex', 'AGENTS.md')
625
+ ]
626
+ return targets.map((target) => {
627
+ const content = fsImpl.existsSync(target) ? fsImpl.readFileSync(target, 'utf8') : ''
628
+ return { target, ...planPolicyUpdate(content, policy) }
629
+ })
630
+ }
631
+
632
+ function applyPolicyPlans(plans, { output, fsImpl }) {
633
+ for (const plan of plans) {
634
+ if (plan.changed) {
635
+ fsImpl.mkdirSync(path.dirname(plan.target), { recursive: true })
636
+ fsImpl.writeFileSync(plan.target, plan.content)
637
+ }
638
+ output.write(plan.status.padEnd(7) + plan.target + '\n')
639
+ }
640
+ }
641
+
642
+ export async function executeInstall(options, {
643
+ output = process.stdout,
644
+ spawn = spawnSync,
645
+ execute = (command, args, runOptions) => runExternal(command, args, { ...runOptions, spawn }),
646
+ exists = (command) => commandExists(command, spawn),
647
+ fsImpl = fs,
648
+ homeDir = os.homedir(),
649
+ cwd = process.cwd(),
650
+ sourceRoot = packagedSkillsPath(),
651
+ policyFile = packagedPolicyPath()
652
+ } = {}) {
653
+ const policyPlans = options.policy
654
+ ? preparePolicyPlans({ fsImpl, homeDir, policyFile })
655
+ : null
656
+
657
+ if (options.method === 'plugin') {
658
+ executePlugin(options, { output, execute, exists })
659
+ } else {
660
+ executeDirect(options, { output, fsImpl, homeDir, cwd, sourceRoot })
661
+ }
662
+
663
+ if (options.policy) {
664
+ output.write('\n[Shared policy]\nSyncing the global Claude Code and Codex policy files...\n')
665
+ applyPolicyPlans(policyPlans, { output, fsImpl })
666
+ }
667
+ }
668
+
669
+ export function printHelp(output = process.stdout) {
670
+ output.write(
671
+ 'Agent OS installer ' + VERSION + '\n\n' +
672
+ 'Usage:\n' +
673
+ ' npx ' + PACKAGE_NAME + ' install\n' +
674
+ ' npx ' + PACKAGE_NAME + ' update\n\n' +
675
+ 'Direct installation is the default and does not require Codex or Claude Code CLI.\n\n' +
676
+ 'Options:\n' +
677
+ ' -p, --platform <name> claude, codex, or both\n' +
678
+ ' -m, --method <name> direct (default) or plugin\n' +
679
+ ' -s, --scope <name> user or project; plugin mode also supports local\n' +
680
+ ' --policy Sync ~/.claude/CLAUDE.md and ~/.codex/AGENTS.md\n' +
681
+ ' --no-policy Leave global policy files unchanged\n' +
682
+ ' -y, --yes Accept defaults; useful in scripts\n' +
683
+ ' --dry-run Show the planned flow without running commands\n' +
684
+ ' -h, --help Show this help\n' +
685
+ ' -v, --version Show the CLI version\n\n' +
686
+ 'Examples:\n' +
687
+ ' npx ' + PACKAGE_NAME + ' install\n' +
688
+ ' npx ' + PACKAGE_NAME + ' install --platform both --yes\n' +
689
+ ' npx ' + PACKAGE_NAME + ' update --platform codex --no-policy\n' +
690
+ ' npx ' + PACKAGE_NAME + ' install --platform codex --method plugin\n' +
691
+ ' npm install --global ' + PACKAGE_NAME + '@latest\n'
692
+ )
693
+ }
694
+
695
+ export function printPlan(options, output = process.stdout, pathOptions = {}) {
696
+ output.write('Planned ' + options.command + ':\n')
697
+ for (const step of buildPlan(options, pathOptions)) {
698
+ const command = step.args.length ? formatCommand(step.command, step.args) : step.command
699
+ output.write(' - ' + step.description + ' [' + command + ']\n')
700
+ }
701
+ }
702
+
703
+ export async function run(argv = process.argv.slice(2), dependencies = {}) {
704
+ const parsed = parseArgs(argv)
705
+ if (parsed.help || parsed.command === 'help') {
706
+ printHelp(dependencies.output || process.stdout)
707
+ return 0
708
+ }
709
+ if (parsed.version) {
710
+ (dependencies.output || process.stdout).write(VERSION + '\n')
711
+ return 0
712
+ }
713
+ const options = await resolveOptions(parsed, dependencies)
714
+ if (options.dryRun) {
715
+ printPlan(options, dependencies.output || process.stdout, {
716
+ homeDir: dependencies.homeDir,
717
+ cwd: dependencies.cwd
718
+ })
719
+ return 0
720
+ }
721
+ await executeInstall(options, dependencies)
722
+ const output = dependencies.output || process.stdout
723
+ output.write('\nAgent OS ' + options.command + ' completed.\n')
724
+ output.write('To update later, use npx ' + PACKAGE_NAME + '@latest update.\n')
725
+ return 0
726
+ }
727
+
728
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
729
+ run().then((code) => {
730
+ process.exitCode = code
731
+ }).catch((error) => {
732
+ console.error('Agent OS installer: ' + error.message)
733
+ process.exitCode = 1
734
+ })
735
+ }