@politty/loculus 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +65 -2
  3. package/bin/cli.mjs +3 -0
  4. package/dist/agent.d.ts +2 -0
  5. package/dist/agent.js +1 -0
  6. package/dist/argv-parser-BRSUT6IV.js +1 -0
  7. package/dist/cli-main-CoQp6CjD.js +1 -0
  8. package/dist/cli-main-D4rJTFFd.js +2 -0
  9. package/dist/cli-run-DABESHM4.js +1 -0
  10. package/dist/cli.d.ts +1 -0
  11. package/dist/cli.js +2 -0
  12. package/dist/command-BXsTrIgI.js +1 -0
  13. package/dist/compile-cache-6u9hgeWu.js +1 -0
  14. package/dist/compile-cache.d.ts +80 -0
  15. package/dist/compile-cache.js +1 -0
  16. package/dist/completion-BGidlN43.js +1 -0
  17. package/dist/completion-Cyw4RN-l.js +116 -0
  18. package/dist/completion.d.ts +333 -0
  19. package/dist/completion.js +1 -0
  20. package/dist/detect-agent-D7KSeWMh.js +3 -0
  21. package/dist/detect-agent-EHaSY1KW.d.ts +49 -0
  22. package/dist/docs.d.ts +770 -0
  23. package/dist/docs.js +94 -0
  24. package/dist/dynamic-BbeRdUqR.js +1 -0
  25. package/dist/dynamic-Hg5BDHzz.js +6 -0
  26. package/dist/import-meta-resolve-DgKm4LYW.js +3 -0
  27. package/dist/index.d.ts +1088 -0
  28. package/dist/index.js +1 -0
  29. package/dist/log-collector-uhRWYT-z.js +1 -0
  30. package/dist/logger-CoeDrmRr.js +1 -0
  31. package/dist/prompt-clack.d.ts +15 -0
  32. package/dist/prompt-clack.js +1 -0
  33. package/dist/prompt-fl79dWPz.js +1 -0
  34. package/dist/prompt-inquirer.d.ts +15 -0
  35. package/dist/prompt-inquirer.js +1 -0
  36. package/dist/prompt.d.ts +106 -0
  37. package/dist/prompt.js +1 -0
  38. package/dist/register-Ceh-HlVN.js +1 -0
  39. package/dist/registry-BEz5iex_.js +1 -0
  40. package/dist/runner-D-n1xa2K.js +33 -0
  41. package/dist/runner-nPWQnqQ3.js +1 -0
  42. package/dist/schema--6eHVfwR.js +1 -0
  43. package/dist/schema-extractor-DFawzmtj.js +1 -0
  44. package/dist/skill.d.ts +581 -0
  45. package/dist/skill.js +2 -0
  46. package/dist/subcommand-router-iqmWGZyU.js +2 -0
  47. package/dist/types-Dhar1ua6.d.ts +1125 -0
  48. package/dist/with-completion-command-CARvhYvv.d.ts +384 -0
  49. package/dist/with-completion-command-yg7HB6Zu.js +3 -0
  50. package/package.json +101 -3
@@ -0,0 +1,1125 @@
1
+ import { t as AgentInfo } from "./detect-agent-EHaSY1KW.js";
2
+ //#region ../core/src/adapter/standard-schema.d.ts
3
+ /**
4
+ * Type-level subset of the Standard Schema V1 interface
5
+ * (https://standardschema.dev), vendored so `@politty/core` can constrain
6
+ * and infer user schemas without importing any schema library.
7
+ *
8
+ * Both zod v4 and valibot v1 type their schemas against the official
9
+ * `@standard-schema/spec` interface, so any schema from either library is
10
+ * structurally assignable to {@link SchemaLike}. Only the properties core
11
+ * needs for constraints and output inference are declared here — extra
12
+ * properties on the real `~standard` object don't affect assignability.
13
+ *
14
+ * This is a TYPE-ONLY neutrality layer: core never calls
15
+ * `~standard.validate` (rich validation goes through the registered
16
+ * `ValidatorAdapter` so error output keeps library-specific detail).
17
+ */
18
+ /** The `~standard` properties politty relies on. */
19
+ interface StandardSchemaProps<Output = unknown> {
20
+ /** Version of the Standard Schema spec the library implements */
21
+ readonly version: 1;
22
+ /** Name of the implementing library (e.g. "zod", "valibot") */
23
+ readonly vendor: string;
24
+ /** Standard validation entry point (unused by politty; see module doc) */
25
+ readonly validate: (value: unknown) => unknown;
26
+ /** Type-inference carrier (never exists at runtime) */
27
+ readonly types?: {
28
+ readonly output: Output;
29
+ } | undefined;
30
+ }
31
+ /**
32
+ * A schema from any Standard Schema implementing library, constrained by
33
+ * its output type.
34
+ *
35
+ * A primitive cannot satisfy this (it has no `~standard` property), which is
36
+ * what matters in practice: schemas are used as `WeakMap` keys by the
37
+ * `arg()` metadata registry. Intersecting with `object` would not add
38
+ * safety — TypeScript still accepts a hand-written `string & SchemaLike<…>`
39
+ * against an object-constrained type, and such a value throws
40
+ * `Invalid value used as weak map key` the moment `arg()` registers it.
41
+ */
42
+ interface SchemaLike<Output = unknown> {
43
+ readonly "~standard": StandardSchemaProps<Output>;
44
+ }
45
+ /** Infer the output type of a {@link SchemaLike}. */
46
+ type InferSchemaOutput<S> = S extends SchemaLike ? NonNullable<S["~standard"]["types"]>["output"] : never;
47
+ //#endregion
48
+ //#region ../core/src/package-requirements.d.ts
49
+ interface PackageRequirement<TArgs = unknown> {
50
+ name: string;
51
+ install?: string | undefined;
52
+ from?: string | URL | undefined;
53
+ description?: string | undefined;
54
+ when?: ((args: TArgs) => boolean) | undefined;
55
+ }
56
+ declare function loadPackage<TModule = unknown>(requirement: Pick<PackageRequirement, "name" | "install" | "from">): Promise<TModule>;
57
+ //#endregion
58
+ //#region ../core/src/core/dynamic-completion-types.d.ts
59
+ /**
60
+ * Types for in-process dynamic value completion.
61
+ *
62
+ * A `resolve` callback registered on `arg(...)` receives parsed context
63
+ * (other arg values typed so far, previous values supplied to the same
64
+ * option, the current word being completed, target shell) and returns
65
+ * candidates. The callback runs inside the `__complete` command. Dispatcher
66
+ * shell scripts call `__complete` for every completion request; static shell
67
+ * scripts delegate to it for any spec that uses `resolve`.
68
+ *
69
+ * Defined under `core/` (not `completion/`) so `arg-registry.ts` can
70
+ * reference the resolver type without crossing the lint-enforced
71
+ * `completion → core` boundary.
72
+ */
73
+ /** Bitmask combining `CompletionDirective` values. */
74
+ type CompletionDirectiveMask = number;
75
+ interface DynamicCompletionContext {
76
+ /** Word being completed. `--field=` inline prefix is stripped before this is set. */
77
+ currentWord: string;
78
+ /** Target shell formatting requested by the caller. */
79
+ shell: "bash" | "zsh" | "fish";
80
+ /**
81
+ * Best-effort parsed values of OTHER args on the same command, keyed by
82
+ * camelCase name. Includes positionals and other options. Zod validation
83
+ * is NOT applied; values are raw strings (or arrays of raw strings for
84
+ * array-typed options/variadic positionals).
85
+ */
86
+ parsedArgs: Readonly<Record<string, unknown>>;
87
+ /**
88
+ * Values already supplied for the SAME option/positional being completed.
89
+ * Useful for de-duplicating repeated array options.
90
+ */
91
+ previousValues: readonly string[];
92
+ /**
93
+ * Subcommand path from root (e.g. ["api"]). Reflects what the user
94
+ * actually typed — aliases are NOT resolved to their canonical names, so
95
+ * resolvers that branch on the path should accept every alias they care
96
+ * about.
97
+ */
98
+ subcommandPath: readonly string[];
99
+ }
100
+ interface DynamicCompletionCandidate {
101
+ value: string;
102
+ description?: string;
103
+ }
104
+ interface DynamicCompletionResult {
105
+ /** Candidates to surface. Strings or `{value, description}` objects. */
106
+ candidates: Array<string | DynamicCompletionCandidate>;
107
+ /**
108
+ * Optional directive override. When omitted, defaults to
109
+ * `FilterPrefix | NoFileCompletion` (matches `choices` behaviour).
110
+ */
111
+ directive?: CompletionDirectiveMask;
112
+ }
113
+ type DynamicCompletionResolver = (ctx: DynamicCompletionContext) => DynamicCompletionResult | Promise<DynamicCompletionResult>;
114
+ //#endregion
115
+ //#region ../core/src/core/expand-completion-types.d.ts
116
+ /**
117
+ * Types for "expand" completion — candidates that depend on sibling arg
118
+ * values.
119
+ *
120
+ * The user provides `dependsOn` (sibling arg names that must have static
121
+ * `choices` or an enum schema) and `enumerate(deps)`. Dispatcher scripts call
122
+ * `enumerate` inside `__complete` for the dependency values already typed on
123
+ * the command line. Static scripts walk the cartesian product of the
124
+ * dependsOn values, call `enumerate` for each combination, and emit a shell
125
+ * lookup table.
126
+ *
127
+ * Defined under `core/` (not `completion/`) so `arg-registry.ts` can
128
+ * reference these types without crossing the lint-enforced
129
+ * `completion → core` boundary.
130
+ */
131
+ /** Candidate returned by an `enumerate` callback. */
132
+ interface ExpandCandidate {
133
+ value: string;
134
+ description?: string;
135
+ }
136
+ /** Resolved candidate stored on a {@link ValueCompletion} after enumeration. */
137
+ interface ResolvedExpandCandidate {
138
+ value: string;
139
+ description?: string;
140
+ }
141
+ /**
142
+ * User-facing spec attached to `completion.custom.expand`.
143
+ *
144
+ * `dependsOn` lists sibling args (camelCase names) whose values determine
145
+ * which candidates apply. Each named arg must have a static set of values —
146
+ * either an explicit `completion.custom.choices` or an enum schema. The
147
+ * order of `dependsOn` is the order in which `deps` keys are exposed to
148
+ * `enumerate`.
149
+ *
150
+ * In dispatcher mode, `enumerate` runs during `__complete` for the dependency
151
+ * values already typed by the user. In static mode, it runs once per
152
+ * cartesian-product combination at script-generation time (e.g. when the user
153
+ * runs `<program> completion zsh --static`). It must be a pure function of
154
+ * `deps`.
155
+ */
156
+ interface ExpandCompletion {
157
+ dependsOn: readonly string[];
158
+ enumerate: (deps: Readonly<Record<string, string>>) => ReadonlyArray<string | ExpandCandidate>;
159
+ }
160
+ //#endregion
161
+ //#region ../core/src/core/arg-registry.d.ts
162
+ /**
163
+ * Built-in completion types
164
+ */
165
+ type CompletionType = "file" | "directory" | "none";
166
+ /**
167
+ * Custom completion specification.
168
+ *
169
+ * `choices`, `shellCommand`, `resolve`, and `expand` are mutually exclusive —
170
+ * specifying more than one throws when the field metadata is resolved.
171
+ */
172
+ interface CustomCompletion {
173
+ /** Static list of choices for completion */
174
+ choices?: string[];
175
+ /** Shell command to execute for dynamic completion */
176
+ shellCommand?: string;
177
+ /**
178
+ * In-process JS callback for dynamic completion. Receives parsed context
179
+ * (other arg values typed so far, previously supplied values for this same
180
+ * option) and returns candidates. Dispatcher scripts call
181
+ * `<program> __complete` for every completion request; static scripts
182
+ * delegate to it whenever this is set.
183
+ */
184
+ resolve?: DynamicCompletionResolver;
185
+ /**
186
+ * Completion whose candidates depend on sibling arg values. Dispatcher
187
+ * scripts call `enumerate` inside `__complete` for the dependency values
188
+ * already typed on the command line. Static scripts pre-enumerate every
189
+ * combination of `dependsOn` values at script-generation time and dispatch
190
+ * via a shell lookup table.
191
+ */
192
+ expand?: ExpandCompletion;
193
+ }
194
+ /**
195
+ * Completion metadata for an argument
196
+ *
197
+ * @example
198
+ * ```ts
199
+ * // File completion with extension filter
200
+ * input: arg(z.string(), {
201
+ * completion: { type: "file", extensions: ["json", "yaml"] }
202
+ * })
203
+ *
204
+ * // Directory completion
205
+ * outputDir: arg(z.string(), {
206
+ * completion: { type: "directory" }
207
+ * })
208
+ *
209
+ * // Custom static choices
210
+ * logLevel: arg(z.string(), {
211
+ * completion: { custom: { choices: ["debug", "info", "warn", "error"] } }
212
+ * })
213
+ *
214
+ * // Dynamic completion from shell command
215
+ * branch: arg(z.string(), {
216
+ * completion: { custom: { shellCommand: "git branch --format='%(refname:short)'" } }
217
+ * })
218
+ *
219
+ * // File completion with glob pattern matcher
220
+ * envFile: arg(z.string(), {
221
+ * completion: { type: "file", matcher: [".env.*"] }
222
+ * })
223
+ * ```
224
+ */
225
+ type CompletionMeta = {
226
+ /** Built-in completion type */
227
+ type?: CompletionType;
228
+ /** Custom completion (takes precedence over type if both specified) */
229
+ custom?: CustomCompletion;
230
+ } & ({
231
+ /** File extension filter (only applies when type is "file") */ extensions?: string[];
232
+ matcher?: never;
233
+ } | {
234
+ /** Glob patterns for file matching (only applies when type is "file") */ matcher?: string[];
235
+ extensions?: never;
236
+ });
237
+ /**
238
+ * Prompt input type for interactive prompts
239
+ *
240
+ * - "text": free-form text input (default for string schemas)
241
+ * - "password": masked text input
242
+ * - "confirm": yes/no prompt (default for boolean schemas)
243
+ * - "select": single selection from choices (default for enum schemas)
244
+ * - "file": file path input (inherited from completion type)
245
+ * - "directory": directory path input (inherited from completion type)
246
+ */
247
+ type PromptType = "text" | "password" | "confirm" | "select" | "file" | "directory";
248
+ /**
249
+ * Prompt metadata for interactive input when a value is missing.
250
+ * Used by the `politty/prompt` module to request user input for unresolved arguments.
251
+ *
252
+ * @example
253
+ * ```ts
254
+ * // Custom prompt message
255
+ * name: arg(z.string(), {
256
+ * prompt: { message: "What is your name?" }
257
+ * })
258
+ *
259
+ * // Password input (masked)
260
+ * token: arg(z.string(), {
261
+ * prompt: { type: "password", message: "Enter API token" }
262
+ * })
263
+ *
264
+ * // Select with custom choices
265
+ * region: arg(z.string(), {
266
+ * prompt: { choices: ["us-east-1", "eu-west-1", "ap-northeast-1"] }
267
+ * })
268
+ * ```
269
+ */
270
+ interface PromptMeta {
271
+ /** Prompt message shown to the user. Defaults to the field's description or name. */
272
+ message?: string;
273
+ /** Explicit prompt type. Overrides auto-detection from schema/completion. */
274
+ type?: PromptType;
275
+ /** Choices for select prompt. Overrides enum values from schema. */
276
+ choices?: Array<string | {
277
+ label: string;
278
+ value: string;
279
+ }>;
280
+ /** Whether to enable prompting for this field (default: true when prompt is set) */
281
+ enabled?: boolean;
282
+ }
283
+ /**
284
+ * Context provided to effect callbacks.
285
+ * When GlobalArgs is extended via declaration merging, `globalArgs` is typed accordingly.
286
+ */
287
+ type EffectContext = {
288
+ /** Field name (camelCase) */
289
+ name: string;
290
+ /**
291
+ * Validated args for this schema (global args for global effects, command
292
+ * args for command effects), carrying the same `$source` helper the run
293
+ * function receives.
294
+ */
295
+ args: Readonly<Record<string, unknown>> & {
296
+ $source?: (name: string) => ArgSource;
297
+ };
298
+ } & (IsEmpty<GlobalArgs> extends true ? {
299
+ globalArgs?: Readonly<Record<string, unknown>>;
300
+ } : {
301
+ globalArgs?: Readonly<GlobalArgs>;
302
+ });
303
+ /**
304
+ * Base metadata shared by all argument types
305
+ */
306
+ interface BaseArgMeta<TValue = unknown> {
307
+ requiredPackages?: readonly Pick<PackageRequirement, "name" | "install" | "from">[];
308
+ /** Argument description */
309
+ description?: string;
310
+ /**
311
+ * Treat as positional argument. Pass `{ named: true }` to also accept it as
312
+ * a long option (`--name <value>`), e.g. for values that may start with `-`.
313
+ */
314
+ positional?: boolean | {
315
+ named?: boolean;
316
+ };
317
+ /** Placeholder for help display */
318
+ placeholder?: string;
319
+ /**
320
+ * Environment variable name(s) to read value from.
321
+ * If an array is provided, earlier entries take priority.
322
+ * CLI arguments always take precedence over environment variables.
323
+ *
324
+ * @example
325
+ * ```ts
326
+ * // Single env var
327
+ * port: arg(z.coerce.number(), { env: "PORT" })
328
+ *
329
+ * // Multiple env vars (PORT takes priority over SERVER_PORT)
330
+ * port: arg(z.coerce.number(), { env: ["PORT", "SERVER_PORT"] })
331
+ * ```
332
+ */
333
+ env?: string | string[];
334
+ /** Completion configuration for shell tab-completion */
335
+ completion?: CompletionMeta;
336
+ /**
337
+ * Interactive prompt configuration for missing values.
338
+ * When set, the `politty/prompt` module will prompt the user interactively
339
+ * if this argument is not provided via CLI args or environment variables.
340
+ *
341
+ * @example
342
+ * ```ts
343
+ * name: arg(z.string(), {
344
+ * description: "User name",
345
+ * prompt: { message: "What is your name?" },
346
+ * })
347
+ * ```
348
+ */
349
+ prompt?: PromptMeta;
350
+ /**
351
+ * Control the boolean negation option.
352
+ *
353
+ * Boolean fields accept `--no-<cliName>` (and the camelCase `--no<Name>`
354
+ * form) to set the value to `false` only when `negation: true` is set.
355
+ * By default no negation form is accepted. This option lets you customize
356
+ * or expose that behavior:
357
+ *
358
+ * - `string` — replaces the auto-generated `--no-*` form with a custom
359
+ * name. The default `--no-*` is no longer recognized.
360
+ * - `true` — enables the default `--no-<cliName>` form and advertises it
361
+ * in help, generated docs, and shell completions.
362
+ * - `false` — disables negation entirely; same as the default, but explicit.
363
+ * Neither the default `--no-*` nor any custom name is accepted.
364
+ *
365
+ * String values follow the same naming conventions as `cliName`
366
+ * (kebab-case is recommended). Only valid on boolean fields; setting
367
+ * `negation` on a non-boolean field is a type error and raises a
368
+ * runtime error during command parsing.
369
+ *
370
+ * @example
371
+ * ```ts
372
+ * // Custom negation name
373
+ * cache: arg(z.boolean().default(true), {
374
+ * description: "Enable caching",
375
+ * negation: "disable-cache",
376
+ * })
377
+ * // Accepts: --cache (true), --disable-cache (false)
378
+ * // No longer accepts: --no-cache
379
+ *
380
+ * // Enable default `--no-X` in parsing/help/docs/completion
381
+ * verbose: arg(z.boolean().default(false), {
382
+ * negation: true,
383
+ * })
384
+ * // Help shows `--verbose / --no-verbose`
385
+ *
386
+ * // Disable negation entirely
387
+ * dryRun: arg(z.boolean().default(false), {
388
+ * negation: false,
389
+ * })
390
+ * // Accepts: --dry-run (true)
391
+ * // No longer accepts: --no-dry-run
392
+ * ```
393
+ */
394
+ negation?: string | boolean;
395
+ /**
396
+ * Description shown for the negation option in help and generated docs.
397
+ * Only meaningful when `negation` is set to a custom name string or `true`.
398
+ * Disallowed when `negation` is `false`.
399
+ */
400
+ negationDescription?: string;
401
+ /**
402
+ * Side-effect callback executed after argument parsing and validation.
403
+ * Runs before the command lifecycle (setup/run/cleanup).
404
+ * Use Zod .transform() for value transformation instead.
405
+ *
406
+ * @example
407
+ * ```ts
408
+ * verbose: arg(z.boolean().default(false), {
409
+ * alias: "v",
410
+ * effect: (value) => {
411
+ * if (value) logger.setLevel("debug");
412
+ * },
413
+ * })
414
+ * ```
415
+ */
416
+ effect?: (value: TValue, context: EffectContext) => void | PromiseLike<void>;
417
+ }
418
+ /**
419
+ * Metadata for regular arguments (non-builtin aliases)
420
+ *
421
+ * `alias` accepts either a single string or an array of strings.
422
+ * Single-character entries become short options (e.g. `-v`); multi-character
423
+ * entries become additional long options (e.g. `--to-be` for `--tobe`).
424
+ */
425
+ interface RegularArgMeta<TValue = unknown> extends BaseArgMeta<TValue> {
426
+ /**
427
+ * Alias name(s) for this option.
428
+ * - 1-char string → short alias (`-v`)
429
+ * - >1-char string → long alias (`--long-name`)
430
+ * - array → multiple aliases of either kind
431
+ */
432
+ alias?: string | string[] | readonly string[];
433
+ /**
434
+ * Alias name(s) that are accepted by the parser but hidden from help,
435
+ * generated docs, and shell completion. Useful for legacy or deprecated
436
+ * names that should still work without being advertised.
437
+ */
438
+ hiddenAlias?: string | string[] | readonly string[];
439
+ }
440
+ /**
441
+ * Metadata for overriding built-in aliases (-h, -H)
442
+ */
443
+ interface BuiltinOverrideArgMeta<TValue = unknown> extends BaseArgMeta<TValue> {
444
+ /** Built-in alias to override ('h' or 'H'), optionally combined with extra aliases */
445
+ alias: "h" | "H" | Array<"h" | "H" | string> | ReadonlyArray<"h" | "H" | string>;
446
+ /** Hidden aliases (accepted but not surfaced in help/docs/completion) */
447
+ hiddenAlias?: string | string[] | readonly string[];
448
+ /** Must be true to override built-in aliases */
449
+ overrideBuiltinAlias: true;
450
+ }
451
+ /**
452
+ * Metadata options for argument definition
453
+ */
454
+ type ArgMeta<TValue = unknown> = RegularArgMeta<TValue> | BuiltinOverrideArgMeta<TValue>;
455
+ /**
456
+ * Register metadata for a schema
457
+ *
458
+ * @param schema - The schema to attach metadata to
459
+ * @param meta - Argument metadata
460
+ * @returns The same schema (for chaining)
461
+ *
462
+ * @example
463
+ * ```ts
464
+ * import { z } from "zod";
465
+ * import { arg, defineCommand } from "politty";
466
+ *
467
+ * const cmd = defineCommand({
468
+ * args: z.object({
469
+ * name: arg(z.string(), { description: "User name", positional: true }),
470
+ * verbose: arg(z.boolean().default(false), { alias: "v" }),
471
+ * }),
472
+ * run: (args) => {
473
+ * console.log(args.name, args.verbose);
474
+ * },
475
+ * });
476
+ * ```
477
+ */
478
+ /**
479
+ * Detect whether `A` contains a reserved alias ("h" or "H"), for either a
480
+ * plain string or a tuple/array of strings. Uses `[A] extends [never]` to
481
+ * prevent distribution returning `never` for missing fields.
482
+ */
483
+ type ContainsReservedAlias<A> = [A] extends [never] ? false : A extends "h" | "H" ? true : A extends readonly (infer E)[] ? [Extract<E, "h" | "H">] extends [never] ? false : true : false;
484
+ type ReservedAliasTypeError<M> = { [K in keyof M]: M[K]; } & {
485
+ __typeError: "Alias 'h' or 'H' requires overrideBuiltinAlias: true";
486
+ };
487
+ type NegationTypeError<M> = { [K in keyof M]: M[K]; } & {
488
+ __typeError: "negation/negationDescription can only be used on boolean fields";
489
+ };
490
+ type AliasFieldOf<M> = M extends {
491
+ alias: infer A;
492
+ } ? A : never;
493
+ type HiddenAliasFieldOf<M> = M extends {
494
+ hiddenAlias: infer H;
495
+ } ? H : never;
496
+ /**
497
+ * Check whether a Zod output type is a (possibly optional) boolean.
498
+ * Strips `undefined` to allow `z.boolean().optional()`. Requires both
499
+ * `boolean extends NonNullable<T>` (so `z.literal(true)` is rejected — the full
500
+ * `boolean` domain is needed) and `NonNullable<T> extends boolean` (so unions
501
+ * such as `z.union([z.boolean(), z.string()])` are rejected at the type level
502
+ * to match the runtime check).
503
+ */
504
+ type IsBooleanField<T> = boolean extends NonNullable<T> ? ([NonNullable<T>] extends [boolean] ? true : false) : false;
505
+ /**
506
+ * Detect whether `M` has `K` set to a non-undefined value.
507
+ *
508
+ * When `M` is inferred from a literal such as `{ negation: "off" }`,
509
+ * `M["negation"]` is `"off"` (without `undefined`), so this returns `true`.
510
+ * When `M` is the wider `ArgMeta` type, `M["negation"]` is
511
+ * `string | boolean | undefined`, so this returns `false` and avoids
512
+ * false-positive type errors on broadly-typed meta values.
513
+ */
514
+ type HasExplicit<M, K extends string> = K extends keyof M ? undefined extends M[K] ? false : true : false;
515
+ /**
516
+ * Reject `negation` / `negationDescription` on non-boolean fields.
517
+ * Uses {@link HasExplicit} so the error only fires when the user explicitly
518
+ * sets the field on a narrowly-inferred meta literal.
519
+ */
520
+ type ValidateNegation<M, TValue> = HasExplicit<M, "negation"> extends true ? IsBooleanField<TValue> extends true ? M : NegationTypeError<M> : HasExplicit<M, "negationDescription"> extends true ? IsBooleanField<TValue> extends true ? M : NegationTypeError<M> : M;
521
+ /**
522
+ * Type helper to validate ArgMeta.
523
+ * Forces a type error when a reserved alias ("h" / "H") is used without
524
+ * `overrideBuiltinAlias: true`, whether the alias is provided as a string
525
+ * or as part of an array, and whether it appears in `alias` or `hiddenAlias`.
526
+ * Also rejects `negation` / `negationDescription` on non-boolean fields.
527
+ */
528
+ type ValidateArgMeta<M, TValue = unknown> = M extends {
529
+ overrideBuiltinAlias: true;
530
+ } ? ValidateNegation<M, TValue> : ContainsReservedAlias<AliasFieldOf<M>> extends true ? ReservedAliasTypeError<M> : ContainsReservedAlias<HiddenAliasFieldOf<M>> extends true ? ReservedAliasTypeError<M> : ValidateNegation<M, TValue>;
531
+ /**
532
+ * The overloaded `arg()` signature, parameterized by the schema constraint.
533
+ * Core's `arg` accepts any Standard Schema; adapter packages re-pin the same
534
+ * runtime function to their library's schema type (e.g. `ArgFn<z.ZodType>`
535
+ * in `@politty/zod`) so a schema from the wrong library is rejected at the
536
+ * type level.
537
+ */
538
+ interface ArgFn<TSchemaBase extends SchemaLike = SchemaLike> {
539
+ <T extends TSchemaBase>(schema: T): T;
540
+ <T extends TSchemaBase, M extends ArgMeta<InferSchemaOutput<T>>>(schema: T, meta: ValidateArgMeta<M, InferSchemaOutput<T>>): T;
541
+ }
542
+ //#endregion
543
+ //#region ../core/src/adapter/field-meta.d.ts
544
+ /**
545
+ * Resolved metadata for an argument field
546
+ */
547
+ interface ResolvedFieldMeta {
548
+ requiredPackages?: readonly Pick<PackageRequirement, "name" | "install" | "from">[] | undefined;
549
+ /** Field name (camelCase, as defined in schema) */
550
+ name: string;
551
+ /** CLI option name (kebab-case, for command line usage) */
552
+ cliName: string;
553
+ /**
554
+ * Aliases for this option, normalized to an array.
555
+ * 1-char entries are short aliases (`-v`); multi-char entries are long
556
+ * aliases (`--to-be`).
557
+ */
558
+ alias?: string[] | undefined;
559
+ /**
560
+ * Aliases that are accepted at parse time but hidden from help,
561
+ * generated docs, and shell completion.
562
+ */
563
+ hiddenAlias?: string[] | undefined;
564
+ /** Argument description */
565
+ description?: string | undefined;
566
+ /** Whether this is a positional argument */
567
+ positional: boolean;
568
+ /** Whether this is accepted as a long option (`--cli-name`) */
569
+ named: boolean;
570
+ /** Placeholder for help display */
571
+ placeholder?: string | undefined;
572
+ /**
573
+ * Environment variable name(s) to read value from.
574
+ * If an array, earlier entries take priority.
575
+ */
576
+ env?: string | string[] | undefined;
577
+ /** Whether this argument is required */
578
+ required: boolean;
579
+ /** Default value if any */
580
+ defaultValue?: unknown;
581
+ /** Detected type from schema */
582
+ type: "string" | "number" | "boolean" | "array" | "unknown";
583
+ /**
584
+ * Original field schema, carried through opaquely for downstream
585
+ * consumers. Its concrete type belongs to the adapter's schema library
586
+ * (zod, valibot, or an internal descriptor); core never calls into it.
587
+ */
588
+ schema: unknown;
589
+ /** True if this overrides built-in aliases (-h, -H) */
590
+ overrideBuiltinAlias?: true;
591
+ /** Enum values if detected from schema (z.enum) */
592
+ enumValues?: string[] | undefined;
593
+ /** Completion metadata from arg() */
594
+ completion?: CompletionMeta | undefined;
595
+ /** Prompt metadata from arg() for interactive input */
596
+ prompt?: PromptMeta | undefined;
597
+ /**
598
+ * Negation configuration for this boolean field.
599
+ *
600
+ * - String (e.g. `"disable-cache"`): the default `--no-<cliName>` form is
601
+ * suppressed and only `--<negation>` (plus its camelCase variant) is
602
+ * accepted as the negation flag.
603
+ * - `true`: the default `--no-<cliName>` form is accepted **and** shown in
604
+ * help, generated docs, and shell completions.
605
+ * - `false`: neither the default `--no-<cliName>` nor any custom name is
606
+ * accepted; the field only responds to the positive flag.
607
+ * - `undefined`: no negation form is accepted or shown.
608
+ *
609
+ * Only applies to boolean fields; populated as `undefined` otherwise.
610
+ */
611
+ negation?: string | boolean | undefined;
612
+ /**
613
+ * Derived display name (no `--` prefix) for the negation flag in help,
614
+ * generated docs, and shell completions. `undefined` means the negation
615
+ * is hidden from those surfaces. Computed from `negation` + `cliName`.
616
+ */
617
+ negationDisplay?: string | undefined;
618
+ /** Description shown for the negation option in help/docs. */
619
+ negationDescription?: string | undefined;
620
+ /** Side-effect callback from arg() metadata */
621
+ effect?: ((value: unknown, context: EffectContext) => void | PromiseLike<void>) | undefined;
622
+ }
623
+ /**
624
+ * Extracted fields from a schema
625
+ */
626
+ interface ExtractedFields {
627
+ /** All field definitions */
628
+ fields: ResolvedFieldMeta[];
629
+ /** Original schema for validation */
630
+ schema: ArgsSchema;
631
+ /** Schema type */
632
+ schemaType: "object" | "discriminatedUnion" | "union" | "xor" | "intersection";
633
+ /** Discriminator key (for discriminatedUnion) */
634
+ discriminator?: string;
635
+ /** Variants (for discriminatedUnion) */
636
+ variants?: Array<{
637
+ discriminatorValue: string;
638
+ normalizeDiscriminator?: (value: unknown) => unknown;
639
+ fields: ResolvedFieldMeta[];
640
+ description?: string;
641
+ }>;
642
+ /** Options (for union) */
643
+ unionOptions?: ExtractedFields[];
644
+ /** Schema description */
645
+ description?: string;
646
+ /**
647
+ * Unknown keys handling mode
648
+ * - "strict": Unknown keys cause validation errors (z.strictObject or z.object().strict())
649
+ * - "strip": Unknown keys trigger warnings (default, z.object())
650
+ * - "passthrough": Unknown keys are silently ignored (z.looseObject or z.object().passthrough())
651
+ */
652
+ unknownKeysMode: UnknownKeysMode;
653
+ }
654
+ /**
655
+ * Unknown keys handling mode for object schemas
656
+ * - "strict": Unknown keys cause validation errors
657
+ * - "strip": Unknown keys are silently ignored (default)
658
+ * - "passthrough": Unknown keys are passed through
659
+ */
660
+ type UnknownKeysMode = "strict" | "strip" | "passthrough";
661
+ /**
662
+ * Convert camelCase to kebab-case
663
+ * @example toKebabCase("dryRun") => "dry-run"
664
+ * @example toKebabCase("outputDir") => "output-dir"
665
+ * @example toKebabCase("XMLParser") => "xml-parser"
666
+ */
667
+ declare function toKebabCase(str: string): string;
668
+ /**
669
+ * Convert hyphen-separated sequences to camelCase.
670
+ *
671
+ * Replaces `-x` (hyphen followed by a lowercase letter) with the uppercase
672
+ * variant. Non-hyphenated input (e.g., already camelCase) is returned as-is.
673
+ *
674
+ * @param str - A string that may contain hyphens
675
+ * @example toCamelCase("dry-run") => "dryRun"
676
+ * @example toCamelCase("output-dir") => "outputDir"
677
+ * @example toCamelCase("dryRun") => "dryRun"
678
+ */
679
+ declare function toCamelCase(str: string): string;
680
+ //#endregion
681
+ //#region ../core/src/lazy.d.ts
682
+ /**
683
+ * A lazily-loaded command that carries synchronous metadata for
684
+ * static analysis (completion, help) while deferring full module
685
+ * loading to execution time.
686
+ */
687
+ interface LazyCommand<T extends AnyCommand = AnyCommand> {
688
+ readonly __politty_lazy__: true;
689
+ readonly meta: T;
690
+ readonly load: () => Promise<AnyCommand>;
691
+ }
692
+ /**
693
+ * Type guard: check if a value is a LazyCommand
694
+ */
695
+ declare function isLazyCommand(value: unknown): value is LazyCommand;
696
+ /**
697
+ * Create a lazily-loaded subcommand with synchronous metadata.
698
+ *
699
+ * The `meta` command provides names, descriptions, and args schema
700
+ * for static analysis (completion scripts, help text) without loading
701
+ * the full command module.
702
+ *
703
+ * The `load` function is called only at execution time.
704
+ *
705
+ * @example
706
+ * ```ts
707
+ * import { lazy, defineCommand } from "politty";
708
+ *
709
+ * const cli = defineCommand({
710
+ * name: "mycli",
711
+ * subCommands: {
712
+ * deploy: lazy(
713
+ * defineCommand({
714
+ * name: "deploy",
715
+ * description: "Deploy the application",
716
+ * args: z.object({ env: arg(z.string()) }),
717
+ * }),
718
+ * () => import("./deploy.js").then((m) => m.deployCommand),
719
+ * ),
720
+ * },
721
+ * });
722
+ * ```
723
+ */
724
+ declare function lazy<T extends AnyCommand>(meta: T, load: () => Promise<AnyCommand>): LazyCommand<T>;
725
+ //#endregion
726
+ //#region ../core/src/types.d.ts
727
+ /**
728
+ * Global args interface for declaration merging (Pattern 3).
729
+ * Users can extend this interface to add global options to all commands:
730
+ *
731
+ * ```ts
732
+ * declare module "politty" {
733
+ * interface GlobalArgs { verbose: boolean; config?: string; }
734
+ * }
735
+ * ```
736
+ */
737
+ interface GlobalArgs {}
738
+ /**
739
+ * Detect empty interface (used for GlobalArgs declaration merging)
740
+ */
741
+ type IsEmpty<T> = keyof T extends never ? true : false;
742
+ /**
743
+ * Where a resolved arg value came from:
744
+ * - `"cli"`: an explicit CLI token (flag or positional)
745
+ * - `"env"`: `field.env` fallback (no CLI token was provided)
746
+ * - `"default"`: neither of the above (e.g. a schema default, or a value
747
+ * resolved by a `prompt` handler)
748
+ */
749
+ type ArgSource = "cli" | "env" | "default";
750
+ /**
751
+ * Identifies the CLI name a command was invoked with in the current run.
752
+ * - `name`: the literal token typed on the CLI to reach this command
753
+ * (a canonical subcommand name or one of its `aliases`).
754
+ * - `aliasFor`: set only when `name` is an alias, to the canonical
755
+ * subcommand name it resolves to; `undefined` when invoked by its
756
+ * canonical name (or run directly, with no subcommand routing involved).
757
+ */
758
+ interface RunInvocation {
759
+ /** The name or alias actually typed on the CLI to reach this command */
760
+ name: string;
761
+ /** Canonical name `name` is an alias for; undefined when not an alias */
762
+ aliasFor?: string | undefined;
763
+ }
764
+ /**
765
+ * Example definition for a command
766
+ */
767
+ interface Example {
768
+ /** Command arguments to execute (e.g., "World" or "--loud Alice") */
769
+ cmd: string;
770
+ /** Description of the example */
771
+ desc: string;
772
+ /** Expected output (optional, for documentation) */
773
+ output?: string;
774
+ }
775
+ /**
776
+ * Logger interface for CLI output
777
+ * Can be overridden by passing a custom logger to runMain or runCommand
778
+ */
779
+ interface Logger {
780
+ /** Log informational message to stdout */
781
+ log(message: string): void;
782
+ /** Log error message to stderr */
783
+ error(message: string): void;
784
+ /** Log warning message to stderr */
785
+ warn?(message: string): void;
786
+ }
787
+ /**
788
+ * Supported schema types for args: any Standard Schema (zod, valibot, ...)
789
+ * whose output is an object. Adapter packages narrow this back to their
790
+ * library's own schema type in their public exports (e.g. `@politty/zod`
791
+ * exports `ArgsSchema = z.ZodType<Record<string, any>>`).
792
+ */
793
+ type ArgsSchema = SchemaLike<Record<string, any>>;
794
+ /**
795
+ * Context provided to setup function
796
+ */
797
+ interface SetupContext<TArgs = unknown> {
798
+ /** Parsed and validated arguments */
799
+ args: TArgs;
800
+ }
801
+ /**
802
+ * Context provided to cleanup function
803
+ */
804
+ interface CleanupContext<TArgs = unknown> {
805
+ /** Parsed and validated arguments */
806
+ args: TArgs;
807
+ /** Error if command execution failed */
808
+ error?: Error | undefined;
809
+ }
810
+ /**
811
+ * Context provided to global setup function (runMain/runCommand level)
812
+ */
813
+ interface GlobalSetupContext {
814
+ /** AI coding agent running the CLI (see `detectAgent`); undefined when none is detected */
815
+ agent?: AgentInfo | undefined;
816
+ }
817
+ /**
818
+ * Context provided to global cleanup function (runMain/runCommand level)
819
+ */
820
+ interface GlobalCleanupContext {
821
+ /** AI coding agent running the CLI (see `detectAgent`); undefined when none is detected */
822
+ agent?: AgentInfo | undefined;
823
+ /** Error if command execution failed */
824
+ error?: Error | undefined;
825
+ }
826
+ /**
827
+ * Context passed to a function-form {@link AgentHelp}
828
+ */
829
+ interface AgentHelpContext {
830
+ /** The detected agent */
831
+ agent: AgentInfo;
832
+ /** Subcommand names from the root to the command whose help is shown (empty at the root) */
833
+ commandPath: readonly string[];
834
+ }
835
+ /**
836
+ * Agent-only guidance prepended to help output (Markdown, rendered like
837
+ * `notes`). A function form can vary it per agent or command, and returns
838
+ * `undefined` to show nothing.
839
+ */
840
+ type AgentHelp = string | ((context: AgentHelpContext) => string | undefined);
841
+ /**
842
+ * Base command interface (shared properties)
843
+ * @template TArgsSchema - The args schema type (from the CLI's schema library)
844
+ * @template TArgs - The inferred args type from the schema
845
+ */
846
+ interface CommandBase<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown> {
847
+ /** Command name (required) */
848
+ name: string;
849
+ /** Command description */
850
+ description?: string | undefined;
851
+ /** Alternative names for this command (used as subcommand aliases) */
852
+ aliases?: string[] | undefined;
853
+ /** Argument schema (preserves the original schema type) */
854
+ args: TArgsSchema;
855
+ requiredPackages?: readonly PackageRequirement<TArgs>[] | undefined;
856
+ /** Subcommands */
857
+ subCommands?: SubCommandsRecord | undefined;
858
+ /** Setup hook */
859
+ setup?: ((context: SetupContext<TArgs>) => void | Promise<void>) | undefined;
860
+ /** Cleanup hook */
861
+ cleanup?: ((context: CleanupContext<TArgs>) => void | Promise<void>) | undefined;
862
+ /** Additional notes */
863
+ notes?: string | undefined;
864
+ /** Example usages for this command */
865
+ examples?: Example[] | undefined;
866
+ /**
867
+ * @internal
868
+ * Hook invoked once at the top of `runMain`, before any parsing. Used
869
+ * by `withCompletionCommand` to fire its detached background-refresh
870
+ * spawn. Best-effort; never throws.
871
+ */
872
+ runMainHook?: ((argv: readonly string[]) => void) | undefined;
873
+ }
874
+ /**
875
+ * A command with a run function
876
+ * @template TArgsSchema - The args schema type (from the CLI's schema library)
877
+ * @template TArgs - The inferred args type from the schema
878
+ * @template TResult - The return type of the run function
879
+ */
880
+ interface RunnableCommand<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown, TResult = unknown> extends CommandBase<TArgsSchema, TArgs> {
881
+ /** Main run function */
882
+ run: (args: TArgs) => TResult;
883
+ /** Not settable alongside `run` (see `NonRunnableCommand.defaultSubCommand`) */
884
+ defaultSubCommand?: undefined;
885
+ }
886
+ /**
887
+ * A command without a run function (e.g., subcommand-only parent)
888
+ * @template TArgsSchema - The args schema type (from the CLI's schema library)
889
+ * @template TArgs - The inferred args type from the schema
890
+ */
891
+ interface NonRunnableCommand<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown> extends CommandBase<TArgsSchema, TArgs> {
892
+ /** No run function */
893
+ run?: undefined;
894
+ /**
895
+ * Name of a `subCommands` entry to run when this command is invoked with
896
+ * no subcommand specified, instead of showing help. Used for CLI plugin
897
+ * dispatch (`onUnknownSubcommand`) to reach a command group whose "no
898
+ * subcommand" case still routes somewhere runnable (e.g. `cli group`
899
+ * falling back to `cli group sub`), without the group itself defining
900
+ * `run` (which would exempt it from plugin dispatch — see
901
+ * `MainOptions.onUnknownSubcommand`).
902
+ *
903
+ * Only fires when this level has zero unconsumed tokens (the same
904
+ * condition that would otherwise show help), so it only covers a bare
905
+ * invocation — a local flag meant for the default subcommand still needs
906
+ * the subcommand named explicitly (`cli group sub --limit 10`, not
907
+ * `cli group --limit 10`), since this command's own (typically
908
+ * schema-less) parse level has no way to know `--limit` belongs to `sub`.
909
+ */
910
+ defaultSubCommand?: string | undefined;
911
+ }
912
+ /**
913
+ * A defined command (union of runnable and non-runnable)
914
+ */
915
+ type Command<TArgsSchema extends ArgsSchema | undefined = undefined, TArgs = unknown, TResult = unknown> = RunnableCommand<TArgsSchema, TArgs, TResult> | NonRunnableCommand<TArgsSchema, TArgs>;
916
+ /**
917
+ * Type alias for any args type.
918
+ * Note: `any` is required here due to TypeScript's function parameter contravariance.
919
+ * Using `unknown` would make it impossible to assign concrete command types to AnyCommand.
920
+ * @internal
921
+ */
922
+ type AnyArgs = any;
923
+ /**
924
+ * Type alias for any result type.
925
+ * @internal
926
+ */
927
+ type AnyResult = any;
928
+ /**
929
+ * Command type that accepts any args/result types
930
+ * Used in internal functions that don't need specific type information
931
+ */
932
+ type AnyCommand = Command<ArgsSchema | undefined, AnyArgs, AnyResult>;
933
+ /**
934
+ * Subcommand value type (either a command or a lazy-loaded command)
935
+ */
936
+ type SubCommandValue = AnyCommand | (() => Promise<AnyCommand>) | LazyCommand;
937
+ /**
938
+ * Record of subcommands indexed by name
939
+ */
940
+ type SubCommandsRecord = Record<string, SubCommandValue>;
941
+ /**
942
+ * Async callback to resolve missing argument values interactively.
943
+ * Called after env fallback, before schema validation.
944
+ * Provided by adapter subpath modules (e.g. `politty/prompt/clack`).
945
+ */
946
+ type PromptResolver = (rawArgs: Record<string, unknown>, extracted: ExtractedFields) => Promise<Record<string, unknown>>;
947
+ /**
948
+ * Options for runMain (CLI entry point)
949
+ */
950
+ interface MainOptions {
951
+ /** Command version */
952
+ version?: string;
953
+ /** Enable debug mode (show stack traces on errors) */
954
+ debug?: boolean;
955
+ /** Capture console and process.stdout/stderr output during execution (default: false) */
956
+ captureLogs?: boolean;
957
+ /** Skip command definition validation (useful in production where tests already verified) */
958
+ skipValidation?: boolean;
959
+ /** Custom logger for output (default: console) */
960
+ logger?: Logger;
961
+ /** Global args schema (shared across all subcommands) */
962
+ globalArgs?: ArgsSchema;
963
+ /** Global setup hook (runs before command execution) */
964
+ setup?: ((context: GlobalSetupContext) => void | Promise<void>) | undefined;
965
+ /** Global cleanup hook (runs after command execution, always executes even on error) */
966
+ cleanup?: ((context: GlobalCleanupContext) => void | Promise<void>) | undefined;
967
+ /** Whether to display errors to stderr before process.exit (default: true) */
968
+ displayErrors?: boolean;
969
+ /** Prompt resolver for interactive missing-arg prompts (e.g. from `politty/prompt/clack`). */
970
+ prompt?: PromptResolver | undefined;
971
+ /**
972
+ * Guidance for AI coding agents, shown above `--help`/`--help-all` output
973
+ * (and the help shown for a missing or unknown subcommand) only when
974
+ * `detectAgent()` detects one; humans never see it. `--help-json` carries
975
+ * it as the `agentHelp` field.
976
+ */
977
+ agentHelp?: AgentHelp | undefined;
978
+ /**
979
+ * Fallback hook for CLI plugin dispatch, invoked when a positional is not a
980
+ * known subcommand at any level whose command exposes subcommands (e.g. exec
981
+ * an external `<cli>-<path...>-<name>` binary).
982
+ *
983
+ * Return a number to treat it as handled and exit with that code; return
984
+ * `undefined` (or omit) to fall back to the default unknown-subcommand/help
985
+ * behavior. Not invoked for internal `__*` subcommands.
986
+ */
987
+ onUnknownSubcommand?: UnknownSubcommandHandler | undefined;
988
+ /**
989
+ * Node.js on-disk compile cache (V8 code cache) control. `runMain` enables
990
+ * it before executing the command so dynamically imported modules (e.g.
991
+ * `lazy()` subcommands) skip recompilation on warm starts (Node >= 22.8.0;
992
+ * no-op otherwise).
993
+ * - omitted / `true`: derive the directory from the command name
994
+ * (`${XDG_CACHE_HOME:-$HOME/.cache}/<sanitized name>/node-compile-cache`,
995
+ * shared with shell-completion workers; the name is reduced to a single
996
+ * safe path segment, e.g. `@scope/cli` → `scope-cli`)
997
+ * - `string`: use this cache directory
998
+ * - `false`: do not enable
999
+ *
1000
+ * The `NODE_COMPILE_CACHE` environment variable always takes precedence.
1001
+ * Note: the entry module's static import graph is compiled before `runMain`
1002
+ * runs and cannot be cached here — see the `compile-cache` subpath for the
1003
+ * bin-shim pattern that covers it.
1004
+ */
1005
+ compileCache?: boolean | string;
1006
+ }
1007
+ /**
1008
+ * Handler for an unrecognized subcommand. See {@link MainOptions.onUnknownSubcommand}.
1009
+ */
1010
+ type UnknownSubcommandHandler = (context: {
1011
+ /**
1012
+ * Known subcommand names traversed before the unknown name (excludes the
1013
+ * root command name). Empty at the root level.
1014
+ */
1015
+ commandPath: readonly string[];
1016
+ /** The unrecognized subcommand name (first unmatched positional). */
1017
+ name: string;
1018
+ /** Args following the name, forwarded verbatim to the plugin. */
1019
+ args: readonly string[];
1020
+ /**
1021
+ * Option tokens the host consumed before the unknown name across every
1022
+ * traversed level (e.g. global flags typed before the plugin command),
1023
+ * excluding the traversed subcommand names themselves. Concatenate with
1024
+ * `args` to reconstruct the user's full flag set when forwarding to a
1025
+ * plugin: `[...precedingArgs, ...args]`.
1026
+ */
1027
+ precedingArgs: readonly string[];
1028
+ }) => number | undefined | Promise<number | undefined>;
1029
+ /**
1030
+ * Options for runCommand (programmatic/test usage)
1031
+ */
1032
+ interface RunCommandOptions {
1033
+ /** Enable debug mode (show stack traces on errors) */
1034
+ debug?: boolean;
1035
+ /** Capture console and process.stdout/stderr output during execution (default: false) */
1036
+ captureLogs?: boolean;
1037
+ /** Skip command definition validation (useful in production where tests already verified) */
1038
+ skipValidation?: boolean;
1039
+ /** Custom logger for output (default: console) */
1040
+ logger?: Logger;
1041
+ /** Global args schema (shared across all subcommands) */
1042
+ globalArgs?: ArgsSchema;
1043
+ /** Global setup hook (runs before command execution) */
1044
+ setup?: ((context: GlobalSetupContext) => void | Promise<void>) | undefined;
1045
+ /** Global cleanup hook (runs after command execution, always executes even on error) */
1046
+ cleanup?: ((context: GlobalCleanupContext) => void | Promise<void>) | undefined;
1047
+ /** Prompt resolver for interactive missing-arg prompts (e.g. from `politty/prompt/clack`). */
1048
+ prompt?: PromptResolver | undefined;
1049
+ /**
1050
+ * Guidance for AI coding agents, shown above `--help`/`--help-all` output
1051
+ * (and the help shown for a missing or unknown subcommand) only when
1052
+ * `detectAgent()` detects one; humans never see it. `--help-json` carries
1053
+ * it as the `agentHelp` field.
1054
+ */
1055
+ agentHelp?: AgentHelp | undefined;
1056
+ }
1057
+ /**
1058
+ * Log level type
1059
+ */
1060
+ type LogLevel = "log" | "info" | "debug" | "warn" | "error";
1061
+ /**
1062
+ * Output stream type
1063
+ */
1064
+ type LogStream = "stdout" | "stderr";
1065
+ /**
1066
+ * A single log entry collected during command execution
1067
+ */
1068
+ interface LogEntry {
1069
+ /** Log message */
1070
+ message: string;
1071
+ /** Timestamp when the log was recorded */
1072
+ timestamp: Date;
1073
+ /** Log level */
1074
+ level: LogLevel;
1075
+ /** Output stream (stdout or stderr) */
1076
+ stream: LogStream;
1077
+ }
1078
+ /**
1079
+ * Collected logs during command execution
1080
+ */
1081
+ interface CollectedLogs {
1082
+ /** All log entries in order */
1083
+ entries: LogEntry[];
1084
+ }
1085
+ /**
1086
+ * Successful command execution result
1087
+ */
1088
+ interface RunResultSuccess<T = unknown> {
1089
+ /** Indicates successful execution */
1090
+ success: true;
1091
+ /** Command return value */
1092
+ result: T | undefined;
1093
+ /** Error that occurred during execution */
1094
+ error?: never;
1095
+ /** Exit code (always 0 for success) */
1096
+ exitCode: 0;
1097
+ /** Collected logs during execution */
1098
+ logs: CollectedLogs;
1099
+ }
1100
+ /**
1101
+ * Failed command execution result
1102
+ */
1103
+ interface RunResultFailure {
1104
+ /** Indicates failed execution */
1105
+ success: false;
1106
+ /** Command return value */
1107
+ result?: never;
1108
+ /** Error that occurred during execution */
1109
+ error: Error;
1110
+ /**
1111
+ * Exit code: 2 when the command line is invalid (an unknown flag or
1112
+ * subcommand, an unexpected positional argument, or arguments that fail
1113
+ * validation), 1 for other failures, or the exit code an
1114
+ * `onUnknownSubcommand` plugin returned
1115
+ */
1116
+ exitCode: number;
1117
+ /** Collected logs during execution */
1118
+ logs: CollectedLogs;
1119
+ }
1120
+ /**
1121
+ * Result of command execution (discriminated union)
1122
+ */
1123
+ type RunResult<T = unknown> = RunResultSuccess<T> | RunResultFailure;
1124
+ //#endregion
1125
+ export { DynamicCompletionCandidate as $, SubCommandsRecord as A, ArgFn as B, RunInvocation as C, RunnableCommand as D, RunResultSuccess as E, ExtractedFields as F, EffectContext as G, CompletionMeta as H, ResolvedFieldMeta as I, ValidateArgMeta as J, PromptMeta as K, UnknownKeysMode as L, LazyCommand as M, isLazyCommand as N, SetupContext as O, lazy as P, CompletionDirectiveMask as Q, toCamelCase as R, RunCommandOptions as S, RunResultFailure as T, CompletionType as U, ArgMeta as V, CustomCompletion as W, ExpandCompletion as X, ExpandCandidate as Y, ResolvedExpandCandidate as Z, LogStream as _, ArgsSchema as a, InferSchemaOutput as at, NonRunnableCommand as b, Command as c, GlobalArgs as d, DynamicCompletionContext as et, GlobalCleanupContext as f, LogLevel as g, LogEntry as h, ArgSource as i, loadPackage as it, UnknownSubcommandHandler as j, SubCommandValue as k, CommandBase as l, IsEmpty as m, AgentHelpContext as n, DynamicCompletionResult as nt, CleanupContext as o, SchemaLike as ot, GlobalSetupContext as p, PromptType as q, AnyCommand as r, PackageRequirement as rt, CollectedLogs as s, AgentHelp as t, DynamicCompletionResolver as tt, Example as u, Logger as v, RunResult as w, PromptResolver as x, MainOptions as y, toKebabCase as z };