-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.ts
More file actions
923 lines (833 loc) · 30.3 KB
/
Copy pathcli.ts
File metadata and controls
923 lines (833 loc) · 30.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
#!/usr/bin/env node
// capstan — CLI for quick provider/plan/region/placement lookup.
//
// Design notes:
// - Output is JSON by default (agent-first). Use --text for human
// line-oriented output. Errors are always JSON on stderr.
// - Offline commands read from embedded specs/*.json — no token, no
// network, sub-millisecond response time.
// - Live commands hit provider APIs and require a token via the
// conventional env vars per provider.
// - Exit codes: 0 success, 1 logic error (drift detected, unknown
// plan, etc.), 2 user error (bad args, missing token, unknown
// subcommand).
import { parseArgs, type ParseArgsConfig } from 'node:util'
import { readFileSync, readdirSync, existsSync, statSync } from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
recommendPlacement,
type Geography,
type SlaTier,
type Workload,
} from './posture.js'
import { createProvider, listImplementedProviders } from './registry.js'
import type { ProviderName } from './types.js'
import hetznerSpec from '../specs/hetzner.json' with { type: 'json' }
import digitaloceanSpec from '../specs/digitalocean.json' with { type: 'json' }
import linodeSpec from '../specs/linode.json' with { type: 'json' }
import vultrSpec from '../specs/vultr.json' with { type: 'json' }
import postureSpec from '../specs/posture.json' with { type: 'json' }
import pkg from '../package.json' with { type: 'json' }
const SPECS = {
hetzner: hetznerSpec,
digitalocean: digitaloceanSpec,
linode: linodeSpec,
vultr: vultrSpec,
} as const
const PROVIDERS: readonly ProviderName[] = ['hetzner', 'digitalocean', 'linode', 'vultr']
const WORKLOADS: readonly Workload[] = ['io-multitenant', 'cpu-latency', 'cpu-throughput', 'general']
const SLA_TIERS: readonly SlaTier[] = ['best-effort', 'standard', 'premium']
const GEOGRAPHIES: readonly Geography[] = [
'eu-central', 'eu-north', 'eu-west', 'eu-south',
'us-east', 'us-central', 'us-west',
'canada', 'singapore', 'japan', 'india',
'indonesia', 'australia', 'latam',
]
const TOKEN_ALIASES: Record<ProviderName, readonly string[]> = {
hetzner: ['HCLOUD_TOKEN', 'HETZNER_API_TOKEN', 'HETZNER_TOKEN'],
digitalocean: [
'DIGITALOCEAN_TOKEN', 'DIGITALOCEAN_ACCESS_TOKEN',
'DOCTL_ACCESS_TOKEN', 'DO_API_KEY', 'DO_TOKEN',
],
linode: ['LINODE_TOKEN', 'LINODE_CLI_TOKEN'],
vultr: ['VULTR_API_KEY', 'VULTR_TOKEN'],
}
// ─── Output helpers ────────────────────────────────────────────────
interface EmitOpts {
text?: boolean
}
export function emit<T>(
data: T,
textRenderer?: (data: T) => string,
opts: EmitOpts = {},
): void {
if (opts.text && textRenderer) {
process.stdout.write(textRenderer(data) + '\n')
} else {
process.stdout.write(JSON.stringify(data, null, 2) + '\n')
}
}
// Narrow parseArgs values (which are typed string|boolean|undefined under
// strict:false) into our EmitOpts. Keeps each command body a one-liner.
function optsOf(values: { text?: string | boolean }): EmitOpts {
return { text: Boolean(values.text) }
}
export function emitError(message: string, code: string, exit = 1): never {
process.stderr.write(JSON.stringify({ ok: false, error: message, code }, null, 2) + '\n')
process.exit(exit)
}
// ─── Argument parsing helpers ──────────────────────────────────────
const commonOpts: ParseArgsConfig['options'] = {
text: { type: 'boolean' },
help: { type: 'boolean', short: 'h' },
}
// ─── Input hardening ───────────────────────────────────────────────
//
// Agents hallucinate differently than humans typo. They tend to:
// - Embed query parameters in identifiers ("cx23?fields=name")
// - Generate invisible control characters from broken string handling
// - Pre-URL-encode strings expecting double-encoding ("%2e%2e")
// - Splice path segments ("../../.ssh") by confusing path math
//
// The CLI is the last validation point before we forward an identifier
// to a provider API. Reject these classes of input loudly with a stable
// error code rather than silently sanitizing — silent sanitization
// trains agents that wrong input "works" and the bug surfaces deeper.
const CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/
const SUSPICIOUS_CHAR_RE = /[?#%&<>\\\s]/
export function rejectControlChars(value: string, field: string): void {
if (CONTROL_CHAR_RE.test(value)) {
emitError(
`${field} contains a control character (likely agent string-handling bug); strip and retry`,
'bad_arg',
2,
)
}
}
export function rejectQueryInjection(value: string, field: string): void {
if (SUSPICIOUS_CHAR_RE.test(value)) {
emitError(
`${field} contains an unsafe character (one of ?#%&<>\\ or whitespace); identifiers must be bare slugs`,
'bad_arg',
2,
)
}
}
// Combined helper for the common "validate a slug-like identifier" case.
function checkSlug(value: string, field: string): void {
rejectControlChars(value, field)
rejectQueryInjection(value, field)
}
export function assertProvider(name: string | undefined): asserts name is ProviderName {
if (!name) {
emitError('provider name required', 'missing_arg', 2)
}
checkSlug(name, 'provider')
if (!(PROVIDERS as readonly string[]).includes(name)) {
emitError(
`unknown provider: ${name}. supported: ${PROVIDERS.join(', ')}`,
'unknown_provider',
2,
)
}
}
// ─── Offline subcommands ───────────────────────────────────────────
export function cmdProviders(argv: string[]): void {
const { values } = parseArgs({ args: argv, options: commonOpts, strict: false })
emit(
{ ok: true, providers: [...PROVIDERS] },
(d) => d.providers.join('\n'),
optsOf(values),
)
}
export function cmdWorkloads(argv: string[]): void {
const { values } = parseArgs({ args: argv, options: commonOpts, strict: false })
emit(
{ ok: true, workloads: [...WORKLOADS] },
(d) => d.workloads.join('\n'),
optsOf(values),
)
}
export function cmdSlaTiers(argv: string[]): void {
const { values } = parseArgs({ args: argv, options: commonOpts, strict: false })
emit(
{ ok: true, slaTiers: [...SLA_TIERS] },
(d) => d.slaTiers.join('\n'),
optsOf(values),
)
}
export function cmdGeographies(argv: string[]): void {
const { values } = parseArgs({ args: argv, options: commonOpts, strict: false })
emit(
{ ok: true, geographies: [...GEOGRAPHIES] },
(d) => d.geographies.join('\n'),
optsOf(values),
)
}
export function cmdPlans(argv: string[]): void {
const { values, positionals } = parseArgs({
args: argv,
options: {
text: { type: 'boolean' },
help: { type: 'boolean', short: 'h' },
ndjson: { type: 'boolean' },
fields: { type: 'string' },
},
allowPositionals: true,
strict: false,
})
const providerName = positionals[0]
assertProvider(providerName)
const spec = SPECS[providerName]
let plans: Array<Record<string, unknown>> = Object.entries(spec.priceCents)
.map(([id, cents]) => ({
id,
priceMonthlyCents: cents,
priceCurrency: spec.priceCurrency,
}))
.sort(
(a, b) =>
(a.priceMonthlyCents as number) - (b.priceMonthlyCents as number),
)
// --fields a,b,c — narrow each plan object to only the requested keys.
// Cuts agent token usage when the caller only needs `id,priceMonthlyCents`.
if (typeof values.fields === 'string' && values.fields.length > 0) {
const requested = values.fields
.split(',')
.map((s) => s.trim())
.filter(Boolean)
for (const f of requested) checkSlug(f, '--fields entry')
const allowed = new Set(['id', 'priceMonthlyCents', 'priceCurrency'])
for (const f of requested) {
if (!allowed.has(f)) {
emitError(
`unknown field "${f}"; allowed: ${[...allowed].join(', ')}`,
'bad_arg',
2,
)
}
}
plans = plans.map((p) => {
const filtered: Record<string, unknown> = {}
for (const k of requested) filtered[k] = p[k]
return filtered
})
}
// --ndjson — emit one plan per line. Streamable, agent-friendly when
// the caller only needs to iterate; avoids buffering a top-level array
// into context. The `{ok, provider, currency}` envelope is dropped in
// ndjson mode — callers who need it should not pass --ndjson.
if (values.ndjson) {
for (const p of plans) process.stdout.write(JSON.stringify(p) + '\n')
return
}
emit(
{ ok: true, provider: providerName, currency: spec.priceCurrency, plans },
(d) =>
d.plans
.map((p) => `${p.id ?? ''}\t${p.priceMonthlyCents ?? ''} ${p.priceCurrency ?? d.currency}`)
.join('\n'),
optsOf(values),
)
}
export function cmdPrice(argv: string[]): void {
const { values, positionals } = parseArgs({
args: argv,
options: commonOpts,
allowPositionals: true,
strict: false,
})
const providerName = positionals[0]
const planId = positionals[1]
assertProvider(providerName)
if (!planId) emitError('plan id required', 'missing_arg', 2)
checkSlug(planId, 'plan')
const spec = SPECS[providerName]
const cents = (spec.priceCents as Record<string, number>)[planId]
if (cents === undefined) {
emitError(
`plan "${planId}" not found in ${providerName} spec; run \`capstan plans ${providerName}\` to list valid plans`,
'unknown_plan',
1,
)
}
emit(
{
ok: true,
provider: providerName,
plan: planId,
priceMonthlyCents: cents,
priceCurrency: spec.priceCurrency,
},
(d) => `${d.priceMonthlyCents} ${d.priceCurrency} /mo`,
optsOf(values),
)
}
export function cmdRecommend(argv: string[]): void {
const { values } = parseArgs({
args: argv,
options: {
text: { type: 'boolean' },
help: { type: 'boolean', short: 'h' },
geo: { type: 'string' },
workload: { type: 'string' },
sla: { type: 'string' },
},
strict: false,
})
if (!values.geo) {
emitError(
'missing --geo flag. valid values: ' + GEOGRAPHIES.join(', '),
'missing_arg',
2,
)
}
const geo = values.geo as string
checkSlug(geo, '--geo')
if (!(GEOGRAPHIES as readonly string[]).includes(geo)) {
emitError(`unknown geography: ${geo}. supported: ${GEOGRAPHIES.join(', ')}`, 'bad_arg', 2)
}
if (values.workload !== undefined) {
checkSlug(values.workload as string, '--workload')
if (!(WORKLOADS as readonly string[]).includes(values.workload as string)) {
emitError(
`unknown workload: ${values.workload}. supported: ${WORKLOADS.join(', ')}`,
'bad_arg',
2,
)
}
}
if (values.sla !== undefined) {
checkSlug(values.sla as string, '--sla')
if (!(SLA_TIERS as readonly string[]).includes(values.sla as string)) {
emitError(
`unknown sla tier: ${values.sla}. supported: ${SLA_TIERS.join(', ')}`,
'bad_arg',
2,
)
}
}
try {
const rec = recommendPlacement({
geography: geo as Geography,
workload: (values.workload as Workload) ?? 'general',
sla: (values.sla as SlaTier) ?? 'standard',
})
emit(
{ ok: true, ...rec },
(d) =>
[
`primary: ${d.primary.provider}/${d.primary.region}/${d.primary.size}`,
...(d.fallbacks.length
? ['fallbacks:', ...d.fallbacks.map((p) => ` ${p.provider}/${p.region}/${p.size}`)]
: []),
...(d.caveats.length ? ['caveats:', ...d.caveats.map((c) => ` - ${c}`)] : []),
].join('\n'),
optsOf(values),
)
} catch (err) {
emitError(String(err instanceof Error ? err.message : err), 'recommend_failed', 1)
}
}
// ─── `describe` — schema introspection ─────────────────────────────
//
// Agents can `capstan describe <command>` to learn the args, flags, and
// output shape at runtime — cheaper than reading --help text or stuffing
// docs into a prompt. The CLI is the canonical source of truth for its
// own schema, so this never drifts from reality.
interface CommandSchema {
positional: { name: string; required: boolean; values?: readonly string[] }[]
flags: { name: string; type: string; description: string }[]
outputKeys: readonly string[]
exitCodes: Record<string, string>
}
const SCHEMAS: Record<string, CommandSchema> = {
providers: {
positional: [],
flags: [{ name: '--text', type: 'boolean', description: 'human-readable output' }],
outputKeys: ['ok', 'providers'],
exitCodes: { '0': 'success' },
},
workloads: {
positional: [],
flags: [{ name: '--text', type: 'boolean', description: 'human-readable output' }],
outputKeys: ['ok', 'workloads'],
exitCodes: { '0': 'success' },
},
'sla-tiers': {
positional: [],
flags: [{ name: '--text', type: 'boolean', description: 'human-readable output' }],
outputKeys: ['ok', 'slaTiers'],
exitCodes: { '0': 'success' },
},
geographies: {
positional: [],
flags: [{ name: '--text', type: 'boolean', description: 'human-readable output' }],
outputKeys: ['ok', 'geographies'],
exitCodes: { '0': 'success' },
},
plans: {
positional: [{ name: 'provider', required: true, values: PROVIDERS }],
flags: [
{ name: '--text', type: 'boolean', description: 'human-readable output' },
{ name: '--ndjson', type: 'boolean', description: 'one plan per line; drops envelope' },
{ name: '--fields', type: 'string', description: 'comma-separated subset of: id, priceMonthlyCents, priceCurrency' },
],
outputKeys: ['ok', 'provider', 'currency', 'plans'],
exitCodes: { '0': 'success', '2': 'missing or unknown provider; bad field name' },
},
price: {
positional: [
{ name: 'provider', required: true, values: PROVIDERS },
{ name: 'plan', required: true },
],
flags: [{ name: '--text', type: 'boolean', description: 'human-readable output' }],
outputKeys: ['ok', 'provider', 'plan', 'priceMonthlyCents', 'priceCurrency'],
exitCodes: { '0': 'success', '1': 'unknown_plan (spec drift candidate)', '2': 'bad args' },
},
recommend: {
positional: [],
flags: [
{ name: '--geo', type: 'string', description: 'geography (required); see `capstan geographies`' },
{ name: '--workload', type: 'string', description: 'workload class; default "general"' },
{ name: '--sla', type: 'string', description: 'SLA tier; default "standard"' },
{ name: '--text', type: 'boolean', description: 'human-readable output' },
],
outputKeys: ['ok', 'primary', 'fallbacks', 'caveats'],
exitCodes: { '0': 'success', '2': 'missing or bad arg' },
},
describe: {
positional: [{ name: 'command', required: false }],
flags: [{ name: '--text', type: 'boolean', description: 'human-readable output' }],
outputKeys: ['ok', 'command', 'positional', 'flags', 'outputKeys', 'exitCodes'],
exitCodes: { '0': 'success', '2': 'unknown command' },
},
skill: {
positional: [{ name: 'name', required: false }],
flags: [{ name: '--text', type: 'boolean', description: 'no-op (skill output is already markdown text)' }],
outputKeys: ['ok', 'skills'],
exitCodes: { '0': 'success', '1': 'unknown skill', '2': 'bad arg' },
},
list: {
positional: [{ name: 'provider', required: true, values: PROVIDERS }],
flags: [
{ name: '--text', type: 'boolean', description: 'human-readable output' },
{ name: '--ndjson', type: 'boolean', description: 'one VPS per line' },
{ name: '--fields', type: 'string', description: 'comma-separated subset of VPS keys' },
],
outputKeys: ['ok', 'provider', 'vpses'],
exitCodes: { '0': 'success', '1': 'auth or network failure', '2': 'bad args or no token' },
},
drift: {
positional: [{ name: 'provider', required: true, values: PROVIDERS }],
flags: [{ name: '--text', type: 'boolean', description: 'human-readable output' }],
outputKeys: ['ok', 'provider', 'inSync', 'onlyInSpec', 'onlyInAPI', 'hasDrift'],
exitCodes: { '0': 'no drift', '1': 'drift detected (or network/auth failure)', '2': 'no token; for public-catalog providers, use Go binary capstan-spec-check' },
},
destroy: {
positional: [
{ name: 'provider', required: true, values: PROVIDERS },
{ name: 'id', required: true },
],
flags: [
{ name: '--text', type: 'boolean', description: 'human-readable output' },
{ name: '--yes', type: 'boolean', description: 'actually destroy (default is dry-run)' },
{ name: '--dry-run', type: 'boolean', description: 'explicit dry-run; overrides --yes' },
],
outputKeys: ['ok', 'mode', 'wouldDestroy', 'destroyed', 'hint'],
exitCodes: {
'0': 'success (dry-run or actual destroy)',
'1': 'not_found, auth, or network failure',
'2': 'bad args or no token',
},
},
}
export function cmdDescribe(argv: string[]): void {
const { values, positionals } = parseArgs({
args: argv,
options: commonOpts,
allowPositionals: true,
strict: false,
})
const target = positionals[0]
if (!target) {
// No target → list all command names
emit(
{ ok: true, commands: Object.keys(SCHEMAS).sort() },
(d) => d.commands.join('\n'),
optsOf(values),
)
return
}
checkSlug(target, 'command')
const schema = SCHEMAS[target]
if (!schema) {
emitError(
`no schema for command "${target}"; run \`capstan describe\` for the list`,
'unknown_subcommand',
2,
)
}
emit(
{ ok: true, command: target, ...schema },
(d) => JSON.stringify(d, null, 2),
optsOf(values),
)
}
// ─── Token resolution for live commands ───────────────────────────
export function resolveToken(provider: ProviderName): { token: string; source: string } {
for (const name of TOKEN_ALIASES[provider]) {
const v = process.env[name]
if (v) return { token: v, source: name }
}
return { token: '', source: TOKEN_ALIASES[provider].join(' or ') }
}
// ─── `list <provider>` — live VPS list ─────────────────────────────
export async function cmdList(argv: string[], deps: LiveDeps = {}): Promise<void> {
const { values, positionals } = parseArgs({
args: argv,
options: {
text: { type: 'boolean' },
help: { type: 'boolean', short: 'h' },
ndjson: { type: 'boolean' },
fields: { type: 'string' },
},
allowPositionals: true,
strict: false,
})
const providerName = positionals[0]
assertProvider(providerName)
const { token, source } = resolveToken(providerName)
if (!token) {
emitError(
`no token in env for ${providerName} (set ${source})`,
'no_token',
2,
)
}
const make = deps.createProvider ?? createProvider
const p = make(providerName, { token, fetchImpl: deps.fetchImpl })
let vpses
try {
vpses = await p.listVPS()
} catch (err) {
const e = err as { code?: string; message?: string; status?: number }
emitError(
e.message ?? String(err),
e.code === 'unauthorized' ? 'auth' : 'network',
1,
)
}
let items: Array<Record<string, unknown>> = vpses.map((v) => ({ ...v }))
if (typeof values.fields === 'string' && values.fields.length > 0) {
const requested = values.fields
.split(',')
.map((s) => s.trim())
.filter(Boolean)
for (const f of requested) checkSlug(f, '--fields entry')
items = items.map((item) => {
const filtered: Record<string, unknown> = {}
for (const k of requested) filtered[k] = item[k]
return filtered
})
}
if (values.ndjson) {
for (const v of items) process.stdout.write(JSON.stringify(v) + '\n')
return
}
emit(
{ ok: true, provider: providerName, vpses: items },
(d) =>
d.vpses
.map((v) => `${v.id ?? ''}\t${v.name ?? ''}\t${v.status ?? ''}\t${v.publicIPv4 ?? ''}`)
.join('\n'),
optsOf(values),
)
}
// ─── `drift <provider>` — live spec drift ──────────────────────────
export async function cmdDrift(argv: string[], deps: LiveDeps = {}): Promise<void> {
const { values, positionals } = parseArgs({
args: argv,
options: commonOpts,
allowPositionals: true,
strict: false,
})
const providerName = positionals[0]
assertProvider(providerName)
const { token, source } = resolveToken(providerName)
if (!token) {
emitError(
`no token in env for ${providerName} (set ${source}); for Linode/Vultr public catalog drift, run \`capstan-spec-check --provider ${providerName}\` (Go binary)`,
'no_token',
2,
)
}
const make = deps.createProvider ?? createProvider
const p = make(providerName, { token, fetchImpl: deps.fetchImpl })
let sizes
try {
sizes = await p.listSizes()
} catch (err) {
const e = err as { code?: string; message?: string }
emitError(e.message ?? String(err), e.code === 'unauthorized' ? 'auth' : 'network', 1)
}
const apiIds = new Set(sizes.map((s) => s.id))
const spec = SPECS[providerName]
const onlyInSpec: Array<{ id: string; priceMonthlyCents: number }> = []
const onlyInAPI: string[] = []
let inSync = 0
for (const [id, cents] of Object.entries(spec.priceCents)) {
if (apiIds.has(id)) inSync++
else onlyInSpec.push({ id, priceMonthlyCents: cents })
}
for (const id of apiIds) {
if (!(id in spec.priceCents)) onlyInAPI.push(id)
}
onlyInSpec.sort((a, b) => a.id.localeCompare(b.id))
onlyInAPI.sort()
const hasDrift = onlyInSpec.length > 0 || onlyInAPI.length > 0
emit(
{
ok: true,
provider: providerName,
inSync,
onlyInSpec,
onlyInAPI,
hasDrift,
},
(d) =>
[
`in sync: ${d.inSync}`,
d.onlyInSpec.length
? `deprecated (in spec, not in API):\n ${d.onlyInSpec.map((x) => x.id).join('\n ')}`
: '',
d.onlyInAPI.length
? `new (in API, not in spec):\n ${d.onlyInAPI.join('\n ')}`
: '',
]
.filter(Boolean)
.join('\n'),
optsOf(values),
)
if (hasDrift) process.exit(1)
}
// ─── `destroy <provider> <id>` — destructive op with safety rails ─
//
// Per Justin Poehnelt's "rewrite for agents" guidance: mutating
// operations need an explicit gate so agents can "think out loud"
// before committing. Default behavior here is DRY-RUN — we Get the
// server, show what would be destroyed, and exit ok without
// touching it. Pass --yes to actually destroy. --dry-run is also
// accepted explicitly for callers that want to be unambiguous.
export async function cmdDestroy(argv: string[], deps: LiveDeps = {}): Promise<void> {
const { values, positionals } = parseArgs({
args: argv,
options: {
text: { type: 'boolean' },
help: { type: 'boolean', short: 'h' },
'dry-run': { type: 'boolean' },
yes: { type: 'boolean' },
},
allowPositionals: true,
strict: false,
})
const providerName = positionals[0]
const id = positionals[1]
assertProvider(providerName)
if (!id) emitError('server id required', 'missing_arg', 2)
checkSlug(id, 'server id')
const { token, source } = resolveToken(providerName)
if (!token) {
emitError(`no token in env for ${providerName} (set ${source})`, 'no_token', 2)
}
const make = deps.createProvider ?? createProvider
const p = make(providerName, { token, fetchImpl: deps.fetchImpl })
// Confirm the server exists and show what it is before any mutation.
let server
try {
server = await p.getVPS(id)
} catch (err) {
const e = err as { code?: string; message?: string }
emitError(e.message ?? String(err), e.code === 'unauthorized' ? 'auth' : 'network', 1)
}
if (!server) {
emitError(`server "${id}" not found in ${providerName} account`, 'not_found', 1)
}
const wantsExecute = Boolean(values.yes) && !values['dry-run']
if (!wantsExecute) {
emit(
{
ok: true,
mode: 'dry-run',
provider: providerName,
wouldDestroy: server,
hint: 'pass --yes to actually destroy; this default-dry-run is a safety gate for agent callers',
},
(d) =>
[
'DRY RUN — would destroy:',
` ${d.wouldDestroy.name} (${d.wouldDestroy.id})`,
` status: ${d.wouldDestroy.status}`,
` ipv4: ${d.wouldDestroy.publicIPv4 ?? '(none)'}`,
` region: ${d.wouldDestroy.region ?? '(unknown)'}`,
` size: ${d.wouldDestroy.size ?? '(unknown)'}`,
'',
'Re-run with --yes to actually destroy.',
].join('\n'),
optsOf(values),
)
return
}
try {
await p.destroyVPS(id)
} catch (err) {
const e = err as { code?: string; message?: string }
emitError(e.message ?? String(err), e.code === 'unauthorized' ? 'auth' : 'network', 1)
}
emit(
{ ok: true, destroyed: { provider: providerName, id, name: server.name } },
(d) => `destroyed ${d.destroyed.name} (${d.destroyed.id})`,
optsOf(values),
)
}
interface LiveDeps {
fetchImpl?: typeof fetch
createProvider?: typeof createProvider
}
// ─── `skill` — emit bundled agent skills ───────────────────────────
//
// Agents discovering capstan organically (via `npx capstan` after
// finding the package on npm) get to its skill via the `skill` command;
// the same SKILL.md file is also resolved by skills.sh when a user runs
// `npx skills add solcreek/capstan`. One source of truth, two surfaces.
// Locate the skills/ directory at runtime. The CLI lives in dist/cli.js
// after build, so skills/ is two levels up. In dev (running from src/),
// resolve relative to the source file instead.
function skillsRoot(): string {
const here = dirname(fileURLToPath(import.meta.url))
// Try dist/cli.js -> repo/skills, then src/cli.ts -> repo/skills.
const distLevel = resolve(here, '..', 'skills')
const srcLevel = resolve(here, '..', '..', 'skills')
for (const c of [distLevel, srcLevel]) {
if (existsSync(c) && statSync(c).isDirectory()) return c
}
return distLevel
}
export function cmdSkill(argv: string[]): void {
const { values, positionals } = parseArgs({
args: argv,
options: commonOpts,
allowPositionals: true,
strict: false,
})
const root = skillsRoot()
const target = positionals[0]
if (!target) {
let skills: string[] = []
try {
skills = readdirSync(root, { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => d.name)
.sort()
} catch {
// No skills/ dir → empty list
}
emit(
{ ok: true, skills },
(d) => (d.skills.length ? d.skills.join('\n') : '(no bundled skills)'),
optsOf(values),
)
return
}
checkSlug(target, 'skill name')
const skillPath = join(root, target, 'SKILL.md')
if (!existsSync(skillPath)) {
emitError(
`skill "${target}" not found in ${root}; run \`capstan skill\` for the list`,
'unknown_skill',
1,
)
}
const content = readFileSync(skillPath, 'utf8')
// Always print raw markdown — the format is meant for agent context
// injection. The --text flag is accepted but has no semantic
// difference here since the markdown IS the textual representation.
process.stdout.write(content)
if (!content.endsWith('\n')) process.stdout.write('\n')
}
// ─── Dispatch ──────────────────────────────────────────────────────
const SUBCOMMANDS: Record<string, (argv: string[]) => void | Promise<void>> = {
providers: cmdProviders,
workloads: cmdWorkloads,
'sla-tiers': cmdSlaTiers,
geographies: cmdGeographies,
plans: cmdPlans,
price: cmdPrice,
recommend: cmdRecommend,
describe: cmdDescribe,
skill: cmdSkill,
list: (argv) => cmdList(argv),
drift: (argv) => cmdDrift(argv),
destroy: (argv) => cmdDestroy(argv),
}
const HELP = `capstan — multi-provider VPS lookup CLI
USAGE
capstan <command> [args...] [--text]
OFFLINE COMMANDS (no token, instant)
providers List supported providers
workloads List workload classes
sla-tiers List SLA tiers
geographies List geographies
plans <provider> List plans (size + price) from spec
price <provider> <plan> Single plan monthly price (cents)
recommend --geo <g> [--workload] [--sla] Placement recommendation
AGENT-FIRST FEATURES
describe [command] Schema for a command (or list all)
skill [name] Emit a bundled agent skill (markdown)
LIVE COMMANDS (need token)
list <provider> List current VPSes for the account
drift <provider> Live spec drift vs provider API
destroy <provider> <id> [--yes] Destroy a VPS (default = dry-run)
GLOBAL FLAGS
--text Human-readable output (default: JSON for agent use)
-h, --help Show this help
-v, --version Print version
Token aliases (when a future live command needs auth):
hetzner HCLOUD_TOKEN | HETZNER_API_TOKEN | HETZNER_TOKEN
digitalocean DIGITALOCEAN_TOKEN | DIGITALOCEAN_ACCESS_TOKEN |
DOCTL_ACCESS_TOKEN | DO_API_KEY | DO_TOKEN
linode LINODE_TOKEN | LINODE_CLI_TOKEN
vultr VULTR_API_KEY | VULTR_TOKEN
`
export async function main(argv: string[]): Promise<void> {
const [sub, ...rest] = argv
if (!sub || sub === '--help' || sub === '-h') {
process.stdout.write(HELP)
return
}
if (sub === '--version' || sub === '-v') {
emit(
{ ok: true, version: pkg.version, name: 'capstan' },
(d) => d.version,
{ text: argv.includes('--text') },
)
return
}
const handler = SUBCOMMANDS[sub]
if (!handler) {
emitError(
`unknown subcommand: ${sub}. run \`capstan --help\` for the list`,
'unknown_subcommand',
2,
)
}
await handler(rest)
}
// Reference touched so tsc doesn't strip the import in CLI-only builds.
void listImplementedProviders
void postureSpec
// Run main when invoked directly (not when imported by tests).
if (import.meta.url === `file://${process.argv[1]}`) {
void main(process.argv.slice(2))
}