bailian-cli-runtime 1.6.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,17 @@
1
- import { Command, Command as Command$1, Config, GlobalFlags, OptionDef, OptionDef as OptionDef$1, OutputFormat, ResolvedCredential } from "bailian-cli-core";
1
+ import { AnyCommand, ApiKeyCredential, AuthStore, Client, Command, CommandPackManager, ConfigStore, FlagDef, FlagsDef, Identity, OutputFormat, ParsedFlags, ResolutionSources, Settings, UsageError } from "bailian-cli-core";
2
2
 
3
+ //#region src/command-packs/types.d.ts
4
+ interface CommandPackDefinition {
5
+ commandPrefixes: readonly string[];
6
+ /** Raw credential domains explicitly delegated to this trusted package. */
7
+ credentialAccess?: readonly CommandPackCredentialAccess[];
8
+ }
9
+ type CommandPackCredentialAccess = "apiKey";
10
+ /** Product policy: each CLI explicitly declares which Command Packs it accepts. */
11
+ interface CommandPackPolicy {
12
+ supported: Readonly<Record<string, CommandPackDefinition>>;
13
+ }
14
+ //#endregion
3
15
  //#region src/create-cli.d.ts
4
16
  /** Per-product identity injected by each CLI entrypoint (bl / rag / …). */
5
17
  interface CliOptions {
@@ -7,38 +19,65 @@ interface CliOptions {
7
19
  binName: string;
8
20
  /** Product version for `--version` output, telemetry and update checks. */
9
21
  version: string;
10
- /** Telemetry client name (e.g. "bailian-cli", "rag-cli"). Defaults to `binName`. */
11
- clientName?: string;
22
+ /** User-Agent / telemetry client name (e.g. "bailian-cli", "rag-cli")。必填,无默认。 */
23
+ clientName: string;
12
24
  /** npm package name for self-update (e.g. "bailian-cli", "bailian-cli-rag"). */
13
25
  npmPackage: string;
26
+ /** Root-help suggestions shown after credentials are configured. */
27
+ quickStartTasks?: readonly string[];
28
+ /** Command Packs accepted by this product. Omit when the product supports none. */
29
+ commandPacks?: CommandPackPolicy;
14
30
  }
15
31
  interface Cli {
16
32
  run(argv?: string[]): Promise<void>;
17
33
  }
18
34
  /**
19
- * Build a CLI from an injected command set. The runtime is agnostic to *which*
20
- * commands exist each product (bailian-cli, rag-cli, …) passes its own map and
21
- * identity. No module-level singleton: the registry is scoped to this instance.
35
+ * Build a CLI from an injected command set each product (bl / rag / …) passes
36
+ * its own commands + identity. `run` resolves argv into a {@link Resolution},
37
+ * then dispatches it.
22
38
  */
23
- declare function createCli(commands: Record<string, Command$1>, opts: CliOptions): Cli;
39
+ declare function createCli(commands: Record<string, AnyCommand>, opts: CliOptions): Cli;
24
40
  //#endregion
25
41
  //#region src/registry.d.ts
42
+ /**
43
+ * What a command path resolves to in the registry. The single judgement that
44
+ * feeds `resolve()` — no scattered `isGroupPath` + throwing `resolve`.
45
+ * - leaf: landed *exactly* on an executable command (no leftover tokens).
46
+ * - group: landed on a command group with no executable of its own (incl. root []).
47
+ * - unknown: the path doesn't exist, or a valid command had unexpected trailing
48
+ * tokens (no positionals); `error` carries the message + hint.
49
+ */
50
+ type LocateResult = {
51
+ kind: "leaf";
52
+ command: AnyCommand;
53
+ matched: string[];
54
+ } | {
55
+ kind: "group";
56
+ matched: string[];
57
+ } | {
58
+ kind: "unknown";
59
+ error: UsageError;
60
+ };
26
61
  declare class CommandRegistry {
27
62
  private root;
28
63
  /** Binary name shown in usage/help/error strings (e.g. "bl", "rag"). */
29
64
  private readonly cliName;
30
- constructor(commands: Record<string, Command$1>, cliName: string);
65
+ private readonly authRequirements;
66
+ constructor(commands: Record<string, AnyCommand>, cliName: string);
31
67
  private register;
32
- getAllCommands(): Command$1[];
68
+ getAllCommands(): AnyCommand[];
33
69
  /** First registered command path, for the "Getting Help" example (e.g. "knowledge retrieve"). */
34
70
  private helpExample;
35
- isGroupPath(commandPath: string[]): boolean;
36
- resolve(commandPath: string[]): {
37
- command: Command$1;
38
- extra: string[];
39
- };
71
+ /**
72
+ * Resolve a command path to a leaf / group / unknown outcome. Pure: walks the
73
+ * trie taking the longest registered prefix as the command. There are no
74
+ * positionals, so a valid command followed by leftover tokens is `unknown`
75
+ * (unexpected argument). Never throws — unknown paths return a carried UsageError.
76
+ */
77
+ locate(commandPath: string[]): LocateResult;
40
78
  private buildResourceLines;
41
- private buildGlobalFlagLines;
79
+ private buildFlagLines;
80
+ private buildAuthFlagSection;
42
81
  private bold;
43
82
  private accent;
44
83
  private dim;
@@ -49,21 +88,91 @@ declare class CommandRegistry {
49
88
  private printChildren;
50
89
  }
51
90
  //#endregion
91
+ //#region src/resolve.d.ts
92
+ /**
93
+ * What an invocation resolves to — "what to do" expressed as data, not control
94
+ * flow. A single pure function (`resolve`) produces one of these; `createCli`'s
95
+ * dispatch switches on it. No scattered `argv.includes(...)` + `process.exit`.
96
+ * - version: print the version and stop.
97
+ * - help: print help for `path` (root [] / a group / an explicit --help). Terminal.
98
+ * - run: execute `command`; `rest` is the flag region for parseFlags.
99
+ * - usageError: the path doesn't exist (or has unexpected args); render and stop.
100
+ */
101
+ type Resolution = {
102
+ kind: "version";
103
+ } | {
104
+ kind: "help";
105
+ path: string[];
106
+ } | {
107
+ kind: "run";
108
+ path: string[];
109
+ command: AnyCommand;
110
+ rest: string[];
111
+ } | {
112
+ kind: "usageError";
113
+ error: UsageError;
114
+ };
115
+ /**
116
+ * Classify argv into a {@link Resolution}. Pure over (argv, registry): one
117
+ * `parsePath` scan for the command path + flag region, one `registry.locate`
118
+ * for the routing decision. Never throws. Trivially unit-testable.
119
+ */
120
+ declare function resolve(argv: string[], registry: CommandRegistry): Resolution;
121
+ //#endregion
122
+ //#region src/middleware.d.ts
123
+ /**
124
+ * What each middleware stage gets for the invocation in flight: the matched
125
+ * `command` with its `path`/`settings`/`flags`, and the `client` (populated by
126
+ * {@link authStage}). A stage reads these and may augment them before `next()`.
127
+ */
128
+ interface RunContext {
129
+ /** 静态产品身份(binName/version/npmPackage/clientName)。 */
130
+ readonly identity: Identity;
131
+ /** The matched command path, e.g. ["speech","recognize"]. */
132
+ readonly path: string[];
133
+ readonly command: AnyCommand;
134
+ /** 只含本命令声明的 flag(分流后);全局 flag 在 sources/settings。 */
135
+ flags: ParsedFlags<FlagsDef>;
136
+ /** 解析后的有效配置面(命令的新读取面;双轨迁移期与 config 并存)。 */
137
+ settings: Settings;
138
+ /** 解析源:provider/访问器用;业务命令不可见(窄视图类型不含此字段)。 */
139
+ sources: ResolutionSources;
140
+ /** 配置持久化能力;lint 限定 commands/config/** 使用。 */
141
+ configStore: ConfigStore;
142
+ /** 鉴权持久化能力;lint 限定 commands/auth/** 使用。 */
143
+ authStore: AuthStore;
144
+ /** Command Pack 管理能力;lint 限定 commands/plugin/** 使用。 */
145
+ commandPacks: CommandPackManager;
146
+ /** Network surface with the credential baked in — set by {@link authStage}. */
147
+ client: Client;
148
+ }
149
+ /** Koa-style onion middleware: do work, call `next()`, do work after it returns. */
150
+ type Middleware = (ctx: RunContext, next: () => Promise<void>) => Promise<void>;
151
+ /** Fold a middleware list into a single runnable function. */
152
+ declare function compose(stack: Middleware[]): (ctx: RunContext) => Promise<void>;
153
+ //#endregion
52
154
  //#region src/args.d.ts
155
+ interface ParsePathResult {
156
+ /** Command path: the leading run of bare tokens, e.g. ["speech", "recognize"]. */
157
+ path: string[];
158
+ /** Everything from the first flag onward — handed to parseFlags later. */
159
+ rest: string[];
160
+ hasHelpFlag: boolean;
161
+ hasVersionFlag: boolean;
162
+ }
53
163
  /**
54
- * Quick scan: collect positional (non-dash) args to determine the command path.
55
- * Skips global flags and their values so that e.g. `--output json text chat`
56
- * correctly produces ['text', 'chat'] instead of ['json', 'text', 'chat'].
164
+ * First pass routing only. The command path is the leading run of bare
165
+ * (non-`-`) tokens; the first flag ends it ("command path first, then flags",
166
+ * oclif-style). There are no positionals, so nothing bare can legitimately
167
+ * follow a flag — and no flags precede the path, so this needs no schema.
57
168
  */
58
- declare function scanCommandPath(argv: string[], globalOptions?: OptionDef$1[]): string[];
169
+ declare function parsePath(argv: string[]): ParsePathResult;
59
170
  /**
60
- * Full flag parse. Types are derived entirely from the provided OptionDef schema:
61
- * - boolean: no <value> placeholder in flag string (or type: 'boolean')
62
- * - number: type: 'number'
63
- * - array: type: 'array' (repeatable via multiple --flag occurrences)
64
- * - default: string
171
+ * Second pass parse the flag region into typed values, driven entirely by the
172
+ * keyed FlagsDef (key = camelCase flag name). Pure: returns typed flags or
173
+ * throws UsageError — never prints/exits. The error boundary decides rendering.
65
174
  */
66
- declare function parseFlags(argv: string[], options: OptionDef$1[]): GlobalFlags;
175
+ declare function parseFlags<F extends FlagsDef>(rest: string[], defs: F): ParsedFlags<F>;
67
176
  //#endregion
68
177
  //#region src/proxy.d.ts
69
178
  declare function setupProxyFromEnv(): void;
@@ -94,13 +203,8 @@ declare const VOICE_TTS_PAGE = "https://help.aliyun.com/zh/model-studio/cosyvoic
94
203
  //#region src/output/output.d.ts
95
204
  /**
96
205
  * Emit the primary result of a command.
97
- *
98
- * Design principle:
99
- * stdout → structured data only (JSON when piped, text when TTY)
100
- * stderr → human info (progress, logs, tips) — handled elsewhere
101
- *
102
- * This ensures `bl cmd ... | jq .` always receives clean JSON,
103
- * while interactive users see human-readable text.
206
+ * stdout → result (text by default; JSON with --output json)
207
+ * stderr human info (progress, logs, tips) — handled elsewhere
104
208
  */
105
209
  declare function emitResult(data: unknown, format: OutputFormat): void;
106
210
  /**
@@ -123,49 +227,34 @@ declare function formatTable(headers: string[], rows: string[][], {
123
227
  gap?: number;
124
228
  }): string[];
125
229
  //#endregion
126
- //#region src/output/prompt.d.ts
127
- /**
128
- * Build a command-usage string for the running command: `<binName> <path> <args>`.
129
- * Both the product binary name and the command path come from the runtime, so
130
- * callers never hardcode "bl" or their own path the same code renders as
131
- * `bl knowledge retrieve …` under bl and `rag retrieve …` under rag.
132
- */
133
- declare function cmdUsage(config: Config, args?: string): string;
134
- /**
135
- * Prompt the user for a text value.
136
- * Only call this when isInteractive() is true; otherwise the function returns
137
- * undefined immediately so the caller can fail fast.
138
- */
139
- declare function promptText(options: {
140
- message: string;
141
- defaultValue?: string;
142
- }): Promise<string | undefined>;
143
- /**
144
- * Like promptText but confirms with y/N before proceeding.
145
- */
146
- declare function promptConfirm(options: {
147
- message: string;
148
- initialValue?: boolean;
149
- }): Promise<boolean | undefined>;
150
- /**
151
- * Prompt the user to select one value from a list.
152
- * Only call this when isInteractive() is true; otherwise the function returns
153
- * undefined immediately so the caller can fail fast.
154
- */
155
- declare function promptSelect(options: {
156
- message: string;
157
- choices: Array<{
158
- value: string;
159
- label: string;
160
- hint?: string;
161
- }>;
162
- defaultValue?: string;
163
- }): Promise<string | undefined>;
230
+ //#region src/output/box-table.d.ts
231
+ interface BarColumn {
232
+ /** Zero-based index of the column rendered as a gauge. */
233
+ index: number;
234
+ /** Percent (0-100) per row, aligned with `rows`; null renders an empty gauge. */
235
+ percents: (number | null)[];
236
+ /** Optional text shown after each gauge (e.g. "84%", "expired"); overrides the default percent label. */
237
+ labels?: (string | null)[];
238
+ /** Gauge width in cells (default 20). */
239
+ width?: number;
240
+ }
241
+ interface BoxTableOptions {
242
+ headers: string[];
243
+ rows: string[][];
244
+ /** Per-column alignment; defaults to left. */
245
+ align?: ("left" | "right")[];
246
+ /** One or more gauge columns rendered as progress bars. */
247
+ barColumns?: BarColumn[];
248
+ /** Return a colored variant of a plain cell value (must keep the same visible width). */
249
+ cellColor?: (rowIndex: number, colIndex: number, value: string) => string | undefined;
250
+ /** Stream used for color capability detection (default process.stdout). */
251
+ out?: NodeJS.WriteStream;
252
+ }
164
253
  /**
165
- * Fail fast with a user-friendly error when a required option is missing
166
- * in non-interactive (agent / CI) mode.
254
+ * Render a bordered table as an array of lines. The header row is drawn as a
255
+ * solid highlight bar that extends to the full table width.
167
256
  */
168
- declare function failIfMissing(flagName: string, context: string): never;
257
+ declare function renderBoxTable(options: BoxTableOptions): string[];
169
258
  //#endregion
170
259
  //#region src/output/progress.d.ts
171
260
  interface Spinner {
@@ -182,17 +271,41 @@ declare function createProgressBar(total: number, label?: string): ProgressBar;
182
271
  //#endregion
183
272
  //#region src/output/banner.d.ts
184
273
  declare function printWelcomeBanner(cliName: string): void;
185
- declare function printQuickStart(): void;
274
+ declare function printQuickStart(tasks: readonly string[]): void;
186
275
  //#endregion
187
276
  //#region src/output/status-bar.d.ts
188
- declare function maybeShowStatusBar(config: Config, token: string, resolved?: ResolvedCredential): void;
277
+ declare function maybeShowStatusBar(settings: Settings, token: string, resolved: ApiKeyCredential): void;
189
278
  //#endregion
190
279
  //#region src/output/cjk-width.d.ts
191
280
  declare function displayWidth(text: string): number;
192
281
  declare function padEnd(text: string, targetWidth: number): string;
193
282
  //#endregion
283
+ //#region src/output/color.d.ts
284
+ type TextStyle = (text: string) => string;
285
+ interface AnsiStyles {
286
+ bold: TextStyle;
287
+ dim: TextStyle;
288
+ green: TextStyle;
289
+ yellow: TextStyle;
290
+ red: TextStyle;
291
+ cyan: TextStyle;
292
+ blue: TextStyle;
293
+ magenta: TextStyle;
294
+ white: TextStyle;
295
+ accent: TextStyle;
296
+ logo: TextStyle;
297
+ purple: TextStyle;
298
+ brandBlue: TextStyle;
299
+ keyPink: TextStyle;
300
+ reset: string;
301
+ }
302
+ declare function isTerminal(out: NodeJS.WriteStream): boolean;
303
+ declare function supportsColor(out: NodeJS.WriteStream): boolean;
304
+ declare function ansi(out: NodeJS.WriteStream): AnsiStyles;
305
+ //#endregion
194
306
  //#region src/utils/polling.d.ts
195
307
  interface PollOptions {
308
+ /** Absolute task URL (Client passes absolute URLs through as-is). */
196
309
  url: string;
197
310
  intervalSec: number;
198
311
  timeoutSec: number;
@@ -201,7 +314,7 @@ interface PollOptions {
201
314
  getStatus?: (data: unknown) => string;
202
315
  getErrorMessage?: (data: unknown) => string | undefined;
203
316
  }
204
- declare function poll<T>(config: Config, opts: PollOptions): Promise<T>;
317
+ declare function poll<T>(client: Client, settings: Settings, opts: PollOptions): Promise<T>;
205
318
  //#endregion
206
319
  //#region src/utils/download.d.ts
207
320
  declare function downloadFile(url: string, destPath: string, opts?: {
@@ -212,19 +325,21 @@ declare function downloadFile(url: string, destPath: string, opts?: {
212
325
  declare function formatBytes(bytes: number): string;
213
326
  //#endregion
214
327
  //#region src/utils/concurrent.d.ts
215
- /** Resolve concurrency from flags (defaults to 1). */
216
- declare function getConcurrency(flags: GlobalFlags): number;
328
+ /** Resolve concurrency from parsed command flags(`--concurrent`,defaults to 1). */
329
+ declare function getConcurrency(flags: {
330
+ concurrent?: number;
331
+ }): number;
217
332
  /**
218
333
  * Run an async task N times concurrently.
219
334
  * Returns all resolved results in order.
220
335
  * If any single task fails, the error propagates (Promise.all semantics).
221
336
  *
222
- * @param n Number of concurrent executions
223
- * @param config CLI config (for logging)
224
- * @param task Async factory to execute
225
- * @param label Optional label for status output (e.g. "requests", "tasks")
337
+ * @param n Number of concurrent executions
338
+ * @param settings Resolved settings (for logging)
339
+ * @param task Async factory to execute
340
+ * @param label Optional label for status output (e.g. "requests", "tasks")
226
341
  */
227
- declare function runConcurrent<T>(n: number, config: Config, task: (index: number) => Promise<T>, label?: string): Promise<T[]>;
342
+ declare function runConcurrent<T>(n: number, settings: Settings, task: (index: number) => Promise<T>, label?: string): Promise<T[]>;
228
343
  /**
229
344
  * Parallel download helper — downloads multiple URLs concurrently.
230
345
  *
@@ -247,16 +362,6 @@ declare function downloadParallel(items: Array<{
247
362
  declare function resolveImageSize(input: string, useSync: boolean): string;
248
363
  declare function resolveImageSize(input: string | undefined, useSync: boolean): string | undefined;
249
364
  //#endregion
250
- //#region src/utils/ensure-key.d.ts
251
- declare function ensureApiKey(config: Config): Promise<void>;
252
- //#endregion
253
- //#region src/utils/command-help.d.ts
254
- declare function setExecutingCommandPath(path: string[]): void;
255
- declare function getExecutingCommandPath(): string[];
256
- declare function registerCommandHelpPrinter(fn: (commandPath: string[], out: NodeJS.WriteStream) => void): void;
257
- /** Print help for the command currently being executed (must call `setExecutingCommandPath` first). */
258
- declare function printCurrentCommandHelp(out?: NodeJS.WriteStream): void;
259
- //#endregion
260
365
  //#region src/utils/update-checker.d.ts
261
366
  declare const NPM_REGISTRY = "https://registry.npmjs.org";
262
367
  /** Default npm package; products override per-call via the `npmPackage` argument. */
@@ -547,7 +652,7 @@ interface StepContext {
547
652
  timeoutSeconds?: number;
548
653
  blRequestTimeoutSeconds?: number;
549
654
  emitEvent?: (event: Record<string, unknown>) => void | Promise<void>;
550
- blConfig?: unknown;
655
+ blEnv?: unknown;
551
656
  }
552
657
  //#endregion
553
658
  //#region src/pipeline/dispatcher.d.ts
@@ -576,4 +681,4 @@ declare function collectPipelineHints(pipeline: PipelineDefinition, dispatcher?:
576
681
  declare function executePipeline(pipeline: PipelineDefinition, runtimeInput?: Record<string, unknown>, options?: ExecutePipelineOptions): Promise<PipelineExecutionReport>;
577
682
  declare function streamPipelineEvents(pipeline: PipelineDefinition, runtimeInput?: Record<string, unknown>, options?: Pick<ExecutePipelineOptions, "concurrency" | "basePath" | "dryRun" | "signal" | "timeoutSeconds" | "blRequestTimeoutSeconds" | "stepDispatcher">): AsyncGenerator<PipelineLifecycleEvent>;
578
683
  //#endregion
579
- export { API_KEY_PAGE, BAILIAN_CONSOLE, BAILIAN_CONSOLE_ROOT, BOOL_FLAG_PROMPT_EXTEND_API_DEFAULT, BOOL_FLAG_PROMPT_EXTEND_CLI_TRUE, BOOL_FLAG_PROMPT_EXTEND_IMAGE_GENERATE, BOOL_FLAG_WATERMARK, CLI_VERSION, type Cli, type CliOptions, type Command, CommandRegistry, NPM_PACKAGE, NPM_REGISTRY, type OptionDef, type PipelineDefinition, type PipelineLifecycleEvent, VOICE_TTS_PAGE, checkForUpdate, cmdUsage, collectPipelineHints, collectPipelineIssues, createCli, createProgressBar, createSpinner, displayWidth, downloadFile, downloadParallel, emitBare, emitResult, ensureApiKey, executePipeline, failIfMissing, fetchLatestVersion, formatBytes, formatTable, getConcurrency, getExecutingCommandPath, getPendingUpdateNotification, handleError, initPipelineSteps, maybeShowStatusBar, padEnd, parseFlags, poll, printCurrentCommandHelp, printQuickStart, printWelcomeBanner, promptConfirm, promptSelect, promptText, registerCommandHelpPrinter, resolveImageSize, runConcurrent, scanCommandPath, setExecutingCommandPath, setupProxyFromEnv, streamPipelineEvents };
684
+ export { API_KEY_PAGE, type AnsiStyles, BAILIAN_CONSOLE, BAILIAN_CONSOLE_ROOT, BOOL_FLAG_PROMPT_EXTEND_API_DEFAULT, BOOL_FLAG_PROMPT_EXTEND_CLI_TRUE, BOOL_FLAG_PROMPT_EXTEND_IMAGE_GENERATE, BOOL_FLAG_WATERMARK, type BarColumn, type BoxTableOptions, CLI_VERSION, type Cli, type CliOptions, type Command, type CommandPackCredentialAccess, type CommandPackDefinition, type CommandPackPolicy, CommandRegistry, type FlagDef, type LocateResult, type Middleware, NPM_PACKAGE, NPM_REGISTRY, type ParsePathResult, type PipelineDefinition, type PipelineLifecycleEvent, type Resolution, type RunContext, type TextStyle, VOICE_TTS_PAGE, ansi, checkForUpdate, collectPipelineHints, collectPipelineIssues, compose, createCli, createProgressBar, createSpinner, displayWidth, downloadFile, downloadParallel, emitBare, emitResult, executePipeline, fetchLatestVersion, formatBytes, formatTable, getConcurrency, getPendingUpdateNotification, handleError, initPipelineSteps, isTerminal, maybeShowStatusBar, padEnd, parseFlags, parsePath, poll, printQuickStart, printWelcomeBanner, renderBoxTable, resolve, resolveImageSize, runConcurrent, setupProxyFromEnv, streamPipelineEvents, supportsColor };