@sockulags/agent-os 0.11.0 → 0.12.1

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.
Files changed (43) hide show
  1. package/README.md +155 -127
  2. package/cli/index.mjs +1022 -735
  3. package/cli/index.test.mjs +574 -300
  4. package/hooks/hooks.json +17 -0
  5. package/package.json +34 -32
  6. package/policy.md +47 -45
  7. package/skills/batch-work/SKILL.md +43 -43
  8. package/skills/batch-work/agents/openai.yaml +2 -2
  9. package/skills/batch-work/references/manifest.md +100 -100
  10. package/skills/batch-work/scripts/manifest-hash.mjs +263 -263
  11. package/skills/batch-work/scripts/test-manifest-hash.mjs +132 -132
  12. package/skills/chart-work/SKILL.md +37 -37
  13. package/skills/chart-work/references/elicitation.md +25 -25
  14. package/skills/chart-work/references/map.md +84 -84
  15. package/skills/chart-work/references/prototypes.md +21 -21
  16. package/skills/check-work/SKILL.md +61 -0
  17. package/skills/deliver-work/SKILL.md +12 -12
  18. package/skills/deliver-work/workflow.md +119 -113
  19. package/skills/diagnose-before-fix/SKILL.md +24 -24
  20. package/skills/dispatch-next/SKILL.md +28 -28
  21. package/skills/init-agent-os/SKILL.md +54 -39
  22. package/skills/init-agent-os/references/repository-init.md +74 -0
  23. package/skills/init-agent-os/scripts/policy-block.ps1 +87 -87
  24. package/skills/list-skills/SKILL.md +43 -42
  25. package/skills/list-skills/agents/openai.yaml +2 -2
  26. package/skills/plain-voice/SKILL.md +39 -0
  27. package/skills/plain-voice/references/tells.md +82 -0
  28. package/skills/proportional-testing/SKILL.md +30 -30
  29. package/skills/proportional-testing/references/strategy.md +75 -75
  30. package/skills/quality-ratchet/SKILL.md +50 -0
  31. package/skills/quality-ratchet/scripts/quality-delta.mjs +752 -0
  32. package/skills/quality-ratchet/scripts/quality-delta.test.mjs +514 -0
  33. package/skills/scope-guard/SKILL.md +21 -21
  34. package/skills/shape-work/SKILL.md +39 -39
  35. package/skills/shape-work/references/implementation-issues.md +69 -69
  36. package/skills/shape-work/references/mockups.md +23 -23
  37. package/skills/simplifier/SKILL.md +34 -34
  38. package/skills/simplifier/agents/openai.yaml +2 -2
  39. package/skills/simplifier-audit/SKILL.md +28 -28
  40. package/skills/simplifier-audit/agents/openai.yaml +2 -2
  41. package/skills/simplifier-review/SKILL.md +36 -29
  42. package/skills/verify-before-done/SKILL.md +29 -29
  43. package/skills/writing-skills/SKILL.md +68 -68
package/cli/index.mjs CHANGED
@@ -1,735 +1,1022 @@
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
+ import {
11
+ HOOK_TIMEOUT_SECONDS,
12
+ QUALITY_HOOK_MARKER
13
+ } from '../skills/quality-ratchet/scripts/quality-delta.mjs'
14
+
15
+ const packageRoot = fileURLToPath(new URL('../', import.meta.url))
16
+ const packagePath = path.join(packageRoot, 'package.json')
17
+ const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'))
18
+
19
+ export const VERSION = packageJson.version
20
+ export const PACKAGE_NAME = packageJson.name
21
+ export const MARKETPLACE_SOURCE = 'sockulags/agent-os'
22
+ export const INSTALL_MANIFEST = '.agent-os-install.json'
23
+ export const QUALITY_HOOK_EVENT = 'Stop'
24
+
25
+ const BEGIN_MARKER = '<!-- BEGIN AGENT OS -->'
26
+ const END_MARKER = '<!-- END AGENT OS -->'
27
+ const PLATFORM_VALUES = ['claude', 'codex', 'both']
28
+ const METHOD_VALUES = ['direct', 'plugin']
29
+ const SCOPE_VALUES = ['user', 'project', 'local']
30
+
31
+ export const PLATFORM_CONFIG = Object.freeze({
32
+ claude: Object.freeze({
33
+ label: 'Claude Code',
34
+ command: 'claude',
35
+ marketplace: 'agent-os-marketplace',
36
+ installArgs: ['plugin', 'marketplace', 'add', MARKETPLACE_SOURCE],
37
+ refreshArgs: ['plugin', 'marketplace', 'update', 'agent-os-marketplace'],
38
+ pluginArgs: (scope) => ['plugin', 'install', 'agent-os@agent-os-marketplace', '--scope', scope],
39
+ nextStep: 'Restart Claude Code or run /reload-plugins.'
40
+ }),
41
+ codex: Object.freeze({
42
+ label: 'Codex',
43
+ command: 'codex',
44
+ marketplace: 'agent-os',
45
+ installArgs: ['plugin', 'marketplace', 'add', MARKETPLACE_SOURCE],
46
+ refreshArgs: ['plugin', 'marketplace', 'upgrade', 'agent-os'],
47
+ pluginArgs: () => ['plugin', 'add', 'agent-os@agent-os'],
48
+ nextStep: 'Start a new Codex session so the refreshed plugin is loaded.'
49
+ })
50
+ })
51
+
52
+ export class CliError extends Error {}
53
+
54
+ function valueAfter(args, index, flag) {
55
+ const value = args[index + 1]
56
+ if (!value || value.startsWith('-')) throw new CliError(flag + ' requires a value.')
57
+ return value
58
+ }
59
+
60
+ function normalizePlatform(value) {
61
+ const normalized = value.toLowerCase()
62
+ if (normalized === 'claude-code') return 'claude'
63
+ if (!PLATFORM_VALUES.includes(normalized)) {
64
+ throw new CliError('Platform must be claude, codex, or both.')
65
+ }
66
+ return normalized
67
+ }
68
+
69
+ function normalizeMethod(value) {
70
+ const normalized = value.toLowerCase()
71
+ if (!METHOD_VALUES.includes(normalized)) {
72
+ throw new CliError('Method must be direct or plugin.')
73
+ }
74
+ return normalized
75
+ }
76
+
77
+ function normalizeScope(value) {
78
+ const normalized = value.toLowerCase()
79
+ if (!SCOPE_VALUES.includes(normalized)) {
80
+ throw new CliError('Scope must be user, project, or local.')
81
+ }
82
+ return normalized
83
+ }
84
+
85
+ function quoteCommandArg(value) {
86
+ return '"' + String(value).replaceAll('"', '\\"') + '"'
87
+ }
88
+
89
+ export function buildManagedHookCommand(scriptPath, nodePath = process.execPath) {
90
+ return [quoteCommandArg(nodePath), quoteCommandArg(scriptPath), 'hook', QUALITY_HOOK_MARKER].join(' ')
91
+ }
92
+
93
+ export function parseArgs(argv) {
94
+ const result = {
95
+ command: 'install',
96
+ platform: null,
97
+ method: null,
98
+ scope: null,
99
+ policy: null,
100
+ yes: false,
101
+ dryRun: false,
102
+ help: false,
103
+ version: false
104
+ }
105
+
106
+ let index = 0
107
+ if (argv[0] && !argv[0].startsWith('-')) {
108
+ result.command = argv[0].toLowerCase()
109
+ index = 1
110
+ }
111
+
112
+ if (result.command === 'upgrade') result.command = 'update'
113
+ if (!['install', 'update', 'help'].includes(result.command)) {
114
+ throw new CliError('Unknown command "' + result.command + '". Use install or update.')
115
+ }
116
+
117
+ while (index < argv.length) {
118
+ const argument = argv[index]
119
+ if (argument === '--help' || argument === '-h') {
120
+ result.help = true
121
+ } else if (argument === '--version' || argument === '-v') {
122
+ result.version = true
123
+ } else if (argument === '--yes' || argument === '-y') {
124
+ result.yes = true
125
+ } else if (argument === '--dry-run') {
126
+ result.dryRun = true
127
+ } else if (argument === '--policy') {
128
+ if (result.policy === false) throw new CliError('Use only one of --policy and --no-policy.')
129
+ result.policy = true
130
+ } else if (argument === '--no-policy') {
131
+ if (result.policy === true) throw new CliError('Use only one of --policy and --no-policy.')
132
+ result.policy = false
133
+ } else if (argument === '--platform' || argument === '-p') {
134
+ result.platform = normalizePlatform(valueAfter(argv, index, argument))
135
+ index += 1
136
+ } else if (argument.startsWith('--platform=')) {
137
+ result.platform = normalizePlatform(argument.slice('--platform='.length))
138
+ } else if (argument === '--method' || argument === '-m') {
139
+ result.method = normalizeMethod(valueAfter(argv, index, argument))
140
+ index += 1
141
+ } else if (argument.startsWith('--method=')) {
142
+ result.method = normalizeMethod(argument.slice('--method='.length))
143
+ } else if (argument === '--scope' || argument === '-s') {
144
+ result.scope = normalizeScope(valueAfter(argv, index, argument))
145
+ index += 1
146
+ } else if (argument.startsWith('--scope=')) {
147
+ result.scope = normalizeScope(argument.slice('--scope='.length))
148
+ } else {
149
+ throw new CliError('Unknown option "' + argument + '". Use --help for usage.')
150
+ }
151
+ index += 1
152
+ }
153
+
154
+ return result
155
+ }
156
+
157
+ export function selectedPlatforms(platform) {
158
+ if (platform === 'both') return ['claude', 'codex']
159
+ return [platform]
160
+ }
161
+
162
+ export function targetSkillRoot(platform, scope, {
163
+ homeDir = os.homedir(),
164
+ cwd = process.cwd()
165
+ } = {}) {
166
+ if (scope === 'user') {
167
+ return platform === 'codex'
168
+ ? path.join(homeDir, '.codex', 'skills')
169
+ : path.join(homeDir, '.claude', 'skills')
170
+ }
171
+ if (scope === 'project') {
172
+ return platform === 'codex'
173
+ ? path.join(cwd, '.agents', 'skills')
174
+ : path.join(cwd, '.claude', 'skills')
175
+ }
176
+ throw new CliError('Local scope is available only with --method plugin.')
177
+ }
178
+
179
+ export function hookConfigPath(platform, scope, {
180
+ homeDir = os.homedir(),
181
+ cwd = process.cwd()
182
+ } = {}) {
183
+ if (scope === 'user') {
184
+ return platform === 'codex'
185
+ ? path.join(homeDir, '.codex', 'hooks.json')
186
+ : path.join(homeDir, '.claude', 'settings.json')
187
+ }
188
+ if (scope === 'project') {
189
+ return platform === 'codex'
190
+ ? path.join(cwd, '.codex', 'hooks.json')
191
+ : path.join(cwd, '.claude', 'settings.json')
192
+ }
193
+ throw new CliError('Local scope is available only with --method plugin.')
194
+ }
195
+
196
+ export function buildPlan(options, pathOptions = {}) {
197
+ const { command, platform, method = 'direct', scope = 'user', policy = true } = options
198
+ const steps = []
199
+ for (const name of selectedPlatforms(platform)) {
200
+ const config = PLATFORM_CONFIG[name]
201
+ if (method === 'direct') {
202
+ const root = targetSkillRoot(name, scope, pathOptions)
203
+ steps.push({
204
+ platform: name,
205
+ kind: command === 'update' ? 'update-skills' : 'install-skills',
206
+ command: 'filesystem',
207
+ args: [root],
208
+ description: (command === 'update' ? 'Update' : 'Install') +
209
+ ' Agent OS managed skills for ' + config.label + '.'
210
+ })
211
+ steps.push({
212
+ platform: name,
213
+ kind: 'install-hooks',
214
+ command: 'filesystem',
215
+ args: [hookConfigPath(name, scope, pathOptions)],
216
+ description: 'Merge the Agent OS Stop hook into the ' + config.label + ' configuration.'
217
+ })
218
+ continue
219
+ }
220
+
221
+ steps.push({
222
+ platform: name,
223
+ kind: 'ensure-marketplace',
224
+ command: config.command,
225
+ args: ['plugin', 'marketplace', 'list', '--json'],
226
+ description: 'Check whether the ' + config.label + ' marketplace is registered.'
227
+ })
228
+ steps.push({
229
+ platform: name,
230
+ kind: 'add-marketplace-if-missing',
231
+ command: config.command,
232
+ args: config.installArgs,
233
+ description: 'Register the Agent OS marketplace when it is not present.'
234
+ })
235
+ if (command === 'update') {
236
+ steps.push({
237
+ platform: name,
238
+ kind: 'refresh-marketplace',
239
+ command: config.command,
240
+ args: config.refreshArgs,
241
+ description: 'Refresh the Agent OS Git marketplace when applicable.'
242
+ })
243
+ }
244
+ steps.push({
245
+ platform: name,
246
+ kind: 'install-plugin',
247
+ command: config.command,
248
+ args: config.pluginArgs(scope),
249
+ description: command === 'update'
250
+ ? 'Install the current Agent OS plugin snapshot.'
251
+ : 'Install the Agent OS plugin.'
252
+ })
253
+ }
254
+ if (policy) {
255
+ steps.push({
256
+ platform: 'shared',
257
+ kind: 'install-policy',
258
+ command: 'node',
259
+ args: [],
260
+ description: 'Sync the shared global policy for Claude Code and Codex.'
261
+ })
262
+ }
263
+ return steps
264
+ }
265
+
266
+ function commandExists(command, spawn = spawnSync) {
267
+ const lookup = process.platform === 'win32' ? 'where.exe' : 'which'
268
+ const result = spawn(lookup, [command], { stdio: 'ignore' })
269
+ return result.status === 0
270
+ }
271
+
272
+ function runExternal(command, args, { capture = false, spawn = spawnSync } = {}) {
273
+ const options = capture
274
+ ? { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }
275
+ : { stdio: 'inherit' }
276
+ if (process.platform === 'win32') options.shell = true
277
+ const result = spawn(command, args, options)
278
+ return {
279
+ status: result.status ?? 1,
280
+ stdout: result.stdout ?? '',
281
+ stderr: result.stderr ?? '',
282
+ error: result.error
283
+ }
284
+ }
285
+
286
+ function marketplacePresent(value, marketplaceName) {
287
+ if (Array.isArray(value)) return value.some((item) => marketplacePresent(item, marketplaceName))
288
+ if (!value || typeof value !== 'object') return false
289
+ if (value.name === marketplaceName || value.marketplaceName === marketplaceName) return true
290
+ return Object.values(value).some((item) => marketplacePresent(item, marketplaceName))
291
+ }
292
+
293
+ function marketplaceSourceType(value, marketplaceName) {
294
+ if (Array.isArray(value)) {
295
+ for (const item of value) {
296
+ const result = marketplaceSourceType(item, marketplaceName)
297
+ if (result) return result
298
+ }
299
+ return null
300
+ }
301
+ if (!value || typeof value !== 'object') return null
302
+ if (value.marketplaceName === marketplaceName && value.marketplaceSource?.sourceType) {
303
+ return value.marketplaceSource.sourceType
304
+ }
305
+ for (const item of Object.values(value)) {
306
+ const result = marketplaceSourceType(item, marketplaceName)
307
+ if (result) return result
308
+ }
309
+ return null
310
+ }
311
+
312
+ function formatCommand(command, args) {
313
+ return [command, ...args].join(' ')
314
+ }
315
+
316
+ function assertSuccess(result, command, args) {
317
+ if (result.status === 0) return
318
+ const detail = result.error?.message || result.stderr?.trim()
319
+ throw new CliError(
320
+ 'Command failed (' + result.status + '): ' + formatCommand(command, args) +
321
+ (detail ? '\n' + detail : '')
322
+ )
323
+ }
324
+
325
+ async function ask(question, { input, output }) {
326
+ const readline = createInterface({ input, output })
327
+ const answer = await new Promise((resolve) => readline.question(question, resolve))
328
+ readline.close()
329
+ return answer.trim()
330
+ }
331
+
332
+ async function choose(question, choices, dependencies) {
333
+ dependencies.output.write('\n' + question + '\n')
334
+ choices.forEach((choice, index) => {
335
+ dependencies.output.write(' ' + (index + 1) + ') ' + choice.label + '\n')
336
+ })
337
+ while (true) {
338
+ const answer = await ask('Choose 1-' + choices.length + ': ', dependencies)
339
+ const selected = Number.parseInt(answer, 10)
340
+ if (selected >= 1 && selected <= choices.length) return choices[selected - 1].value
341
+ dependencies.output.write('Please choose one of the listed numbers.\n')
342
+ }
343
+ }
344
+
345
+ async function confirm(question, dependencies, defaultValue = true) {
346
+ const suffix = defaultValue ? ' [Y/n] ' : ' [y/N] '
347
+ const answer = (await ask(question + suffix, dependencies)).toLowerCase()
348
+ if (!answer) return defaultValue
349
+ return answer === 'y' || answer === 'yes'
350
+ }
351
+
352
+ export async function resolveOptions(parsed, {
353
+ input = process.stdin,
354
+ output = process.stdout
355
+ } = {}) {
356
+ const dependencies = { input, output }
357
+ const interactive = Boolean(input.isTTY && output.isTTY)
358
+ if (!interactive && !parsed.yes && !parsed.dryRun) {
359
+ throw new CliError('This command needs a terminal or --yes with explicit options.')
360
+ }
361
+
362
+ let platform = parsed.platform
363
+ if (!platform) {
364
+ if (!interactive) throw new CliError('Choose a platform with --platform claude, codex, or both.')
365
+ platform = await choose('Where should Agent OS be installed?', [
366
+ { value: 'codex', label: 'Codex' },
367
+ { value: 'claude', label: 'Claude Code' },
368
+ { value: 'both', label: 'Both' }
369
+ ], dependencies)
370
+ }
371
+
372
+ let method = parsed.method
373
+ if (!method) {
374
+ method = interactive && !parsed.yes
375
+ ? await choose('How should Agent OS be installed?', [
376
+ { value: 'direct', label: 'Direct skills (recommended; no host CLI required)' },
377
+ { value: 'plugin', label: 'Native plugin marketplace' }
378
+ ], dependencies)
379
+ : 'direct'
380
+ }
381
+
382
+ let scope = parsed.scope || 'user'
383
+ if (!parsed.scope && interactive && !parsed.yes) {
384
+ if (method === 'direct') {
385
+ scope = await choose('Where should the skill files live?', [
386
+ { value: 'user', label: 'User (recommended; available across projects)' },
387
+ { value: 'project', label: 'Project (stored in this repository)' }
388
+ ], dependencies)
389
+ } else if (platform !== 'codex') {
390
+ scope = await choose('What Claude Code plugin scope should be used?', [
391
+ { value: 'user', label: 'User (recommended; available across projects)' },
392
+ { value: 'project', label: 'Project (shared through this repository)' },
393
+ { value: 'local', label: 'Local (this repository for you only)' }
394
+ ], dependencies)
395
+ }
396
+ }
397
+ if (method === 'direct' && scope === 'local') {
398
+ throw new CliError('Local scope is available only with --method plugin. Use user or project.')
399
+ }
400
+
401
+ let policy = parsed.policy
402
+ if (policy === null) {
403
+ policy = interactive && !parsed.yes
404
+ ? await confirm('Also sync the shared global policy files?', dependencies, true)
405
+ : true
406
+ }
407
+
408
+ return { ...parsed, platform, method, scope, policy }
409
+ }
410
+
411
+ function packagedSkillsPath() {
412
+ return path.join(packageRoot, 'skills')
413
+ }
414
+
415
+ function packagedPolicyPath() {
416
+ return path.join(packageRoot, 'policy.md')
417
+ }
418
+
419
+ function listPackagedSkills(sourceRoot, fsImpl = fs) {
420
+ if (!fsImpl.existsSync(sourceRoot)) {
421
+ throw new CliError('Packaged skills directory is missing: ' + sourceRoot)
422
+ }
423
+ const entries = fsImpl.readdirSync(sourceRoot, { withFileTypes: true })
424
+ .filter((entry) => entry.isDirectory() && fsImpl.existsSync(path.join(sourceRoot, entry.name, 'SKILL.md')))
425
+ .map((entry) => entry.name)
426
+ .sort()
427
+ if (entries.length === 0) throw new CliError('No packaged skills were found in ' + sourceRoot)
428
+ return entries
429
+ }
430
+
431
+ function containsHookMarker(value) {
432
+ if (typeof value === 'string') return value.includes(QUALITY_HOOK_MARKER)
433
+ if (Array.isArray(value)) return value.some(containsHookMarker)
434
+ if (value && typeof value === 'object') return Object.values(value).some(containsHookMarker)
435
+ return false
436
+ }
437
+
438
+ function managedCommandHooks(value, matches = []) {
439
+ if (Array.isArray(value)) {
440
+ value.forEach((item) => managedCommandHooks(item, matches))
441
+ return matches
442
+ }
443
+ if (!value || typeof value !== 'object') return matches
444
+ if (typeof value.command === 'string' && value.command.includes(QUALITY_HOOK_MARKER)) {
445
+ matches.push(value)
446
+ }
447
+ Object.entries(value).forEach(([key, item]) => {
448
+ if (key !== 'command') managedCommandHooks(item, matches)
449
+ })
450
+ return matches
451
+ }
452
+
453
+ export function planManagedHookConfig(content, command, target = 'Agent OS hook configuration') {
454
+ let config
455
+ if (!content.trim()) {
456
+ config = {}
457
+ } else {
458
+ try {
459
+ config = JSON.parse(content)
460
+ } catch (cause) {
461
+ throw new CliError('Cannot read ' + target + ': ' + cause.message + '; no files were changed.')
462
+ }
463
+ }
464
+ if (!config || typeof config !== 'object' || Array.isArray(config)) {
465
+ throw new CliError('Refusing to merge the Agent OS hook into malformed ' + target + '; no files were changed.')
466
+ }
467
+ if (config.hooks === undefined) config.hooks = {}
468
+ if (!config.hooks || typeof config.hooks !== 'object' || Array.isArray(config.hooks)) {
469
+ throw new CliError('Refusing to merge the Agent OS hook into malformed ' + target + '.hooks; no files were changed.')
470
+ }
471
+ if (config.hooks[QUALITY_HOOK_EVENT] === undefined) config.hooks[QUALITY_HOOK_EVENT] = []
472
+ if (!Array.isArray(config.hooks[QUALITY_HOOK_EVENT])) {
473
+ throw new CliError('Refusing to merge the Agent OS hook into malformed ' + target + '.hooks.Stop; no files were changed.')
474
+ }
475
+
476
+ const managed = []
477
+ for (const [event, value] of Object.entries(config.hooks)) {
478
+ const matches = managedCommandHooks(value)
479
+ if (matches.length && event !== QUALITY_HOOK_EVENT) {
480
+ throw new CliError('Refusing to update an Agent OS hook outside hooks.Stop in ' + target + '; no files were changed.')
481
+ }
482
+ managed.push(...matches)
483
+ }
484
+ if (containsHookMarker(config) && managed.length === 0) {
485
+ throw new CliError('Refusing to update an ambiguous Agent OS hook marker in ' + target + '; no files were changed.')
486
+ }
487
+ if (managed.length > 1) {
488
+ throw new CliError('Refusing to update multiple Agent OS hook entries in ' + target + '; no files were changed.')
489
+ }
490
+
491
+ if (managed.length === 1) {
492
+ const entry = managed[0]
493
+ if (entry.type !== 'command') {
494
+ throw new CliError('Refusing to update a malformed Agent OS command hook in ' + target + '; no files were changed.')
495
+ }
496
+ const changed = entry.command !== command || entry.timeout !== HOOK_TIMEOUT_SECONDS
497
+ entry.command = command
498
+ entry.timeout = HOOK_TIMEOUT_SECONDS
499
+ return {
500
+ changed,
501
+ status: changed ? 'UPDATED' : 'OK',
502
+ content: changed ? JSON.stringify(config, null, 2) + '\n' : content
503
+ }
504
+ }
505
+
506
+ config.hooks[QUALITY_HOOK_EVENT].push({
507
+ hooks: [{
508
+ type: 'command',
509
+ command,
510
+ timeout: HOOK_TIMEOUT_SECONDS
511
+ }]
512
+ })
513
+ return {
514
+ changed: true,
515
+ status: 'ADDED',
516
+ content: JSON.stringify(config, null, 2) + '\n'
517
+ }
518
+ }
519
+
520
+ function readInstallManifest(root, fsImpl = fs) {
521
+ const manifestPath = path.join(root, INSTALL_MANIFEST)
522
+ if (!fsImpl.existsSync(manifestPath)) return null
523
+ let manifest
524
+ try {
525
+ manifest = JSON.parse(fsImpl.readFileSync(manifestPath, 'utf8'))
526
+ } catch (error) {
527
+ throw new CliError('Cannot read Agent OS install manifest at ' + manifestPath + ': ' + error.message)
528
+ }
529
+ if (manifest.package !== PACKAGE_NAME || !Array.isArray(manifest.skills) ||
530
+ ![1, 2].includes(manifest.schemaVersion ?? 1)) {
531
+ throw new CliError('Refusing to use an unrecognized install manifest at ' + manifestPath)
532
+ }
533
+ return manifest
534
+ }
535
+
536
+ function directTargets(options, { homeDir, cwd }) {
537
+ return selectedPlatforms(options.platform).map((platform) => ({
538
+ platform,
539
+ scope: options.scope,
540
+ root: targetSkillRoot(platform, options.scope, { homeDir, cwd }),
541
+ hookPath: hookConfigPath(platform, options.scope, { homeDir, cwd })
542
+ }))
543
+ }
544
+
545
+ function prepareHookPlans(options, { homeDir, cwd, fsImpl = fs }) {
546
+ return directTargets(options, { homeDir, cwd }).map((target) => {
547
+ const scriptPath = path.join(target.root, 'quality-ratchet', 'scripts', 'quality-delta.mjs')
548
+ const command = buildManagedHookCommand(scriptPath)
549
+ const current = fsImpl.existsSync(target.hookPath)
550
+ ? fsImpl.readFileSync(target.hookPath, 'utf8')
551
+ : ''
552
+ return {
553
+ ...target,
554
+ command,
555
+ ...planManagedHookConfig(current, command, target.hookPath)
556
+ }
557
+ })
558
+ }
559
+
560
+ function writeFileAtomic(target, content, fsImpl = fs) {
561
+ const directory = path.dirname(target)
562
+ const temporary = path.join(
563
+ directory,
564
+ '.' + path.basename(target) + '.agent-os-' + randomUUID() + '.tmp'
565
+ )
566
+ fsImpl.mkdirSync(directory, { recursive: true })
567
+ try {
568
+ fsImpl.writeFileSync(temporary, content)
569
+ fsImpl.renameSync(temporary, target)
570
+ } finally {
571
+ if (fsImpl.existsSync(temporary)) fsImpl.rmSync(temporary, { force: true })
572
+ }
573
+ }
574
+
575
+ function applyHookPlans(plans, { output, fsImpl = fs }) {
576
+ const applied = []
577
+ try {
578
+ for (const plan of plans) {
579
+ if (plan.changed) {
580
+ const previous = fsImpl.existsSync(plan.hookPath)
581
+ ? fsImpl.readFileSync(plan.hookPath, 'utf8')
582
+ : null
583
+ applied.push({ ...plan, previous })
584
+ writeFileAtomic(plan.hookPath, plan.content, fsImpl)
585
+ }
586
+ output.write(plan.status.padEnd(7) + plan.hookPath + '\n')
587
+ }
588
+ } catch (cause) {
589
+ let rollbackFailure = null
590
+ for (const plan of applied.reverse()) {
591
+ try {
592
+ if (plan.previous === null) fsImpl.rmSync(plan.hookPath, { force: true })
593
+ else writeFileAtomic(plan.hookPath, plan.previous, fsImpl)
594
+ } catch (rollbackCause) {
595
+ rollbackFailure ??= rollbackCause
596
+ }
597
+ }
598
+ throw new CliError('Failed to update Agent OS hook configuration: ' + cause.message +
599
+ (rollbackFailure ? '; rollback also failed: ' + rollbackFailure.message : ''))
600
+ }
601
+ }
602
+
603
+ function preflightDirectTarget(target, skillNames, fsImpl = fs) {
604
+ const manifest = readInstallManifest(target.root, fsImpl)
605
+ const managed = new Set(manifest?.skills || [])
606
+ const conflicts = skillNames.filter((name) => {
607
+ const destination = path.join(target.root, name)
608
+ return fsImpl.existsSync(destination) && !managed.has(name)
609
+ })
610
+ if (conflicts.length > 0) {
611
+ throw new CliError(
612
+ 'Refusing to overwrite unmanaged skills in ' + target.root + ': ' + conflicts.join(', ') +
613
+ '. Move or remove them, then rerun the installer.'
614
+ )
615
+ }
616
+ return manifest
617
+ }
618
+
619
+ function replaceManagedSkills(target, sourceRoot, skillNames, previousManifest, fsImpl = fs) {
620
+ fsImpl.mkdirSync(target.root, { recursive: true })
621
+ const token = randomUUID()
622
+ const stageRoot = path.join(target.root, '.agent-os-stage-' + token)
623
+ const backupRoot = path.join(target.root, '.agent-os-backup-' + token)
624
+ const previousNames = previousManifest?.skills || []
625
+ const namesToBackup = [...new Set([...previousNames, ...skillNames])]
626
+ .filter((name) => fsImpl.existsSync(path.join(target.root, name)))
627
+ const installed = []
628
+ const backedUp = []
629
+ const manifestPath = path.join(target.root, INSTALL_MANIFEST)
630
+ const previousManifestText = fsImpl.existsSync(manifestPath)
631
+ ? fsImpl.readFileSync(manifestPath, 'utf8')
632
+ : null
633
+
634
+ try {
635
+ fsImpl.mkdirSync(stageRoot, { recursive: true })
636
+ for (const name of skillNames) {
637
+ fsImpl.cpSync(path.join(sourceRoot, name), path.join(stageRoot, name), { recursive: true })
638
+ }
639
+
640
+ if (namesToBackup.length > 0) fsImpl.mkdirSync(backupRoot, { recursive: true })
641
+ for (const name of namesToBackup) {
642
+ fsImpl.renameSync(path.join(target.root, name), path.join(backupRoot, name))
643
+ backedUp.push(name)
644
+ }
645
+
646
+ for (const name of skillNames) {
647
+ fsImpl.renameSync(path.join(stageRoot, name), path.join(target.root, name))
648
+ installed.push(name)
649
+ }
650
+
651
+ const manifest = {
652
+ schemaVersion: 2,
653
+ package: PACKAGE_NAME,
654
+ version: VERSION,
655
+ platform: target.platform,
656
+ scope: target.scope,
657
+ skills: skillNames,
658
+ integrations: {
659
+ hooks: {
660
+ configPath: target.hookPath,
661
+ event: QUALITY_HOOK_EVENT,
662
+ marker: QUALITY_HOOK_MARKER
663
+ }
664
+ }
665
+ }
666
+ writeFileAtomic(manifestPath, JSON.stringify(manifest, null, 2) + '\n', fsImpl)
667
+ } catch (error) {
668
+ for (const name of installed.reverse()) {
669
+ const destination = path.join(target.root, name)
670
+ if (fsImpl.existsSync(destination)) fsImpl.rmSync(destination, { recursive: true, force: true })
671
+ }
672
+ for (const name of backedUp.reverse()) {
673
+ const backup = path.join(backupRoot, name)
674
+ if (fsImpl.existsSync(backup)) fsImpl.renameSync(backup, path.join(target.root, name))
675
+ }
676
+ if (previousManifestText === null) {
677
+ if (fsImpl.existsSync(manifestPath)) fsImpl.rmSync(manifestPath, { force: true })
678
+ } else {
679
+ writeFileAtomic(manifestPath, previousManifestText, fsImpl)
680
+ }
681
+ throw new CliError('Failed to update managed skills in ' + target.root + ': ' + error.message)
682
+ } finally {
683
+ if (fsImpl.existsSync(stageRoot)) fsImpl.rmSync(stageRoot, { recursive: true, force: true })
684
+ if (fsImpl.existsSync(backupRoot)) fsImpl.rmSync(backupRoot, { recursive: true, force: true })
685
+ }
686
+ }
687
+
688
+ function prepareDirectInstall(options, {
689
+ fsImpl,
690
+ homeDir,
691
+ cwd,
692
+ sourceRoot
693
+ }) {
694
+ const skillNames = listPackagedSkills(sourceRoot, fsImpl)
695
+ const targets = directTargets(options, { homeDir, cwd })
696
+ const manifests = targets.map((target) => preflightDirectTarget(target, skillNames, fsImpl))
697
+ return { skillNames, targets, manifests, sourceRoot }
698
+ }
699
+
700
+ function prepareManagedSkillRollback(plan, fsImpl = fs) {
701
+ const snapshots = []
702
+ try {
703
+ plan.targets.forEach((target, index) => {
704
+ const previousNames = plan.manifests[index]?.skills || []
705
+ const backupRoot = path.join(target.root, '.agent-os-transaction-' + randomUUID())
706
+ const backedUpNames = previousNames.filter((name) =>
707
+ fsImpl.existsSync(path.join(target.root, name)))
708
+ const manifestPath = path.join(target.root, INSTALL_MANIFEST)
709
+ const previousManifestText = fsImpl.existsSync(manifestPath)
710
+ ? fsImpl.readFileSync(manifestPath, 'utf8')
711
+ : null
712
+ const snapshot = { target, backupRoot, previousNames, backedUpNames, previousManifestText }
713
+ snapshots.push(snapshot)
714
+ if (backedUpNames.length > 0) {
715
+ fsImpl.mkdirSync(backupRoot, { recursive: true })
716
+ for (const name of backedUpNames) {
717
+ fsImpl.cpSync(path.join(target.root, name), path.join(backupRoot, name), { recursive: true })
718
+ }
719
+ }
720
+ })
721
+ return snapshots
722
+ } catch (cause) {
723
+ for (const snapshot of snapshots) {
724
+ if (fsImpl.existsSync(snapshot.backupRoot)) {
725
+ fsImpl.rmSync(snapshot.backupRoot, { recursive: true, force: true })
726
+ }
727
+ }
728
+ throw new CliError('Failed to prepare managed skill rollback: ' + cause.message)
729
+ }
730
+ }
731
+
732
+ function cleanupManagedSkillRollback(snapshots, fsImpl = fs) {
733
+ for (const snapshot of snapshots) {
734
+ if (fsImpl.existsSync(snapshot.backupRoot)) {
735
+ fsImpl.rmSync(snapshot.backupRoot, { recursive: true, force: true })
736
+ }
737
+ }
738
+ }
739
+
740
+ function rollbackManagedSkills(plan, snapshots, fsImpl = fs) {
741
+ let failure = null
742
+ snapshots.slice().reverse().forEach((snapshot) => {
743
+ try {
744
+ const names = [...new Set([...plan.skillNames, ...snapshot.previousNames])]
745
+ for (const name of names) {
746
+ const destination = path.join(snapshot.target.root, name)
747
+ if (fsImpl.existsSync(destination)) fsImpl.rmSync(destination, { recursive: true, force: true })
748
+ }
749
+ for (const name of snapshot.backedUpNames) {
750
+ const backup = path.join(snapshot.backupRoot, name)
751
+ if (fsImpl.existsSync(backup)) fsImpl.renameSync(backup, path.join(snapshot.target.root, name))
752
+ }
753
+ const manifestPath = path.join(snapshot.target.root, INSTALL_MANIFEST)
754
+ if (snapshot.previousManifestText === null) fsImpl.rmSync(manifestPath, { force: true })
755
+ else writeFileAtomic(manifestPath, snapshot.previousManifestText, fsImpl)
756
+ } catch (cause) {
757
+ failure ??= cause
758
+ }
759
+ })
760
+ if (failure) throw new CliError('Failed to restore managed skills: ' + failure.message)
761
+ cleanupManagedSkillRollback(snapshots, fsImpl)
762
+ }
763
+
764
+ function applyDirectInstall(options, plan, {
765
+ output,
766
+ fsImpl
767
+ }) {
768
+ plan.targets.forEach((target, index) => {
769
+ const config = PLATFORM_CONFIG[target.platform]
770
+ output.write('\n[' + config.label + ']\n')
771
+ output.write((options.command === 'update' ? 'Updating' : 'Installing') +
772
+ ' ' + plan.skillNames.length + ' managed skills in ' + target.root + '...\n')
773
+ replaceManagedSkills(target, plan.sourceRoot, plan.skillNames, plan.manifests[index], fsImpl)
774
+ output.write('Done. Start a new ' + config.label + ' session to load the skills.\n')
775
+ })
776
+ }
777
+
778
+ function isNotGitMarketplace(result) {
779
+ return result.status !== 0 && /not configured as a Git marketplace/i.test(result.stderr || '')
780
+ }
781
+
782
+ function executePlugin(options, { output, execute, exists }) {
783
+ const names = selectedPlatforms(options.platform)
784
+ const missing = names.filter((name) => !exists(PLATFORM_CONFIG[name].command))
785
+ if (missing.length > 0) {
786
+ const details = missing.map((name) => {
787
+ const config = PLATFORM_CONFIG[name]
788
+ const hint = name === 'claude'
789
+ ? 'npm install -g @anthropic-ai/claude-code'
790
+ : 'npm install -g @openai/codex'
791
+ return config.label + ': ' + hint
792
+ })
793
+ throw new CliError('Native plugin mode requires the selected host CLIs:\n' + details.join('\n'))
794
+ }
795
+
796
+ for (const name of names) {
797
+ const config = PLATFORM_CONFIG[name]
798
+ output.write('\n[' + config.label + ']\n')
799
+ const listed = execute(config.command, ['plugin', 'marketplace', 'list', '--json'], { capture: true })
800
+ let registered = false
801
+ if (listed.status === 0) {
802
+ try {
803
+ registered = marketplacePresent(JSON.parse(listed.stdout), config.marketplace)
804
+ } catch {
805
+ registered = false
806
+ }
807
+ }
808
+ if (!registered) {
809
+ output.write('Registering the Agent OS marketplace...\n')
810
+ assertSuccess(execute(config.command, config.installArgs), config.command, config.installArgs)
811
+ } else {
812
+ output.write('Agent OS marketplace is already registered.\n')
813
+ }
814
+
815
+ if (options.command === 'update') {
816
+ let sourceType = null
817
+ if (name === 'codex' && registered) {
818
+ const plugins = execute(config.command, ['plugin', 'list', '--json'], { capture: true })
819
+ if (plugins.status === 0) {
820
+ try {
821
+ sourceType = marketplaceSourceType(JSON.parse(plugins.stdout), config.marketplace)
822
+ } catch {
823
+ sourceType = null
824
+ }
825
+ }
826
+ }
827
+ if (sourceType === 'local') {
828
+ output.write('Local marketplace detected; skipping Git refresh.\n')
829
+ } else {
830
+ output.write('Refreshing the Agent OS marketplace...\n')
831
+ const refreshed = execute(config.command, config.refreshArgs, { capture: name === 'codex' })
832
+ if (isNotGitMarketplace(refreshed)) {
833
+ output.write('Local marketplace detected; skipping Git refresh.\n')
834
+ } else {
835
+ assertSuccess(refreshed, config.command, config.refreshArgs)
836
+ }
837
+ }
838
+ }
839
+
840
+ const pluginArgs = config.pluginArgs(options.scope)
841
+ output.write(options.command === 'update'
842
+ ? 'Installing the current plugin snapshot...\n'
843
+ : 'Installing the plugin...\n')
844
+ assertSuccess(execute(config.command, pluginArgs), config.command, pluginArgs)
845
+ output.write('Done. ' + config.nextStep + '\n')
846
+ }
847
+ }
848
+
849
+ function countOccurrences(content, value) {
850
+ return content.split(value).length - 1
851
+ }
852
+
853
+ export function planPolicyUpdate(content, policy) {
854
+ const normalizedPolicy = policy.trimEnd()
855
+ const block = BEGIN_MARKER + '\n' + normalizedPolicy + '\n' + END_MARKER
856
+ const beginCount = countOccurrences(content, BEGIN_MARKER)
857
+ const endCount = countOccurrences(content, END_MARKER)
858
+
859
+ if (beginCount === 0 && endCount === 0) {
860
+ const separator = content.length === 0 ? '' : content.endsWith('\n') ? '\n' : '\n\n'
861
+ return { changed: true, status: 'ADDED', content: content + separator + block + '\n' }
862
+ }
863
+
864
+ const start = content.indexOf(BEGIN_MARKER)
865
+ const endStart = content.indexOf(END_MARKER)
866
+ if (beginCount !== 1 || endCount !== 1 || start >= endStart) {
867
+ throw new CliError(
868
+ 'Malformed Agent OS policy markers (begin=' + beginCount + ' end=' + endCount + '); no files were changed.'
869
+ )
870
+ }
871
+
872
+ const end = endStart + END_MARKER.length
873
+ const current = content.slice(start, end)
874
+ if (current === block) return { changed: false, status: 'OK', content }
875
+ return {
876
+ changed: true,
877
+ status: 'UPDATED',
878
+ content: content.slice(0, start) + block + content.slice(end)
879
+ }
880
+ }
881
+
882
+ function preparePolicyPlans({ fsImpl, homeDir, policyFile }) {
883
+ const policy = fsImpl.readFileSync(policyFile, 'utf8')
884
+ const targets = [
885
+ path.join(homeDir, '.claude', 'CLAUDE.md'),
886
+ path.join(homeDir, '.codex', 'AGENTS.md')
887
+ ]
888
+ return targets.map((target) => {
889
+ const content = fsImpl.existsSync(target) ? fsImpl.readFileSync(target, 'utf8') : ''
890
+ return { target, ...planPolicyUpdate(content, policy) }
891
+ })
892
+ }
893
+
894
+ function applyPolicyPlans(plans, { output, fsImpl }) {
895
+ for (const plan of plans) {
896
+ if (plan.changed) {
897
+ fsImpl.mkdirSync(path.dirname(plan.target), { recursive: true })
898
+ fsImpl.writeFileSync(plan.target, plan.content)
899
+ }
900
+ output.write(plan.status.padEnd(7) + plan.target + '\n')
901
+ }
902
+ }
903
+
904
+ export async function executeInstall(options, {
905
+ output = process.stdout,
906
+ spawn = spawnSync,
907
+ execute = (command, args, runOptions) => runExternal(command, args, { ...runOptions, spawn }),
908
+ exists = (command) => commandExists(command, spawn),
909
+ fsImpl = fs,
910
+ homeDir = os.homedir(),
911
+ cwd = process.cwd(),
912
+ sourceRoot = packagedSkillsPath(),
913
+ policyFile = packagedPolicyPath()
914
+ } = {}) {
915
+ const policyPlans = options.policy
916
+ ? preparePolicyPlans({ fsImpl, homeDir, policyFile })
917
+ : null
918
+ const directPlan = options.method === 'plugin'
919
+ ? null
920
+ : prepareDirectInstall(options, { fsImpl, homeDir, cwd, sourceRoot })
921
+ const hookPlans = options.method === 'plugin'
922
+ ? null
923
+ : prepareHookPlans(options, { fsImpl, homeDir, cwd })
924
+
925
+ if (options.method === 'plugin') {
926
+ executePlugin(options, { output, execute, exists })
927
+ } else {
928
+ const rollback = prepareManagedSkillRollback(directPlan, fsImpl)
929
+ try {
930
+ applyDirectInstall(options, directPlan, { output, fsImpl })
931
+ output.write('\n[Quality ratchet hooks]\n')
932
+ applyHookPlans(hookPlans, { output, fsImpl })
933
+ } catch (cause) {
934
+ try {
935
+ rollbackManagedSkills(directPlan, rollback, fsImpl)
936
+ } catch (rollbackCause) {
937
+ throw new CliError(cause.message + '; ' + rollbackCause.message)
938
+ }
939
+ throw cause
940
+ }
941
+ try {
942
+ cleanupManagedSkillRollback(rollback, fsImpl)
943
+ } catch (cause) {
944
+ throw new CliError('Agent OS direct install committed, but failed to clean transaction backups: ' +
945
+ cause.message + '. Installed skills and hooks were not rolled back.')
946
+ }
947
+ }
948
+
949
+ if (options.policy) {
950
+ output.write('\n[Shared policy]\nSyncing the global Claude Code and Codex policy files...\n')
951
+ applyPolicyPlans(policyPlans, { output, fsImpl })
952
+ }
953
+ }
954
+
955
+ export function printHelp(output = process.stdout) {
956
+ output.write(
957
+ 'Agent OS installer ' + VERSION + '\n\n' +
958
+ 'Usage:\n' +
959
+ ' npx ' + PACKAGE_NAME + ' install\n' +
960
+ ' npx ' + PACKAGE_NAME + ' update\n\n' +
961
+ 'Direct installation is the default and does not require Codex or Claude Code CLI.\n\n' +
962
+ 'Direct installation also merges the Agent OS quality-ratchet Stop hook without replacing unrelated hooks.\n\n' +
963
+ 'Options:\n' +
964
+ ' -p, --platform <name> claude, codex, or both\n' +
965
+ ' -m, --method <name> direct (default) or plugin\n' +
966
+ ' -s, --scope <name> user or project; plugin mode also supports local\n' +
967
+ ' --policy Sync ~/.claude/CLAUDE.md and ~/.codex/AGENTS.md\n' +
968
+ ' --no-policy Leave global policy files unchanged\n' +
969
+ ' -y, --yes Accept defaults; useful in scripts\n' +
970
+ ' --dry-run Show the planned flow without running commands\n' +
971
+ ' -h, --help Show this help\n' +
972
+ ' -v, --version Show the CLI version\n\n' +
973
+ 'Examples:\n' +
974
+ ' npx ' + PACKAGE_NAME + ' install\n' +
975
+ ' npx ' + PACKAGE_NAME + ' install --platform both --yes\n' +
976
+ ' npx ' + PACKAGE_NAME + ' update --platform codex --no-policy\n' +
977
+ ' npx ' + PACKAGE_NAME + ' install --platform codex --method plugin\n' +
978
+ ' npm install --global ' + PACKAGE_NAME + '@latest\n'
979
+ )
980
+ }
981
+
982
+ export function printPlan(options, output = process.stdout, pathOptions = {}) {
983
+ output.write('Planned ' + options.command + ':\n')
984
+ for (const step of buildPlan(options, pathOptions)) {
985
+ const command = step.args.length ? formatCommand(step.command, step.args) : step.command
986
+ output.write(' - ' + step.description + ' [' + command + ']\n')
987
+ }
988
+ }
989
+
990
+ export async function run(argv = process.argv.slice(2), dependencies = {}) {
991
+ const parsed = parseArgs(argv)
992
+ if (parsed.help || parsed.command === 'help') {
993
+ printHelp(dependencies.output || process.stdout)
994
+ return 0
995
+ }
996
+ if (parsed.version) {
997
+ (dependencies.output || process.stdout).write(VERSION + '\n')
998
+ return 0
999
+ }
1000
+ const options = await resolveOptions(parsed, dependencies)
1001
+ if (options.dryRun) {
1002
+ printPlan(options, dependencies.output || process.stdout, {
1003
+ homeDir: dependencies.homeDir,
1004
+ cwd: dependencies.cwd
1005
+ })
1006
+ return 0
1007
+ }
1008
+ await executeInstall(options, dependencies)
1009
+ const output = dependencies.output || process.stdout
1010
+ output.write('\nAgent OS ' + options.command + ' completed.\n')
1011
+ output.write('To update later, use npx ' + PACKAGE_NAME + '@latest update.\n')
1012
+ return 0
1013
+ }
1014
+
1015
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
1016
+ run().then((code) => {
1017
+ process.exitCode = code
1018
+ }).catch((error) => {
1019
+ console.error('Agent OS installer: ' + error.message)
1020
+ process.exitCode = 1
1021
+ })
1022
+ }