@sixb/cli 0.1.5 → 0.1.7

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 (54) hide show
  1. package/README.md +125 -18
  2. package/dist/commands/init.d.ts +0 -1
  3. package/dist/commands/init.d.ts.map +1 -1
  4. package/dist/commands/login.d.ts +8 -0
  5. package/dist/commands/login.d.ts.map +1 -0
  6. package/dist/commands/logout.d.ts +6 -0
  7. package/dist/commands/logout.d.ts.map +1 -0
  8. package/dist/commands/profile.d.ts +7 -0
  9. package/dist/commands/profile.d.ts.map +1 -0
  10. package/dist/commands/service-account.d.ts +1 -0
  11. package/dist/commands/service-account.d.ts.map +1 -1
  12. package/dist/commands/status.d.ts +8 -0
  13. package/dist/commands/status.d.ts.map +1 -0
  14. package/dist/commands/token.d.ts +1 -0
  15. package/dist/commands/token.d.ts.map +1 -1
  16. package/dist/lib/api-client.d.ts +0 -11
  17. package/dist/lib/api-client.d.ts.map +1 -1
  18. package/dist/lib/command-line.d.ts +176 -0
  19. package/dist/lib/command-line.d.ts.map +1 -0
  20. package/dist/lib/errors.d.ts +6 -0
  21. package/dist/lib/errors.d.ts.map +1 -1
  22. package/dist/lib/instance-command.d.ts +3 -0
  23. package/dist/lib/instance-command.d.ts.map +1 -0
  24. package/dist/lib/loadSixb.d.ts.map +1 -1
  25. package/dist/lib/profile-api-client.d.ts +6 -0
  26. package/dist/lib/profile-api-client.d.ts.map +1 -0
  27. package/dist/lib/profiles.d.ts +34 -0
  28. package/dist/lib/profiles.d.ts.map +1 -0
  29. package/dist/lib/runtime.d.ts.map +1 -1
  30. package/dist/lib/worker-registry.d.ts.map +1 -1
  31. package/dist/ui/index.d.ts +5 -5
  32. package/dist/ui/index.d.ts.map +1 -1
  33. package/package.json +15 -14
  34. package/src/commands/init.tsx +1 -13
  35. package/src/commands/login.tsx +196 -0
  36. package/src/commands/logout.tsx +36 -0
  37. package/src/commands/profile.tsx +101 -0
  38. package/src/commands/service-account.tsx +18 -15
  39. package/src/commands/status.tsx +93 -0
  40. package/src/commands/token.tsx +11 -8
  41. package/src/index.tsx +134 -156
  42. package/src/lib/api-client.ts +4 -65
  43. package/src/lib/command-line.ts +743 -0
  44. package/src/lib/errors.ts +13 -0
  45. package/src/lib/instance-command.ts +80 -0
  46. package/src/lib/loadSixb.ts +0 -2
  47. package/src/lib/profile-api-client.ts +38 -0
  48. package/src/lib/profiles.ts +262 -0
  49. package/src/lib/runtime.ts +7 -1
  50. package/src/lib/worker-registry.ts +7 -1
  51. package/src/ui/index.tsx +39 -140
  52. package/dist/commands/auth.d.ts +0 -8
  53. package/dist/commands/auth.d.ts.map +0 -1
  54. package/src/commands/auth.tsx +0 -96
@@ -0,0 +1,743 @@
1
+ import { INSTANCE_COMMANDS, type InstanceCommand } from "@sixb/cli-core"
2
+
3
+ type OptionKind = "boolean" | "string"
4
+
5
+ export const CLI_OPTION_DEFINITIONS = {
6
+ entry: {
7
+ syntax: "--entry <path>",
8
+ summary: "Entry file (default: sixb.config.ts)",
9
+ kind: "string",
10
+ },
11
+ "no-migrate": {
12
+ syntax: "--no-migrate",
13
+ summary: "Start a role without migrating storage (or SIXB_SKIP_MIGRATION=1)",
14
+ kind: "boolean",
15
+ },
16
+ port: { syntax: "--port <port>", summary: "Role port; dev uses Atlas base port", kind: "string" },
17
+ host: {
18
+ syntax: "--host <host>",
19
+ summary: "Bind host (dev: 127.0.0.1, production roles: 0.0.0.0)",
20
+ kind: "string",
21
+ },
22
+ "api-port": {
23
+ syntax: "--api-port <port>",
24
+ summary: "API port (default: Atlas port + 2)",
25
+ kind: "string",
26
+ },
27
+ "api-host": {
28
+ syntax: "--api-host <host>",
29
+ summary: "API bind host (default: --host)",
30
+ kind: "string",
31
+ },
32
+ "api-public-origin": {
33
+ syntax: "--api-public-origin <origin>",
34
+ summary: "Public API origin",
35
+ kind: "string",
36
+ },
37
+ "agent-turn-timeout": {
38
+ syntax: "--agent-turn-timeout <duration>",
39
+ summary: "Agent turn wall-clock budget (default: 10m)",
40
+ kind: "string",
41
+ },
42
+ concurrency: {
43
+ syntax: "--concurrency <value>",
44
+ summary: "Concurrent jobs: count for worker; repeat type=count for dev/worker-group",
45
+ kind: "string",
46
+ },
47
+ "atlas-public-origin": {
48
+ syntax: "--atlas-public-origin <origin>",
49
+ summary: "Public Atlas origin",
50
+ kind: "string",
51
+ },
52
+ "app-public-origin": {
53
+ syntax: "--app-public-origin <origin>",
54
+ summary: "Public custom app origin",
55
+ kind: "string",
56
+ },
57
+ profile: { syntax: "--profile <name>", summary: "Use a saved API profile", kind: "string" },
58
+ "api-url": {
59
+ syntax: "--api-url <url>",
60
+ summary: "Use an API without a saved profile",
61
+ kind: "string",
62
+ },
63
+ token: {
64
+ syntax: "--token <token>",
65
+ summary: "Bearer token for an explicit API URL",
66
+ kind: "string",
67
+ },
68
+ "token-stdin": {
69
+ syntax: "--token-stdin",
70
+ summary: "Import a login token from standard input",
71
+ kind: "boolean",
72
+ },
73
+ id: { syntax: "--id <id>", summary: "Token or service-account id", kind: "string" },
74
+ name: { syntax: "--name <name>", summary: "Token or service-account name", kind: "string" },
75
+ description: {
76
+ syntax: "--description <text>",
77
+ summary: "Service-account description",
78
+ kind: "string",
79
+ },
80
+ "expires-in": {
81
+ syntax: "--expires-in <duration>",
82
+ summary: "Token lifetime, e.g. 30d or 1y",
83
+ kind: "string",
84
+ },
85
+ "expires-at": {
86
+ syntax: "--expires-at <iso>",
87
+ summary: "Token expiration timestamp",
88
+ kind: "string",
89
+ },
90
+ group: { syntax: "--group <id>", summary: "Assignable token group; may repeat", kind: "string" },
91
+ json: { syntax: "--json", summary: "Print JSON for management commands", kind: "boolean" },
92
+ outdir: { syntax: "--outdir <path>", summary: "Build output directory", kind: "string" },
93
+ "dry-run": {
94
+ syntax: "--dry-run",
95
+ summary: "Preview lake cleanup without changing storage",
96
+ kind: "boolean",
97
+ },
98
+ "expire-older-than": {
99
+ syntax: "--expire-older-than <interval>",
100
+ summary: "Lake snapshot expiration window",
101
+ kind: "string",
102
+ },
103
+ "delete-older-than": {
104
+ syntax: "--delete-older-than <interval>",
105
+ summary: "Lake file deletion window",
106
+ kind: "string",
107
+ },
108
+ } as const satisfies Record<string, { syntax: string; summary: string; kind: OptionKind }>
109
+
110
+ export type CliOptionName = keyof typeof CLI_OPTION_DEFINITIONS
111
+ export type LocalCommandId =
112
+ | "dev"
113
+ | "api"
114
+ | "atlas"
115
+ | "app"
116
+ | "login"
117
+ | "logout"
118
+ | "status"
119
+ | "profile:list"
120
+ | "profile:show"
121
+ | "profile:use"
122
+ | "token:list"
123
+ | "token:create"
124
+ | "token:revoke"
125
+ | "service-account:list"
126
+ | "service-account:create"
127
+ | "service-account:disable"
128
+ | "service-account:token:list"
129
+ | "service-account:token:create"
130
+ | "service-account:token:revoke"
131
+ | "scheduler"
132
+ | "orchestrator"
133
+ | "rules"
134
+ | "worker"
135
+ | "worker-group"
136
+ | "check"
137
+ | "typegen"
138
+ | "build"
139
+ | "db:migrate"
140
+ | "lake:check"
141
+ | "lake:cleanup"
142
+ | "init"
143
+
144
+ interface CommandNode {
145
+ readonly name: string
146
+ readonly summary: string
147
+ readonly usage: string
148
+ readonly id?: LocalCommandId
149
+ readonly instance?: boolean
150
+ readonly children?: readonly CommandNode[]
151
+ readonly options?: readonly CliOptionName[]
152
+ readonly repeatable?: readonly CliOptionName[]
153
+ readonly minimumPositionals?: number
154
+ readonly maximumPositionals?: number
155
+ readonly requiredInputs?: readonly {
156
+ readonly option: CliOptionName
157
+ readonly positional: number
158
+ }[]
159
+ readonly rootHelpLabel?: string
160
+ }
161
+
162
+ const CONNECTION_OPTIONS = ["api-url", "token", "profile"] as const
163
+ const TOKEN_CREATE_OPTIONS = [
164
+ ...CONNECTION_OPTIONS,
165
+ "name",
166
+ "expires-at",
167
+ "expires-in",
168
+ "group",
169
+ "json",
170
+ ] as const
171
+ const SERVICE_ACCOUNT_CREATE_OPTIONS = [
172
+ ...CONNECTION_OPTIONS,
173
+ "id",
174
+ "name",
175
+ "description",
176
+ "expires-at",
177
+ "expires-in",
178
+ "group",
179
+ "json",
180
+ ] as const
181
+
182
+ const INSTANCE_SUMMARIES = {
183
+ project: "Show project metadata",
184
+ ontology: "Inspect the visible ontology",
185
+ objects: "Inspect, list, search, and query objects",
186
+ telemetry: "Read current and historical telemetry",
187
+ actions: "Discover and request actions",
188
+ "action-runs": "Inspect action execution history",
189
+ files: "Upload and download files",
190
+ workflows: "Discover and start workflows",
191
+ "workflow-runs": "Inspect workflow execution history",
192
+ } as const satisfies Record<InstanceCommand, string>
193
+
194
+ const instanceNodes: readonly CommandNode[] = INSTANCE_COMMANDS.map((name) => ({
195
+ name,
196
+ summary: INSTANCE_SUMMARIES[name],
197
+ usage: `sixb ${name} --help`,
198
+ instance: true,
199
+ rootHelpLabel:
200
+ name === "project" ? "project show" : name === "ontology" ? "ontology list|get" : `${name} ...`,
201
+ }))
202
+
203
+ const commandTree: readonly CommandNode[] = [
204
+ command("dev", "Start local development (server + built-in UI + app)", {
205
+ options: [
206
+ "entry",
207
+ "port",
208
+ "host",
209
+ "api-port",
210
+ "api-host",
211
+ "api-public-origin",
212
+ "agent-turn-timeout",
213
+ "concurrency",
214
+ "atlas-public-origin",
215
+ "app-public-origin",
216
+ ],
217
+ repeatable: ["concurrency"],
218
+ }),
219
+ command("api", "Start production API/docs/WebSocket server", {
220
+ options: [
221
+ "entry",
222
+ "no-migrate",
223
+ "port",
224
+ "host",
225
+ "api-port",
226
+ "api-host",
227
+ "api-public-origin",
228
+ "atlas-public-origin",
229
+ "app-public-origin",
230
+ ],
231
+ }),
232
+ command("atlas", "Start production Atlas UI server", {
233
+ options: ["entry", "port", "host", "api-public-origin", "atlas-public-origin"],
234
+ }),
235
+ command("app", "Start production custom app server", {
236
+ options: ["entry", "port", "host", "api-public-origin", "app-public-origin"],
237
+ }),
238
+ command("login", "Save and select a local API profile", {
239
+ usage: "sixb login <api-url> [--profile <name>] [--token-stdin]",
240
+ options: ["profile", "token-stdin", "json"],
241
+ minimumPositionals: 1,
242
+ maximumPositionals: 1,
243
+ rootHelpLabel: "login <api-url>",
244
+ }),
245
+ command("logout", "Remove a saved profile", { options: ["profile", "json"] }),
246
+ command("status", "Check the selected API profile", {
247
+ options: [...CONNECTION_OPTIONS, "json"],
248
+ }),
249
+ {
250
+ name: "profile",
251
+ summary: "Manage local API profiles",
252
+ usage: "sixb profile <list|show|use> [name]",
253
+ rootHelpLabel: "profile list|show|use",
254
+ children: [
255
+ command("profile:list", "List saved profiles", {
256
+ path: ["profile", "list"],
257
+ options: ["json"],
258
+ }),
259
+ command("profile:show", "Show a profile without exposing its token", {
260
+ path: ["profile", "show"],
261
+ usage: "sixb profile show [name]",
262
+ options: ["json"],
263
+ maximumPositionals: 1,
264
+ }),
265
+ command("profile:use", "Select the current profile", {
266
+ path: ["profile", "use"],
267
+ usage: "sixb profile use <name>",
268
+ options: ["json"],
269
+ minimumPositionals: 1,
270
+ maximumPositionals: 1,
271
+ }),
272
+ ],
273
+ },
274
+ ...instanceNodes,
275
+ {
276
+ name: "token",
277
+ summary: "Manage personal access tokens",
278
+ usage: "sixb token <list|create|revoke>",
279
+ children: [
280
+ command("token:list", "List personal access tokens", {
281
+ path: ["token", "list"],
282
+ options: [...CONNECTION_OPTIONS, "json"],
283
+ rootHelpLabel: "token list",
284
+ }),
285
+ command("token:create", "Create a personal access token", {
286
+ path: ["token", "create"],
287
+ usage: "sixb token create [name] [options]",
288
+ options: TOKEN_CREATE_OPTIONS,
289
+ repeatable: ["group"],
290
+ maximumPositionals: 1,
291
+ requiredInputs: [{ option: "name", positional: 0 }],
292
+ rootHelpLabel: "token create",
293
+ }),
294
+ command("token:revoke", "Revoke a personal access token", {
295
+ path: ["token", "revoke"],
296
+ usage: "sixb token revoke <token-id>",
297
+ options: [...CONNECTION_OPTIONS, "id", "json"],
298
+ maximumPositionals: 1,
299
+ requiredInputs: [{ option: "id", positional: 0 }],
300
+ rootHelpLabel: "token revoke <id>",
301
+ }),
302
+ ],
303
+ },
304
+ {
305
+ name: "service-account",
306
+ summary: "Manage service accounts",
307
+ usage: "sixb service-account <list|create|disable|token>",
308
+ children: [
309
+ command("service-account:list", "List service accounts", {
310
+ path: ["service-account", "list"],
311
+ options: [...CONNECTION_OPTIONS, "json"],
312
+ rootHelpLabel: "service-account list",
313
+ }),
314
+ command("service-account:create", "Create a service account", {
315
+ path: ["service-account", "create"],
316
+ usage: "sixb service-account create [name] [options]",
317
+ options: SERVICE_ACCOUNT_CREATE_OPTIONS,
318
+ repeatable: ["group"],
319
+ maximumPositionals: 1,
320
+ requiredInputs: [{ option: "name", positional: 0 }],
321
+ rootHelpLabel: "service-account create",
322
+ }),
323
+ command("service-account:disable", "Disable a service account", {
324
+ path: ["service-account", "disable"],
325
+ usage: "sixb service-account disable <service-account-id>",
326
+ options: [...CONNECTION_OPTIONS, "id", "json"],
327
+ maximumPositionals: 1,
328
+ requiredInputs: [{ option: "id", positional: 0 }],
329
+ rootHelpLabel: "service-account disable",
330
+ }),
331
+ {
332
+ name: "token",
333
+ summary: "Manage service-account tokens",
334
+ usage: "sixb service-account token <list|create|revoke> <service-account-id>",
335
+ rootHelpLabel: "service-account token",
336
+ children: [
337
+ command("service-account:token:list", "List service-account tokens", {
338
+ path: ["service-account", "token", "list"],
339
+ usage: "sixb service-account token list <service-account-id>",
340
+ options: [...CONNECTION_OPTIONS, "json"],
341
+ minimumPositionals: 1,
342
+ maximumPositionals: 1,
343
+ }),
344
+ command("service-account:token:create", "Create a service-account token", {
345
+ path: ["service-account", "token", "create"],
346
+ usage: "sixb service-account token create <service-account-id> [name] [options]",
347
+ options: [...CONNECTION_OPTIONS, "name", "expires-at", "expires-in", "group", "json"],
348
+ repeatable: ["group"],
349
+ minimumPositionals: 1,
350
+ maximumPositionals: 2,
351
+ requiredInputs: [{ option: "name", positional: 1 }],
352
+ }),
353
+ command("service-account:token:revoke", "Revoke a service-account token", {
354
+ path: ["service-account", "token", "revoke"],
355
+ usage: "sixb service-account token revoke <service-account-id> <token-id>",
356
+ options: [...CONNECTION_OPTIONS, "id", "json"],
357
+ minimumPositionals: 1,
358
+ maximumPositionals: 2,
359
+ requiredInputs: [{ option: "id", positional: 1 }],
360
+ }),
361
+ ],
362
+ },
363
+ ],
364
+ },
365
+ command("scheduler", "Start production scheduler event producer", {
366
+ options: ["entry", "no-migrate"],
367
+ }),
368
+ command("orchestrator", "Start production event-to-queue dispatcher", {
369
+ options: ["entry", "no-migrate"],
370
+ }),
371
+ command("rules", "Start production rules runtime", { options: ["entry", "no-migrate"] }),
372
+ command(
373
+ "worker",
374
+ "Start production queue worker: sync, action, agent, pipeline, projection, workflow",
375
+ {
376
+ usage: "sixb worker <sync|action|agent|pipeline|projection|workflow> [options]",
377
+ options: ["entry", "no-migrate", "api-public-origin", "agent-turn-timeout", "concurrency"],
378
+ minimumPositionals: 1,
379
+ maximumPositionals: 1,
380
+ rootHelpLabel: "worker <type>",
381
+ }
382
+ ),
383
+ command("worker-group", "Co-host multiple queue workers in one process (constrained resources)", {
384
+ usage: "sixb worker-group [types...] [options]",
385
+ options: ["entry", "no-migrate", "api-public-origin", "agent-turn-timeout", "concurrency"],
386
+ repeatable: ["concurrency"],
387
+ maximumPositionals: Number.POSITIVE_INFINITY,
388
+ rootHelpLabel: "worker-group [types...]",
389
+ }),
390
+ command("check", "Validate project configuration and health", { options: ["entry"] }),
391
+ command("typegen", "Generate ontology types for client query inference", { options: ["entry"] }),
392
+ command("build", "Build runtime and production UI/app assets", { options: ["entry", "outdir"] }),
393
+ {
394
+ name: "db",
395
+ summary: "Manage runtime storage",
396
+ usage: "sixb db <migrate>",
397
+ children: [
398
+ command("db:migrate", "Run adapter-owned database migrations ahead of a role", {
399
+ path: ["db", "migrate"],
400
+ options: ["entry"],
401
+ rootHelpLabel: "db migrate",
402
+ }),
403
+ ],
404
+ },
405
+ {
406
+ name: "lake",
407
+ summary: "Inspect and maintain lake storage",
408
+ usage: "sixb lake <check|cleanup>",
409
+ children: [
410
+ command("lake:check", "Check lake dataset definitions for drift", {
411
+ path: ["lake", "check"],
412
+ options: ["entry"],
413
+ rootHelpLabel: "lake check",
414
+ }),
415
+ command("lake:cleanup", "Run lake storage maintenance cleanup", {
416
+ path: ["lake", "cleanup"],
417
+ options: ["entry", "dry-run", "expire-older-than", "delete-older-than"],
418
+ rootHelpLabel: "lake cleanup",
419
+ }),
420
+ ],
421
+ },
422
+ command("init", "Initialize sixb project in a directory", {
423
+ usage: "sixb init [dir]",
424
+ maximumPositionals: 1,
425
+ rootHelpLabel: "init [dir]",
426
+ }),
427
+ ]
428
+
429
+ export interface CliHelpItem {
430
+ readonly label: string
431
+ readonly value: string
432
+ }
433
+
434
+ export interface CliHelp {
435
+ readonly path: readonly string[]
436
+ readonly usage: string
437
+ readonly summary: string
438
+ readonly commands: readonly CliHelpItem[]
439
+ readonly options: readonly CliHelpItem[]
440
+ }
441
+
442
+ export interface ParsedCliOptions {
443
+ readonly [name: string]: string | boolean | readonly string[] | undefined
444
+ }
445
+
446
+ export type ParsedCli =
447
+ | { readonly kind: "help"; readonly help: CliHelp }
448
+ | { readonly kind: "version" }
449
+ | { readonly kind: "instance"; readonly args: readonly string[] }
450
+ | {
451
+ readonly kind: "command"
452
+ readonly id: LocalCommandId
453
+ readonly path: readonly string[]
454
+ readonly positionals: readonly string[]
455
+ readonly options: ParsedCliOptions
456
+ }
457
+
458
+ export class CliUsageError extends Error {
459
+ readonly help: CliHelp
460
+ readonly exitCode = 2
461
+
462
+ constructor(message: string, help: CliHelp) {
463
+ super(message)
464
+ this.name = "CliUsageError"
465
+ this.help = help
466
+ }
467
+ }
468
+
469
+ export const ROOT_HELP: CliHelp = {
470
+ path: [],
471
+ usage: "sixb <command> [options]",
472
+ summary: "Real-time digital twin framework",
473
+ commands: rootHelpItems(commandTree),
474
+ options: [
475
+ ...Object.values(CLI_OPTION_DEFINITIONS).map(({ syntax, summary }) => ({
476
+ label: syntax,
477
+ value: summary,
478
+ })),
479
+ { label: "--help", value: "Show contextual help" },
480
+ { label: "--version", value: "Show version" },
481
+ ],
482
+ }
483
+
484
+ export const CLI_EXAMPLES = [
485
+ "sixb dev",
486
+ "sixb build",
487
+ "sixb api",
488
+ "sixb login http://localhost:3002 --profile local",
489
+ "sixb ontology list",
490
+ "sixb objects inspect Customer customer-123",
491
+ "sixb token create --name 'Local CLI' --expires-in 90d",
492
+ "sixb service-account create --id svc_sandbox --name 'Sandbox agent' --group agents",
493
+ "sixb service-account token create svc_sandbox --name 'Sandbox token' --expires-in 30d",
494
+ "sixb status",
495
+ "sixb atlas",
496
+ "sixb app",
497
+ "sixb scheduler",
498
+ "sixb orchestrator",
499
+ "sixb rules",
500
+ "sixb worker pipeline",
501
+ "sixb worker agent --concurrency 8",
502
+ "sixb worker-group sync agent --concurrency sync=2 --concurrency agent=8",
503
+ "sixb dev --entry examples/mac-os/sixb.config.ts --port 8080",
504
+ "sixb check",
505
+ "sixb typegen",
506
+ "sixb db migrate",
507
+ "sixb lake check",
508
+ "sixb lake cleanup --dry-run",
509
+ ] as const
510
+
511
+ export function parseCliArgs(args: readonly string[]): ParsedCli {
512
+ const first = args[0]
513
+ if (!first) return { kind: "help", help: ROOT_HELP }
514
+ if (first === "--help" || first === "-h") {
515
+ if (args.length !== 1) throw new CliUsageError(`${first} accepts no arguments.`, ROOT_HELP)
516
+ return { kind: "help", help: ROOT_HELP }
517
+ }
518
+ if (first === "--version" || first === "-v") {
519
+ if (args.length !== 1) throw new CliUsageError("--version accepts no arguments.", ROOT_HELP)
520
+ return { kind: "version" }
521
+ }
522
+ if (first === "help") return parseHelpArgs(args.slice(1))
523
+ if (first.startsWith("-")) throw new CliUsageError(`Unknown option '${first}'.`, ROOT_HELP)
524
+
525
+ const root = commandTree.find((node) => node.name === first)
526
+ if (!root) throw new CliUsageError(`Unknown command '${first}'.`, ROOT_HELP)
527
+ if (root.instance) return { kind: "instance", args }
528
+ return parseLocalCommand(root, args)
529
+ }
530
+
531
+ export function stringOption(options: ParsedCliOptions, name: CliOptionName): string | undefined {
532
+ const value = options[name]
533
+ return typeof value === "string" ? value : undefined
534
+ }
535
+
536
+ export function booleanOption(options: ParsedCliOptions, name: CliOptionName): boolean {
537
+ return options[name] === true
538
+ }
539
+
540
+ export function repeatedOption(options: ParsedCliOptions, name: CliOptionName): readonly string[] {
541
+ const value = options[name]
542
+ return Array.isArray(value) ? value : typeof value === "string" ? [value] : []
543
+ }
544
+
545
+ export function wantsManagementJson(args: readonly string[]): boolean {
546
+ return (
547
+ ["login", "logout", "status", "profile", "token", "service-account"].includes(args[0] ?? "") &&
548
+ args.some((argument) => argument === "--json" || argument.startsWith("--json="))
549
+ )
550
+ }
551
+
552
+ function command(
553
+ id: LocalCommandId,
554
+ summary: string,
555
+ input: {
556
+ readonly path?: readonly string[]
557
+ readonly usage?: string
558
+ readonly options?: readonly CliOptionName[]
559
+ readonly repeatable?: readonly CliOptionName[]
560
+ readonly minimumPositionals?: number
561
+ readonly maximumPositionals?: number
562
+ readonly requiredInputs?: readonly {
563
+ readonly option: CliOptionName
564
+ readonly positional: number
565
+ }[]
566
+ readonly rootHelpLabel?: string
567
+ } = {}
568
+ ): CommandNode {
569
+ const path = input.path ?? [id]
570
+ return {
571
+ name: path.at(-1) ?? id,
572
+ id,
573
+ summary,
574
+ usage: input.usage ?? `sixb ${path.join(" ")}`,
575
+ options: input.options,
576
+ repeatable: input.repeatable,
577
+ minimumPositionals: input.minimumPositionals,
578
+ maximumPositionals: input.maximumPositionals ?? 0,
579
+ requiredInputs: input.requiredInputs,
580
+ rootHelpLabel: input.rootHelpLabel ?? (path.length === 1 ? path[0] : undefined),
581
+ }
582
+ }
583
+
584
+ function parseHelpArgs(path: readonly string[]): ParsedCli {
585
+ if (path.length === 0) return { kind: "help", help: ROOT_HELP }
586
+ const root = commandTree.find((node) => node.name === path[0])
587
+ if (!root) throw new CliUsageError(`Unknown command '${path[0]}'.`, ROOT_HELP)
588
+ if (root.instance) return { kind: "instance", args: [...path, "--help"] }
589
+
590
+ let node = root
591
+ for (const name of path.slice(1)) {
592
+ const child = node.children?.find((candidate) => candidate.name === name)
593
+ if (!child) throw new CliUsageError(`Unknown command '${path.join(" ")}'.`, helpFor(node, path))
594
+ node = child
595
+ }
596
+ return { kind: "help", help: helpFor(node, path) }
597
+ }
598
+
599
+ function parseLocalCommand(root: CommandNode, args: readonly string[]): ParsedCli {
600
+ let node = root
601
+ let index = 1
602
+ const path = [root.name]
603
+
604
+ while (node.children) {
605
+ const next = args[index]
606
+ if (!next || next === "--help" || next === "-h") {
607
+ return { kind: "help", help: helpFor(node, path) }
608
+ }
609
+ if (next.startsWith("-")) {
610
+ throw new CliUsageError(`'${path.join(" ")}' requires a subcommand.`, helpFor(node, path))
611
+ }
612
+ const child = node.children.find((candidate) => candidate.name === next)
613
+ if (!child) {
614
+ throw new CliUsageError(`Unknown ${path.join(" ")} command '${next}'.`, helpFor(node, path))
615
+ }
616
+ node = child
617
+ path.push(next)
618
+ index++
619
+ }
620
+
621
+ if (!node.id) throw new Error(`[SixbCLI] Command '${path.join(" ")}' has no handler.`)
622
+ const remaining = args.slice(index)
623
+ if (requestsHelp(remaining)) {
624
+ return { kind: "help", help: helpFor(node, path) }
625
+ }
626
+ const { options, positionals } = parseOptions(node, path, remaining)
627
+ return { kind: "command", id: node.id, path, positionals, options }
628
+ }
629
+
630
+ function requestsHelp(args: readonly string[]): boolean {
631
+ const separator = args.indexOf("--")
632
+ const options = separator < 0 ? args : args.slice(0, separator)
633
+ return options.includes("--help") || options.includes("-h")
634
+ }
635
+
636
+ function parseOptions(
637
+ node: CommandNode,
638
+ path: readonly string[],
639
+ args: readonly string[]
640
+ ): { readonly options: ParsedCliOptions; readonly positionals: readonly string[] } {
641
+ const options: Record<string, string | boolean | string[]> = {}
642
+ const positionals: string[] = []
643
+ const allowed = new Set(node.options ?? [])
644
+ const repeatable = new Set(node.repeatable ?? [])
645
+ let positionalOnly = false
646
+
647
+ for (let index = 0; index < args.length; index++) {
648
+ const argument = args[index]
649
+ if (argument === undefined) continue
650
+ if (argument === "--") {
651
+ positionalOnly = true
652
+ continue
653
+ }
654
+ if (positionalOnly || !argument.startsWith("-")) {
655
+ positionals.push(argument)
656
+ continue
657
+ }
658
+ if (!argument.startsWith("--")) {
659
+ throw new CliUsageError(`Unknown option '${argument}'.`, helpFor(node, path))
660
+ }
661
+
662
+ const equalsIndex = argument.indexOf("=")
663
+ const name = argument.slice(2, equalsIndex < 0 ? undefined : equalsIndex) as CliOptionName
664
+ const definition = CLI_OPTION_DEFINITIONS[name]
665
+ if (!definition || !allowed.has(name)) {
666
+ throw new CliUsageError(
667
+ `Unknown option '--${name}' for '${path.join(" ")}'.`,
668
+ helpFor(node, path)
669
+ )
670
+ }
671
+ if (options[name] !== undefined && !repeatable.has(name)) {
672
+ throw new CliUsageError(`--${name} may only be provided once.`, helpFor(node, path))
673
+ }
674
+
675
+ if (definition.kind === "boolean") {
676
+ if (equalsIndex >= 0) {
677
+ throw new CliUsageError(`--${name} does not accept a value.`, helpFor(node, path))
678
+ }
679
+ options[name] = true
680
+ continue
681
+ }
682
+
683
+ const value = equalsIndex < 0 ? args[++index] : argument.slice(equalsIndex + 1)
684
+ if (!value || value.startsWith("--")) {
685
+ throw new CliUsageError(`--${name} requires a value.`, helpFor(node, path))
686
+ }
687
+ if (repeatable.has(name)) {
688
+ const values = options[name]
689
+ options[name] = Array.isArray(values) ? [...values, value] : [value]
690
+ } else {
691
+ options[name] = value
692
+ }
693
+ }
694
+
695
+ const minimum = node.minimumPositionals ?? 0
696
+ const maximum = node.maximumPositionals ?? 0
697
+ if (positionals.length < minimum || positionals.length > maximum) {
698
+ throw new CliUsageError(`Invalid arguments for '${path.join(" ")}'.`, helpFor(node, path))
699
+ }
700
+ for (const required of node.requiredInputs ?? []) {
701
+ if (!positionals[required.positional] && typeof options[required.option] !== "string") {
702
+ throw new CliUsageError(
703
+ `Missing required ${CLI_OPTION_DEFINITIONS[required.option].syntax}.`,
704
+ helpFor(node, path)
705
+ )
706
+ }
707
+ }
708
+ if (typeof options["api-url"] === "string" && typeof options.profile === "string") {
709
+ throw new CliUsageError("--api-url and --profile cannot be used together.", helpFor(node, path))
710
+ }
711
+ return { options, positionals }
712
+ }
713
+
714
+ function helpFor(node: CommandNode, path: readonly string[]): CliHelp {
715
+ const prefix = `sixb ${path.join(" ")}`
716
+ return {
717
+ path: [...path],
718
+ usage: node.usage,
719
+ summary: node.summary,
720
+ commands: (node.children ?? []).map((child) => ({
721
+ label: child.usage.startsWith(`${prefix} `)
722
+ ? child.usage.slice(prefix.length + 1)
723
+ : child.name,
724
+ value: child.summary,
725
+ })),
726
+ options: [
727
+ ...(node.options ?? []).map((name) => ({
728
+ label: CLI_OPTION_DEFINITIONS[name].syntax,
729
+ value: CLI_OPTION_DEFINITIONS[name].summary,
730
+ })),
731
+ { label: "--help", value: "Show this help" },
732
+ ],
733
+ }
734
+ }
735
+
736
+ function rootHelpItems(nodes: readonly CommandNode[]): CliHelpItem[] {
737
+ const items: CliHelpItem[] = []
738
+ for (const node of nodes) {
739
+ if (node.rootHelpLabel) items.push({ label: node.rootHelpLabel, value: node.summary })
740
+ if (!node.rootHelpLabel && node.children) items.push(...rootHelpItems(node.children))
741
+ }
742
+ return items
743
+ }