//#region src/errors/codes.d.ts export declare const ExitCode: { readonly SUCCESS: 0; readonly GENERAL: 1; readonly USAGE: 2; readonly AUTH: 3; readonly QUOTA: 4; readonly TIMEOUT: 5; readonly NETWORK: 6; readonly CONFIRMATION_REQUIRED: 7; readonly CONTENT_FILTER: 10; }; export type ExitCode = (typeof ExitCode)[keyof typeof ExitCode]; //#endregion //#region src/errors/base.d.ts interface ApiErrorContext { httpStatus?: number; apiCode?: string; requestId?: string; } interface BailianErrorOptions { cause?: unknown; api?: ApiErrorContext; rawResponse?: string; } export declare class BailianError extends Error { readonly exitCode: ExitCode; readonly hint?: string; readonly api?: ApiErrorContext; readonly rawResponse?: string; constructor(message: string, exitCode?: ExitCode, hint?: string, options?: BailianErrorOptions); toJSON(): { error: { cause?: Record | undefined; request_id?: string | undefined; api_code?: string | undefined; http_status?: number | undefined; hint?: string | undefined; code: ExitCode; message: string; }; }; } /** Invalid usage: unknown command, bad/unknown flag, missing required, failed validation. */ export declare class UsageError extends BailianError { constructor(message: string, hint?: string); } //#endregion //#region src/errors/api.d.ts interface ApiErrorBody { error?: { message?: string; type?: string; code?: number | string; }; code?: number | string; message?: string; request_id?: string; requestID?: string; } export declare function mapApiError(status: number, body: ApiErrorBody, _url?: string): BailianError; //#endregion //#region src/types/api.d.ts interface ChatMessage { role: "system" | "user" | "assistant"; content: string | ChatMessageContent[]; } type ChatMessageContent = { type: "text"; text: string; } | { type: "image_url"; image_url: { url: string; }; } | { type: "input_audio"; input_audio: { data: string; format?: string; }; } | { type: "audio_url"; audio_url: { url: string; }; } | { type: "video"; video: string[]; } | { type: "video_url"; video_url: { url: string; }; }; interface ChatTool { type: "function"; function: { name: string; description?: string; parameters: Record; }; } interface ChatResponseFormat { type: "json_object" | "json_schema"; json_schema?: { name: string; schema?: Record; strict?: boolean; }; } interface ChatRequest { model: string; messages: ChatMessage[]; max_tokens?: number; temperature?: number; top_p?: number; stream?: boolean; tools?: ChatTool[]; tool_choice?: "auto" | "none" | { type: "function"; function: { name: string; }; }; enable_thinking?: boolean; thinking_budget?: number; modalities?: string[]; audio?: { voice: string; format?: string; }; stream_options?: { include_usage?: boolean; }; response_format?: ChatResponseFormat; } interface ChatChoice { index: number; message: { role: "assistant"; content: string | null; reasoning_content?: string | null; tool_calls?: Array<{ id: string; type: "function"; function: { name: string; arguments: string; }; }>; }; finish_reason: string; } interface ChatResponse { id: string; object: "chat.completion"; created: number; model: string; choices: ChatChoice[]; usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number; }; } interface StreamChoice { index: number; delta: { role?: string; content?: string | null; reasoning_content?: string | null; audio?: { data?: string; id?: string; expires_at?: number; }; tool_calls?: Array<{ index: number; id?: string; type?: "function"; function?: { name?: string; arguments?: string; }; }>; }; finish_reason: string | null; } interface StreamChunk { id: string; object: "chat.completion.chunk"; created: number; model: string; choices: StreamChoice[]; usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number; }; } interface ResponsesRequest { model: string; input: ChatMessage[]; max_output_tokens?: number; temperature?: number; top_p?: number; stream?: boolean; tools?: Array>; enable_thinking?: boolean; } interface ResponsesOutputContent { type: string; text?: string; } interface ResponsesOutputItem { type: string; content?: ResponsesOutputContent[]; [key: string]: unknown; } interface ResponsesResponse { id: string; object: "response"; status: string; output: ResponsesOutputItem[]; [key: string]: unknown; } interface ResponsesStreamEvent { type: string; delta?: string; [key: string]: unknown; } interface DashScopeImageRequest { model: string; input: { messages: Array<{ role: "user"; content: Array<{ text?: string; image?: string; }>; }>; } | { prompt: string; /** Required by image2image models such as wan2.5-i2i-preview. */ images?: string[]; negative_prompt?: string; } | { /** Required by wanx*-imageedit models. */ function: string; prompt: string; base_image_url: string; mask_image_url?: string; }; parameters?: { size?: string; n?: number; seed?: number; prompt_extend?: boolean; watermark?: boolean; negative_prompt?: string; strength?: number; }; } interface DashScopeImageSyncResponse { output: { choices: Array<{ finish_reason: string; message: { role: "assistant"; content: Array<{ image: string; type: "image"; }>; }; }>; finished: boolean; }; usage: { image_count: number; }; request_id: string; } interface DashScopeVideoRequest { model: string; input: { prompt: string; negative_prompt?: string; img_url?: string; first_frame_url?: string; last_frame_url?: string; media?: Array<{ type: "image" | "video" | "first_frame" | "last_frame" | "driving_audio" | "first_clip" | "file"; url: string; }>; }; parameters?: { resolution?: string; ratio?: string; duration?: number; prompt_extend?: boolean; watermark?: boolean; seed?: number; }; } interface DashScopeVideoRefRequest { model: string; input: { prompt: string; media: Array<{ type: "reference_image" | "reference_video" | "reference_audio"; url: string; reference_voice?: string; }>; }; parameters?: { resolution?: string; ratio?: string; duration?: number; prompt_extend?: boolean; watermark?: boolean; seed?: number; }; } interface DashScopeVideoEditRequest { model: string; input: { prompt?: string; negative_prompt?: string; media: Array<{ type: "video" | "reference_image"; url: string; }>; }; parameters?: { resolution?: string; ratio?: string; duration?: number; audio_setting?: "auto" | "origin"; prompt_extend?: boolean; watermark?: boolean; seed?: number; }; } interface AppCompletionRequest { input: { prompt?: string; session_id?: string; image_list?: string[]; file_ids?: string[]; biz_params?: Record; }; parameters?: { has_thoughts?: boolean; incremental_output?: boolean; rag_options?: { pipeline_ids?: string[]; knowledge_base_ids?: string[]; }; memory_id?: string; }; debug?: Record; } interface AppCompletionResponse { output: { text: string; finish_reason: string; session_id: string; thoughts?: Array<{ thought: string; action_type: string; action_name: string; action: string; action_input_stream: string; action_input: string; response: string; observation: string; }>; doc_references?: Array<{ index_id: string; title: string; doc_id: string; doc_name: string; text: string; images?: string[]; }>; }; usage: { models: Array<{ model_id: string; input_tokens: number; output_tokens: number; }>; }; request_id: string; } interface AppStreamChunk { output: { text: string; finish_reason: string; session_id: string; thoughts?: AppCompletionResponse["output"]["thoughts"]; doc_references?: AppCompletionResponse["output"]["doc_references"]; }; usage?: AppCompletionResponse["usage"]; request_id: string; } interface MemoryMessage { role: "user" | "assistant"; content: string; } interface MemoryAddRequest { user_id: string; messages?: MemoryMessage[]; custom_content?: string; profile_schema?: string; memory_library_id?: string; } interface MemoryAddResponse { request_id: string; memory_ids?: string[]; } interface MemorySearchRequest { user_id: string; messages?: MemoryMessage[]; query?: string; top_k?: number; memory_library_id?: string; } interface MemoryNode { memory_node_id: string; content: string; user_id?: string; meta_data?: Record; created_at?: string; updated_at?: string; } interface MemorySearchResponse { request_id: string; memory_nodes: MemoryNode[]; } interface MemoryNodeListResponse { request_id: string; memory_nodes: MemoryNode[]; total?: number; page_num?: number; page_size?: number; } interface MemoryNodeUpdateRequest { user_id: string; custom_content: string; /** 非默认记忆库时必填(与控制台记忆库 ID 一致) */ memory_library_id?: string; } interface ProfileAttribute { name: string; description: string; value?: string; } interface ProfileSchemaCreateRequest { name: string; description?: string; attributes: ProfileAttribute[]; } interface ProfileSchemaCreateResponse { request_id: string; profile_schema_id: string; } interface UserProfileResponse { request_id: string; profile: { schema_id: string; user_id: string; attributes: ProfileAttribute[]; }; } interface DashScopeKnowledgeRetrieveRequest { index_id: string; query: string; search_filters?: Array>; dense_similarity_top_k?: number; sparse_similarity_top_k?: number; enable_reranking?: boolean; rerank_top_n?: number; rerank?: Array<{ model_name: string; rerank_mode?: string; rerank_instruct?: string; }>; } interface DashScopeKnowledgeRetrieveResponse { request_id: string; data: { total: number; nodes: Array<{ text: string; score: number; metadata: Record; }>; }; } interface KnowledgeSearchRequest { query: string; agent_id: string; /** "beta" targets the debug draft; a numeric version targets that published version; defaults to the latest published version */ agent_version?: string; images?: string[]; } interface KnowledgeSearchResponse { code: string; status_code: number; request_id: string; data: { total: number; cost_time: number; nodes: Array<{ score: number; text: string; metadata: { content?: string; title?: string; doc_id?: string; doc_name?: string; doc_url?: string; pipeline_id?: string; workspace_id?: string; page_number?: number; image_url?: string; _knowledge_type?: string; _citation_index?: number; _score?: number; }; }>; }; } type KnowledgeChatContentPart = { type: "text"; text: string; } | { type: "image_url"; image_url: { url: string; }; }; interface KnowledgeChatMessage { role: "user" | "assistant"; content: string | KnowledgeChatContentPart[]; } interface KnowledgeChatRequest { input: { messages: KnowledgeChatMessage[]; }; parameters: { agent_options: { agent_id: string; /** "beta" targets the debug draft; a numeric version targets that published version; defaults to the latest published version */ agent_version?: string; user?: { user_id?: string; workspace_id?: string; }; }; }; stream: boolean; } interface KnowledgeChatStreamChunk { output: { choices: Array<{ message: { role: string; content: string; tool_calls?: unknown[]; extra?: { group?: string; step_change?: string; step?: string; }; }; finish_reason: string; }>; }; code: string; message: string; request_id: string; } interface DashScopeTTSRequest { model: string; input: { text: string; voice?: string; format?: "mp3" | "pcm" | "wav" | "opus"; sample_rate?: number; volume?: number; rate?: number; pitch?: number; seed?: number; language_hints?: string[]; instruction?: string; enable_ssml?: boolean; }; } interface DashScopeTTSResponse { output: { audio: { url: string; expires_at?: string; }; finish_reason?: string; }; usage?: Record; request_id: string; } interface DashScopeTTSStreamChunk { output: { audio: { data?: string; url?: string; expires_at?: string; }; finish_reason?: string; }; usage?: Record; request_id?: string; } /** Context-enhancement message for async ASR `input.context` / sync Flash `input.messages`. */ interface AsrContextMessage { role: "user" | "assistant"; content: Array<{ type: "input_text" | "text"; text: string; }>; } interface DashScopeASRRequest { model: string; input: { file_urls?: string[]; file_url?: string; /** Context enhancement for async filetrans (array of chat-style messages). */ context?: AsrContextMessage[]; }; parameters?: { channel_id?: number[]; /** Classic async models (fun-asr / paraformer / qwen-audio filetrans, etc.) */ language_hints?: string[]; /** qwen3-asr-flash-filetrans* uses singular `language` */ language?: string; diarization_enabled?: boolean; speaker_count?: number; vocabulary_id?: string; /** Instant hot words (word → weight); takes effect on Qwen-Audio-3.0-ASR-Flash series. */ vocabulary?: Record; }; } interface DashScopeASRTranscriptionItem { file_url?: string; transcription_url?: string; subtask_status?: string; code?: string; message?: string; } interface DashScopeASRTaskResult { output: { task_id: string; task_status: "PENDING" | "RUNNING" | "SUCCEEDED" | "FAILED" | "UNKNOWN"; /** Multi-file async results (fun-asr / paraformer / qwen-audio filetrans, etc.) */ results?: DashScopeASRTranscriptionItem[]; /** Singular result returned by qwen3-asr-flash-filetrans* on success */ result?: { transcription_url?: string; }; task_metrics?: { TOTAL: number; SUCCEEDED: number; FAILED: number; }; code?: string; message?: string; }; usage?: Record; request_id: string; } interface DashScopeAsyncResponse { output: { task_id: string; task_status: string; }; request_id: string; } interface DashScopeTaskResponse { output: { task_id: string; task_status: "PENDING" | "RUNNING" | "SUCCEEDED" | "FAILED" | "UNKNOWN"; finished?: boolean; task_metrics?: { TOTAL?: number; SUCCEEDED?: number; FAILED?: number; }; choices?: Array<{ finish_reason: string; message: { role: "assistant"; content: Array<{ image: string; type: "image"; }>; }; }>; results?: Array<{ url: string; }>; video_url?: string; submit_time?: string; scheduled_time?: string; end_time?: string; code?: string; message?: string; }; usage?: Record; request_id: string; } //#endregion //#region src/types/knowledge-admin.d.ts /** Common response envelope for the indices domain (top-level fields are snake_case) */ interface RagResponse { code?: string; message?: string; status_code?: number; request_id?: string; data: T; [key: string]: unknown; } /** GET index/list row (fields inside rows are camelCase as-is; full config field set) */ interface RagIndexRow { id: string; name: string; description?: string; dataType?: string; embeddingModelName?: string; embeddingDimension?: number; chunkSize?: number; overlapSize?: number; chunkMode?: string; separator?: string; rerankModelName?: string; rerankMinScore?: number; rerankTopN?: number; rerankMode?: string; enableRewrite?: boolean; denseSimilarityTopK?: number; sparseSimilarityTopK?: number; sourceType?: string; connectorId?: string; [key: string]: unknown; } interface RagIndexListData { rows?: RagIndexRow[]; total?: number; [key: string]: unknown; } type RagIndexListResponse = RagResponse; /** GET index/files document row */ interface RagIndexFileRow { doc_id?: string; doc_name?: string; doc_type?: string; status?: string; size?: number | string; ingestion_id?: string; [key: string]: unknown; } interface RagIndexFilesData { rows?: RagIndexFileRow[]; total_count?: number; [key: string]: unknown; } type RagIndexFilesResponse = RagResponse; /** * GET index_job/status (verified against the live API) * Gotcha: the overall job state lives in `ingestion_status` (PENDING/RUNNING/COMPLETED, * no FAILED value); the per-document list is `rows[]` (not docs[]), and failures * surface via `rows[].code` (e.g. PARSE_FAILED). */ interface RagIndexJobDoc { doc_id?: string; doc_name?: string; doc_type?: string; /** Fine-grained processing status code: FINISH / PARSE_FAILED / ... */ code?: string; status?: string; message?: string; size?: number | string; ingestion_id?: string; [key: string]: unknown; } interface RagIndexJobStatusData { /** Overall job state: PENDING / RUNNING / COMPLETED */ ingestion_status?: string; ingestion_message?: string; rows?: RagIndexJobDoc[]; total_count?: number; [key: string]: unknown; } type RagIndexJobStatusResponse = RagResponse; /** Common response envelope for the connector domain (top-level requestId is camelCase — unlike the indices domain) */ interface RagConnectorResponse { code?: string; message?: string; requestId?: string; success?: boolean; status?: number | string; data: T; [key: string]: unknown; } /** POST applyFileUploadLease */ interface RagUploadLeaseParam { url?: string; method?: string; headers?: Record; [key: string]: unknown; } interface RagUploadLeaseData { type?: string; leaseId?: string; param?: RagUploadLeaseParam; [key: string]: unknown; } type RagUploadLeaseResponse = RagConnectorResponse; /** POST addFile */ interface RagAddFileData { fileId?: string; parser?: string; [key: string]: unknown; } type RagAddFileResponse = RagConnectorResponse; /** POST listCategory */ interface RagCategory { categoryId?: string; categoryName?: string; isDefault?: boolean; [key: string]: unknown; } interface RagListCategoryData { categoryList?: RagCategory[]; nextToken?: string; [key: string]: unknown; } type RagListCategoryResponse = RagConnectorResponse; /** POST index/job/create (incremental import; response field names pending live verification) */ interface RagJobCreateData { ingestionId?: string; [key: string]: unknown; } type RagJobCreateResponse = RagResponse; /** POST index/create_v2 */ interface RagCreateIndexV2Data { pipelineId?: string; ingestionId?: string; status?: string; [key: string]: unknown; } type RagCreateIndexV2Response = RagResponse; /** POST index/update and index/delete — data carries no details (empty object or absent) */ type RagMutationResponse = RagResponse | undefined>; /** POST index/delete_file — data.deleted lists the document IDs actually deleted */ interface RagDeleteFileData { deleted?: string[]; [key: string]: unknown; } type RagDeleteFileResponse = RagResponse; /** POST batchUpdateFileTag — connector-domain envelope, data is an empty object */ type RagBatchUpdateTagResponse = RagConnectorResponse | undefined>; /** agent_config — chat and search scenes carry different field sets; modeled loosely as one type */ interface RagAgentConfig { agent_policy?: string; agent_model?: string; enable_session_file?: string; enable_refusal?: string; enable_anti_leak?: string; enable_rich_text?: string; enable_citation?: string; temperature?: number; max_num_llm_calls?: number; max_completion_tokens?: number; session_file_max_parse_length?: number; enable_kb_router?: string; kb_router_model?: string; user_system_prompt?: string; anti_leak_prompt?: string; refusal_prompt?: string; credibility_prompt?: string; enable_thinking?: boolean; enable_temperature?: boolean; enable_credibility?: boolean; enable_max_completion_tokens?: boolean; session_file_parse_mode?: string; rerank_top_n?: number; hybrid_rerank?: Record; kb_search_configs?: Array>; [key: string]: unknown; } /** agent/list row */ interface RagAgentRow { agent_id?: string; agent_name?: string; agent_scene?: string; agent_status?: string; agent_version?: string; create_time?: string | number; modify_time?: string | number; pipeline_list?: Array<{ pipeline_id?: string; pipeline_name?: string; }>; [key: string]: unknown; } interface RagAgentListData { page_number?: number; page_size?: number; total_count?: number; rows?: RagAgentRow[]; [key: string]: unknown; } type RagAgentListResponse = RagResponse; /** agent/get per-version detail */ interface RagAgentDetail { agent_version?: string; agent_version_desc?: string | null; publish_time?: string | number; agent_config?: RagAgentConfig; [key: string]: unknown; } interface RagAgentGetData { agent_id?: string; agent_name?: string; agent_desc?: string; agent_scene?: string; agent_status?: string; create_time?: string | number; modify_time?: string | number; agent_details?: RagAgentDetail[]; [key: string]: unknown; } type RagAgentGetResponse = RagResponse; /** agent/create · update · deploy · delete · copy — union of the data field sets */ interface RagAgentMutationData { agent_id?: string; agent_name?: string; agent_version?: string; agent_status?: string; [key: string]: unknown; } type RagAgentMutationResponse = RagResponse; /** POST index/chunklist — nodes[].metadata carries the chunk payload */ interface RagChunkNodeMetadata { _id?: string; doc_id?: string; doc_name?: string; title?: string; content?: string; hier_title?: string; is_displayed_chunk_content?: boolean; _chunk_status_message?: string; [key: string]: unknown; } interface RagChunkNode { score?: number; text?: string; metadata?: RagChunkNodeMetadata; [key: string]: unknown; } interface RagChunkListData { total?: number; nodes?: RagChunkNode[]; [key: string]: unknown; } type RagChunkListResponse = RagResponse; /** POST index/monitor — timestamps are second-precision strings. * Shape verified against the live API: both monitor fields are objects, * not arrays as the public docs' empty-array examples suggest. */ interface RagStorageMonitorData { indexStorageLimit?: number; indexStorageUsage?: number; [key: string]: unknown; } interface RagQpsMonitorData { peakQps?: number; monitorData?: Array>; [key: string]: unknown; } interface RagMonitorData { pipelineCommercialType?: string; storageMonitorData?: RagStorageMonitorData; qpsMonitorData?: RagQpsMonitorData; [key: string]: unknown; } type RagMonitorResponse = RagResponse; /** POST addCategory */ interface RagAddCategoryData { categoryId?: string; [key: string]: unknown; } type RagAddCategoryResponse = RagConnectorResponse; /** POST listFile / describeFile — field names verified against the live API: * sizeBytes/uploadTime/category (not sizeInBytes/createTime/categoryId as the public docs state) */ interface RagDataCenterFile { fileId?: string; fileName?: string; fileType?: string; parser?: string; sizeBytes?: number | string; md5?: string; status?: string; tags?: string[] | string; category?: string; uploadTime?: string; parseErrorMessage?: string; [key: string]: unknown; } interface RagListFileData { fileList?: RagDataCenterFile[]; nextToken?: string; hasNext?: boolean; [key: string]: unknown; } type RagListFileResponse = RagConnectorResponse; type RagDescribeFileResponse = RagConnectorResponse; /** POST addConnector response / getConnector response — server does NOT echo fileConnectorConfig (live-verified) */ interface RagConnectorInfo { connectorId?: string; connectorName?: string; description?: string; connectorType?: string; [key: string]: unknown; } type RagAddConnectorResponse = RagConnectorResponse; type RagGetConnectorResponse = RagConnectorResponse; /** POST addFilesFromAuthorizedOss — live shape is addFileResultList (the docs' fileIds is not returned) */ interface RagOssImportFileResult { fileId?: string; ossKey?: string; status?: string; msg?: string; [key: string]: unknown; } interface RagOssImportData { addFileResultList?: RagOssImportFileResult[]; [key: string]: unknown; } type RagOssImportResponse = RagConnectorResponse; //#endregion //#region src/config/schema.d.ts export declare const REGIONS: { readonly cn: "https://dashscope.aliyuncs.com"; readonly us: "https://dashscope-us.aliyuncs.com"; readonly intl: "https://dashscope-intl.aliyuncs.com"; }; export declare const DOCS_HOSTS: { readonly cn: "https://help.aliyun.com/zh/model-studio"; readonly us: "https://help.aliyun.com/zh/model-studio"; readonly intl: "https://help.aliyun.com/zh/model-studio"; }; export declare const BAILIAN_HOST = "https://bailian.cn-beijing.aliyuncs.com"; type Region = keyof typeof REGIONS; export declare const SUPPORTED_LANGUAGES: readonly ["en-US", "zh-CN"]; type Language = (typeof SUPPORTED_LANGUAGES)[number]; export declare const DEFAULT_LANGUAGE: Language; interface ConfigFile { language?: Language; api_key?: string; /** OAuth-style token from `bl auth login --console` callback; sent as `Authorization: Bearer …` */ access_token?: string; /** Alibaba Cloud OpenAPI AccessKey ID from `bl auth login --open-api`. */ access_key_id?: string; /** Alibaba Cloud OpenAPI AccessKey secret from `bl auth login --open-api`. */ access_key_secret?: string; /** Alibaba Cloud STS Security Token (optional, for temporary credentials). */ security_token?: string; base_url?: string; output?: "text" | "json"; output_dir?: string; timeout?: number; watermark?: boolean; default_text_model?: string; default_video_model?: string; default_image_to_video_model?: string; default_reference_to_video_model?: string; default_image_model?: string; default_speech_model?: string; default_speech_recognition_model?: string; default_omni_model?: string; /** Leaf API-key capabilities this named Profile endpoint can serve. */ api_key_capabilities?: string[]; workspace_id?: string; console_site?: "domestic" | "international"; console_region?: string; console_switch_agent?: number; telemetry?: boolean; } export declare const CONFIG_FILE_KEYS: readonly ["language", "api_key", "access_token", "access_key_id", "access_key_secret", "security_token", "base_url", "output", "output_dir", "timeout", "watermark", "default_text_model", "default_video_model", "default_image_to_video_model", "default_reference_to_video_model", "default_image_model", "default_speech_model", "default_speech_recognition_model", "default_omni_model", "api_key_capabilities", "workspace_id", "console_site", "console_region", "console_switch_agent", "telemetry"]; export declare const API_KEY_CAPABILITY_PATTERN: RegExp; export declare function isApiKeyCapability(value: string): boolean; /** * Normalize a persisted capability allowlist. Absence keeps the policy disabled; * a present malformed value fails closed to an empty allowlist. */ export declare function normalizeApiKeyCapabilities(value: unknown): string[] | undefined; export declare function parseConfigFile(raw: unknown): ConfigFile; /** 静态产品身份,createCli 注入一次(bl/rag 各异,故注入而非模块常量)。 */ interface Identity { /** Product binary name, e.g. "bl", "rag". */ binName: string; version: string; /** npm package name for self-update, e.g. "bailian-cli". */ npmPackage: string; /** User-Agent / telemetry client name. */ clientName: string; } /** * 命令唯一会读的配置面(flag/env/file 解析后的有效值)。 * 不含身份(Identity)、不含秘密(credential);console 三元组为 dry-run 展示保留, * 真实调用走 ConsoleCredential(同链解析,受控重叠)。 */ interface Settings { configPath?: string; configName?: string; output: "text" | "json"; /** * Whether `output` came from an explicit source (flag/env/file) rather than * the default. Commands whose default format differs from the global default * (e.g. `advisor recommend` defaults to json) branch on this. */ outputExplicit: boolean; outputDir?: string; timeout: number; watermark: boolean; defaultTextModel?: string; defaultVideoModel?: string; defaultImageToVideoModel?: string; defaultReferenceToVideoModel?: string; defaultImageModel?: string; defaultSpeechModel?: string; defaultSpeechRecognitionModel?: string; defaultOmniModel?: string; workspaceId?: string; consoleRegion?: string; consoleSite?: "domestic" | "international"; consoleSwitchAgent?: number; verbose: boolean; quiet: boolean; dryRun: boolean; telemetry: boolean; } //#endregion //#region src/config/store.d.ts /** * config 命令族的持久化能力面(lint 限定 commands/config/** 使用)。 * 读写都直达磁盘(非 dispatch 时的快照),与现有 config set/show 的行为一致。 */ interface ConfigStore { read(): ConfigFile; /** 合并写入;patch 里值为 undefined 的键会被删除。 */ write(patch: Partial): Promise; /** 删除指定键。 */ unset(keys: (keyof ConfigFile)[]): Promise; /** 读取所有 Profile 与持久化激活项。 */ profiles(): ConfigProfiles; /** 激活已存在的命名 Profile;undefined/default 激活顶层配置。 */ activate(name?: unknown): Promise; /** 校验激活目标并返回规范化展示名,不落盘。 */ validateActivation(name?: unknown): string; path: string; } export declare function makeConfigStore(configName?: string): ConfigStore; //#endregion //#region src/auth/types.d.ts /** Where a resolved credential came from (shown by `bl auth status`). */ type CredentialSource = "flag" | "env" | "config"; /** Credential for the **model domain** (DashScope data plane). Always an API key. */ interface ApiKeyCredential { token: string; /** Base URL to send this key's requests to. */ baseUrl: string; source: CredentialSource; } /** Credential for the **console domain** (Bailian console gateway). An access token + region/site. */ interface ConsoleCredential { token: string; region: string; site: "domestic" | "international"; switchAgent?: number; source: CredentialSource; } /** Credential for Alibaba Cloud OpenAPI calls signed with AK/SK. */ interface OpenApiCredential { accessKeyId: string; accessKeySecret: string; securityToken?: string; source: CredentialSource; } /** Full auth snapshot for display (`bl auth status`) — what would resolve per domain. */ interface AuthState { apiKey?: ApiKeyCredential; console?: ConsoleCredential; openapi?: OpenApiCredential; } //#endregion //#region src/auth/store.d.ts /** 登录允许落盘的键:凭证本体 + 登录回调携带的连接/作用域字段。 */ type AuthPersistPatch = Pick; /** * auth 命令族的凭证能力面(lint 限定 commands/auth/** 使用)。 * 登录产生的全部落盘走 login,不放宽 configStore 的边界。 */ interface AuthStore { /** 各域"将会解析出"的凭证快照(auth status 用)。 */ describe(): AuthState; /** 磁盘上当前是否存有各域凭证,以及 model baseUrl/capability 配置(只看 file,不含 flag/env 源)。 */ stored(): { apiKey: boolean; console: boolean; openapi: boolean; baseUrl?: string; apiKeyCapabilities?: string[]; }; /** model 域 baseUrl 链(flag > env > config file > fallback)。 */ resolveBaseUrl(fallback?: string): string; /** 登录落盘:合并写入,undefined 键忽略;显式 --config 成功后同时激活目标 Profile。 */ login(patch: AuthPersistPatch): Promise; /** 清凭证:console/openapi 只删对应域;all 清全部登录凭证和 model baseUrl。返回是否有变更。 */ logout(scope: "console" | "openapi" | "all"): Promise; /** 实际写入的 config.json 路径(不受命名配置影响,一直是同一个文件)。 */ path: string; } export declare function makeAuthStore(sources: ResolutionSources): AuthStore; //#endregion //#region src/client/http.d.ts /** 传输层依赖:UA 用 identity,timeout/verbose 用 settings。凭证由调用方(Client)注头。 */ interface HttpDeps { identity: Identity; settings: Settings; } interface RequestOpts { url: string; method?: string; body?: unknown; headers?: Record; timeout?: number; stream?: boolean; async?: boolean; signal?: AbortSignal; } export declare function request(deps: HttpDeps, opts: RequestOpts): Promise; export declare function requestJson(deps: HttpDeps, opts: RequestOpts): Promise; //#endregion //#region src/client/acs.d.ts type AcsQueryParams = Record; interface AcsSignConfig { accessKeyId: string; accessKeySecret: string; securityToken?: string; action: string; version: string; body: string; host: string; pathname: string; method?: string; /** ACS3 canonical query string (sorted, encoded, no leading `?`). */ queryString?: string; } /** Build ACS3 canonical query string from OpenAPI query parameters. */ export declare function buildAcsCanonicalQuery(params: AcsQueryParams): string; export declare function signAcsRequest(cfg: AcsSignConfig): Record; //#endregion //#region src/client/mcp.d.ts interface McpTool { name: string; description?: string; inputSchema?: Record; } interface McpToolResult { content: Array<{ type: string; text?: string; data?: string; mimeType?: string; }>; isError?: boolean; } /** * Compose the streamable-HTTP MCP endpoint for a Bailian MCP server. * The path is `/api/v1/mcps//mcp`; the `serverCode` is taken * verbatim from `bl mcp list` (e.g. `WebSearch`, `market-cmapi00073529`). */ export declare function bailianMcpPath(serverCode: string): string; /** Classic SSE path: `/api/v1/mcps//sse`. */ export declare function bailianMcpSsePath(serverCode: string): string; /** * True when Streamable HTTP is unsupported and classic SSE fallback should be tried. * Anchored to HTTP wrapper text only (not JSON-RPC / nested copies). Bailian 404 excluded. */ export declare function isStreamableHttpUnsupported(error: unknown): boolean; /** * SSE fallback for `--url` (official backwards-compat: same URL, HTTP 405/404 then GET SSE). */ export declare function isUrlOverrideSseFallbackCandidate(error: unknown): boolean; type McpConnectedClient = { initialize(): Promise; listTools(): Promise; callTool(name: string, args: Record): Promise; close?(): void; }; type ConnectBailianMcpOptions = { deps: HttpDeps; authToken: string | undefined; /** Full Streamable HTTP URL (/mcp). */ httpUrl: string; /** Full classic SSE URL (/sse). */ sseUrl: string; serverCode: string; /** * Explicit `--url` override: try Streamable on that URL first; * on 405/404 fall back to classic SSE on the same URL. */ urlOverride?: string; }; /** * Connect via Streamable HTTP first; on 405 (except WebSearch), fall back to SSE. * `--url` uses the same URL for Streamable then classic SSE (official backwards-compat). * For WebSearch, rethrow the original error so commands can attach a re-activate hint. */ export declare function connectBailianMcpWithFallback(options: ConnectBailianMcpOptions): Promise<{ client: McpConnectedClient; url: string; }>; export declare class McpClient { private url; private sessionId; private nextId; private deps; private authToken; constructor(deps: HttpDeps, url: string, authToken?: string); /** Initialize the MCP session. Must be called before any other method. */ initialize(): Promise; listTools(): Promise; callTool(name: string, args: Record): Promise; private rpc; private notify; /** * Read a JSON-RPC response by Content-Type: application/json or text/event-stream. */ private readJsonRpcResponse; private readJsonRpcFromSse; private send; } //#endregion //#region src/client/client.d.ts /** Client 的结构化依赖:身份 + 有效配置 + 各域凭证(按命令的 auth 注入)。 */ interface ClientDeps { identity: Identity; settings: Settings; /** Model 域 base URL(凭证无关链解析,resolveModelBaseUrl;有 apiCred 时两者一致)。 */ baseUrl: string; /** True only when the shared URL chain used its default; explicit origins win over service defaults. */ baseUrlIsDefault?: boolean; apiCred?: ApiKeyCredential; consoleCred?: ConsoleCredential; openApiCred?: OpenApiCredential; } /** Like {@link RequestOpts} but with a `path` (credential baseUrl prepended) or an absolute URL. */ interface ClientRequestOpts extends Omit { path: string; } interface ClientOpenApiQueryOpts { host: string; path: string; action: string; version: string; method: "GET" | "POST"; queryParams: AcsQueryParams; } interface ClientOpenApiJsonOpts { host: string; path: string; action: string; version: string; method: "GET" | "POST"; /** JSON request body; omit for query-only calls (signed as an empty body). */ body?: unknown; queryParams?: AcsQueryParams; } interface OpenApiResponse { Success?: boolean; Code?: string; Message?: string; } /** * A command's network surface: call its methods to reach the API — the * credential and base URL are already baked in, so commands never handle tokens * or baseUrl. Model methods (`request`/`requestJson`/`mcp`) need an api key; * `uploadFile` only needs one for local files, and passes URLs through without * credentials. `console` needs a console token; calling one without its * credential throws. */ export declare class Client { private readonly deps; constructor(deps: ClientDeps); private get http(); private requireApi; private requireOpenApi; /** Model-domain base URL. Readable without a key (e.g. dry-run preview); real requests still need one. */ get baseUrl(): string; /** * Export the model-domain credential for delegation to an embedded SDK that * owns its own transport (e.g. @openagentpack/sdk). Deliberate escape hatch: * regular commands keep calling {@link request}/{@link requestJson} and never * handle tokens; only trusted internal adapters such as managed-agent/_engine * and the Command Pack host use this export. Undefined when no credential * resolved (authStage tolerates that only under dry-run). */ exportApiCredential(): ApiKeyCredential | undefined; /** * Headers for registering a Bailian MCP endpoint in an external Agent. * Credential resolution and channel attribution remain owned by the client. */ bailianMcpRegistrationHeaders(): Record; /** * Full URL for a model-domain path. Services may supply a lazy default origin, * evaluated only when no flag/env/profile base URL was configured. */ url(path: string, defaultBaseUrl?: () => string): string; private toOpts; request(opts: ClientRequestOpts): Promise; requestJson(opts: ClientRequestOpts): Promise; /** Resolve a file arg: upload a local path to OSS (returns oss:// URL), or pass a URL through. */ uploadFile(source: string, model: string, opts?: { signal?: AbortSignal; }): Promise; /** * Resolve an image input while keeping Token Plan's upload limitation isolated. * Token Plan local images are sent as Data URIs; every other connection keeps * the established temporary OSS upload flow. URLs and existing Data URIs pass through. */ resolveImageInput(source: string, model: string, opts?: { signal?: AbortSignal; }): Promise; usesTokenPlanEndpoint(): boolean; /** Open an MCP client. Accepts a path (prepended with the model baseUrl) or an absolute URL. */ mcp(pathOrUrl: string): McpClient; /** * Connect to a Bailian MCP: try Streamable HTTP, then SSE on 405 (except WebSearch). * `urlOverride` maps to `--url`: Streamable first, then classic SSE on the same URL (405/404). */ connectBailianMcp(serverCode: string, urlOverride?: string): Promise<{ client: McpConnectedClient; url: string; }>; console(api: string, data: Record): Promise; openApiQueryJson(opts: ClientOpenApiQueryOpts): Promise; openApiJson(opts: ClientOpenApiJsonOpts): Promise; } //#endregion //#region src/types/command-pack-manager.d.ts interface CommandPackMutationResult { name: string; version?: string; commands: string[]; } interface CommandPackReport { name: string; version?: string; source: "installed" | "linked"; status: "loaded" | "failed"; commands: string[]; error?: string; } /** Product-bound Command Pack management surface injected by the CLI runtime. */ interface CommandPackManager { install(spec: string): Promise; link(path: string): Promise; list(): Promise; remove(name: string): Promise; } //#endregion //#region src/types/command.d.ts type LocalizedText = string | { readonly "en-US": string; readonly "zh-CN": string; }; /** A presence flag: `--quiet`. No value; absent → false. */ interface SwitchFlag { type: "switch"; description: LocalizedText; } /** A value flag: `--prompt `, `--n `, `--watermark true|false`. */ interface ValueFlag { type: "string" | "number" | "boolean" | "array"; description: LocalizedText; valueHint: string; required?: boolean; /** * Restrict to a fixed set of values. The parser rejects anything else and the * parsed type narrows to the union. Declare with `as const` so the literals * survive inference: `choices: ["mp3", "wav"] as const`. */ choices?: readonly string[]; } type FlagDef = SwitchFlag | ValueFlag; type FlagsDef = Record; type ParsedValue = F extends SwitchFlag ? boolean : F extends { type: "number"; } ? number : F extends { type: "boolean"; } ? boolean : F extends { choices: readonly (infer C extends string)[]; } ? F extends { type: "array"; } ? C[] : C : F extends { type: "array"; } ? string[] : string; /** Switches and `required` value flags are present; other value flags optional. */ type IsRequired = F extends SwitchFlag ? true : F extends { required: true; } ? true : false; /** * Map a FlagsDef to the parsed flags object type. Required flags (switches + * `required: true`) are required properties; optional value flags are `?`. */ type ParsedFlags = { [K in keyof F as IsRequired extends true ? K : never]: ParsedValue; } & { [K in keyof F as IsRequired extends true ? never : K]?: ParsedValue; }; type AuthRequirement = "apiKey" | "console" | "openapi" | "none"; /** 所有命令都可用的全局 flag。 */ export declare const GLOBAL_FLAGS: { output: { type: "string"; valueHint: string; description: { "en-US": string; "zh-CN": string; }; }; timeout: { type: "number"; valueHint: string; description: { "en-US": string; "zh-CN": string; }; }; quiet: { type: "switch"; description: { "en-US": string; "zh-CN": string; }; }; verbose: { type: "switch"; description: { "en-US": string; "zh-CN": string; }; }; dryRun: { type: "switch"; description: { "en-US": string; "zh-CN": string; }; }; config: { type: "string"; valueHint: string; description: { "en-US": string; "zh-CN": string; }; }; help: { type: "switch"; description: { "en-US": string; "zh-CN": string; }; }; version: { type: "switch"; description: { "en-US": string; "zh-CN": string; }; }; }; /** Command-scoped flag for commands that support parallel API calls. */ export declare const CONCURRENT_FLAG: { concurrent: { type: "number"; valueHint: string; description: { "en-US": string; "zh-CN": string; }; }; }; /** Command-scoped flag for task-based commands that can return without polling. */ export declare const ASYNC_FLAG: { async: { type: "switch"; description: { "en-US": string; "zh-CN": string; }; }; }; /** Model 域凭证/连接 flag,`auth: "apiKey"` 命令可见。 */ export declare const MODEL_AUTH_FLAGS: { apiKey: { type: "string"; valueHint: string; description: { "en-US": string; "zh-CN": string; }; }; baseUrl: { type: "string"; valueHint: string; description: { "en-US": string; "zh-CN": string; }; }; }; /** Console 域目标/作用域 flag,`auth: "console"` 命令可见。 */ export declare const CONSOLE_AUTH_FLAGS: { consoleRegion: { type: "string"; valueHint: string; description: { "en-US": string; "zh-CN": string; }; }; consoleSite: { type: "string"; valueHint: string; description: { "en-US": string; "zh-CN": string; }; }; consoleSwitchAgent: { type: "number"; valueHint: string; description: { "en-US": string; "zh-CN": string; }; }; workspaceId: { type: "string"; valueHint: string; description: { "en-US": string; "zh-CN": string; }; }; }; /** Alibaba Cloud OpenAPI AK/SK credential flags, visible to `auth: "openapi"` commands. */ export declare const OPENAPI_AUTH_FLAGS: { accessKeyId: { type: "string"; valueHint: string; description: { "en-US": string; "zh-CN": string; }; }; accessKeySecret: { type: "string"; valueHint: string; description: { "en-US": string; "zh-CN": string; }; }; securityToken: { type: "string"; valueHint: string; description: { "en-US": string; "zh-CN": string; }; }; }; /** sources 里可能出现的全部 flag(全局 + 凭证域)。 */ type SourceFlags = ParsedFlags; /** 该命令可见的凭证域 flag 定义。 */ export declare function credentialFlagDefs(cmd: { auth: AuthRequirement; }): FlagsDef; /** * What a command's `run` receives: `client` for all network calls (its * credential is already injected per the command's `auth`), `settings` for the * resolved configuration surface, `identity` for product identity, and `flags` * for parsed arguments. Never handle tokens or baseUrl. */ interface CommandContext { /** 静态产品身份(binName/version/npmPackage/clientName)。 */ identity: Identity; /** * Locale selector for user-facing output: picks the `en-US` / `zh-CN` variant * of a {@link LocalizedText} per the resolved language. Supplied by the runtime * (RunContext.localize). Commands use it to localize what they *print*; the * localized command metadata (description/flags/notes) is rendered by the * runtime's help output and does not need this. */ localize: (text: LocalizedText) => string; /** flag/env/file 解析后的有效配置面。 */ settings: Settings; /** 只含本命令声明的 flag;全局 flag 经 settings 读。 */ flags: ParsedFlags; /** Network surface; the credential for the command's `auth` is pre-injected. */ client: Client; /** 配置持久化能力;lint 限定 commands/config/** 使用。 */ configStore: ConfigStore; /** 鉴权持久化能力;lint 限定 commands/auth/** 使用。 */ authStore: AuthStore; /** Command Pack 管理能力;lint 限定 commands/plugin/** 使用。 */ commandPacks: CommandPackManager; } /** * A command. Generic over its flags `F` so `run`/`validate` receive precisely * typed flags (`ParsedFlags` = 命令自有 flag). Stored heterogeneously as * {@link AnyCommand}; the precise typing lives at the `defineCommand` call site. */ type CommandRiskLevel = "high"; interface CommandRisk { level: CommandRiskLevel; message: LocalizedText; } interface Command { description: LocalizedText; /** Credential this command requires. See {@link AuthRequirement}. */ auth: AuthRequirement; /** * Runtime-classified operation risk and its user-facing consequence message. * Omit for normal commands. * High-risk commands must return from `run` on `settings.dryRun` before any * remote request or local write; runtime only owns the confirmation gate. */ risk?: CommandRisk; /** Usage line arg portion, e.g. "--prompt [flags]". Manually written. */ usageArgs?: string; /** Example args (without the ` ` prefix). */ exampleArgs?: LocalizedText[]; /** Additional help paragraphs rendered below flags. */ notes?: LocalizedText[]; flags?: F; /** * Cross-flag validation, after parsing and before run. Return an error message * → UsageError; undefined to pass. Single-flag `required` is enforced by the * parser — use this for rules spanning flags or depending on a flag's *value*. * May be async for read-only local preflight. Runtime awaits it before auth * and confirmation. Do not perform remote requests or local writes here. */ validate?: (flags: ParsedFlags) => string | undefined | Promise; run: (ctx: CommandContext) => Promise; } /** Type-erased command for heterogeneous storage (registry / context). */ type AnyCommand = Command; /** Identity wrapper whose only job is to infer `F` from `spec.flags`. */ export declare function defineCommand(spec: Command): Command; //#endregion //#region src/config/loader.d.ts /** * 校验并规范化 `--config `:`undefined`/""/"default" 都视为未指定(等价顶层默认配置)。 * 合法命名只允许字母、数字、`-`/`_`,且不能与 `ConfigFile` 顶层字段同名(避免写入时与默认配置字段歧义)。 */ export declare function normalizeConfigName(name?: unknown): string | undefined; export declare function readConfigFile(configName?: string): ConfigFile; /** 写入所选 Profile;登录流程可在同一次原子写入中将显式 Profile 设为激活项。 */ export declare function writeConfigFile(data: Record, configName?: string, options?: { activate?: boolean; }): Promise; /** 全量配置快照:顶层默认配置 + 各命名 profile。 */ interface ConfigProfiles { /** 顶层默认配置(parseConfigFile 过滤后)。 */ default: ConfigFile; /** 命名配置 name -> 配置。 */ named: Record; /** 当前持久化激活项;default 表示顶层配置。 */ active: string; } /** * 读取全部 profile:顶层默认配置与各命名 block。 * 命名 block = raw 中不属于 `CONFIG_FILE_KEYS`、且值为普通对象的项。 */ export declare function readConfigProfiles(): ConfigProfiles; /** 校验激活目标并返回规范化展示名;不写配置。 */ export declare function validateConfigProfileActivation(name?: unknown): string; /** 将已存在的命名 Profile(或 default)设为持久化激活项。 */ export declare function activateConfigProfile(name?: unknown): Promise; /** 删除一个命名 profile block;存在才删并回写,返回是否有变更。 */ export declare function deleteConfigProfile(name?: unknown): Promise; /** * 解析的三个来源,dispatch 边界一次构建。flags 收 Partial:ParsedFlags 里 switch 是 * 必填 boolean,收 Partial 让 pipeline 等无 flag 场景传 {} 即可。 */ interface ResolutionSources { flags: Partial; file: ConfigFile; env: NodeJS.ProcessEnv; /** 当前命名配置名(`--config ` 解析后);未指定或 `default` 时为 undefined。 */ configName?: string; /** 实际 config.json 路径(不受 configName 影响,一直是同一个文件)。 */ configPath?: string; } interface ApiKeyResolutionSourceSelection { sources: ResolutionSources; /** Named Profile whose file-backed API credential was replaced by default. */ fallbackFrom?: string; } /** * Select the file-backed API-key source for a command capability. Only a * persisted Profile capability list enables fallback. An explicit flag or * environment API connection override bypasses it entirely. */ export declare function selectApiKeyResolutionSources(sources: ResolutionSources, capability: string): ApiKeyResolutionSourceSelection; export declare function buildSources(flags: Partial): ResolutionSources; /** * 纯解析 sources → Settings(命令唯一会读的配置面)。不含身份、baseUrl、鉴权。 * 各字段链序 flag > env > file > 默认;锁定表 tests/config-priority.test.ts。 */ export declare function buildSettings(s: ResolutionSources): Settings; //#endregion //#region src/auth/resolver.d.ts /** Preserve whether the shared base URL chain selected a configured origin or its default. */ export declare function resolveModelBaseUrlState(sources: ResolutionSources, fallback?: string): { baseUrl: string; baseUrlIsDefault: boolean; }; /** Model-domain baseUrl(flag > env > config file > fallback);无需 key 也可解析。 */ export declare function resolveModelBaseUrl(s: ResolutionSources, fallback?: string): string; /** * Model-domain credential from sources. Priority: `--api-key` flag > * `DASHSCOPE_API_KEY` env > config.json `api_key`. baseUrl: flag > env > file > cn. */ export declare function resolveApiKey(s: ResolutionSources): ApiKeyCredential; /** Console-domain credential from sources — access token + 连接目标(flag > file > 默认)。 */ export declare function resolveConsole(s: ResolutionSources): ConsoleCredential; /** Alibaba Cloud OpenAPI AK/SK credential. Priority: flags > env > config. */ export declare function resolveOpenApi(s: ResolutionSources): OpenApiCredential; /** Full auth snapshot from sources — what would resolve per domain (or undefined). */ export declare function describeAuthState(s: ResolutionSources): AuthState; //#endregion //#region src/auth/refresh-token.d.ts export declare function generateCLIAccessToken(opts: { identity: Identity; settings: Settings; baseUrl: string; accessKeyId: string; accessKeySecret: string; securityToken?: string; }): Promise; /** * Try to refresh the console access_token using stored AK/SK. * Returns the new token on success, or null if AK/SK are not available. */ export declare function refreshAccessToken(opts: { identity: Identity; settings: Settings; baseUrl: string; }): Promise; //#endregion //#region src/client/endpoints.d.ts export declare function chatPath(): string; export declare function responsesPath(): string; /** Async image API used by wan2.6-t2i / wan2.6-image (T2I) and similar message-format models. */ export declare function imagePath(): string; /** Sync multimodal API (qwen-image / wan2.7-image / z-image generate; also wan2.6-image edit). */ export declare function imageSyncPath(): string; /** Legacy async text-to-image API (wan2.5/2.2/2.1-t2i, wanx-*-t2i). */ export declare function imageText2ImagePath(): string; /** Legacy async image-to-image / edit API (wan2.5-i2i, *imageedit*). */ export declare function image2ImagePath(): string; export declare function videoGeneratePath(): string; /** POST /api/v1/services/aigc/image2video/video-synthesis — kf2v (first+last frame). */ export declare function image2videoPath(): string; export declare function taskPath(taskId: string): string; export declare function modelsLimitsPath(): string; export declare function modelsPermissionsPath(): string; export declare function appCompletionPath(appId: string): string; export declare function memoryAddPath(): string; export declare function memorySearchPath(): string; export declare function memoryListPath(): string; export declare function memoryNodePath(nodeId: string): string; export declare function speechSynthesizePath(): string; export declare function speechRecognizePath(): string; export declare function speechVocabularyPath(): string; export declare function profileSchemaPath(): string; export declare function userProfilePath(schemaId: string): string; export declare function knowledgeRetrievePath(): string; export declare function workspaceMaaSBaseUrl(workspaceId: string): string; export declare function knowledgeSearchEndpoint(workspaceId: string): string; export declare function knowledgeChatEndpoint(workspaceId: string): string; /** Per-workspace AgentStudio host (same shape as {@link ragEndpoint}'s host). */ export declare function agentStudioHost(workspaceId: string): string; /** GET protection overview — fixed to the last 24 hours, no request params. */ export declare function securityOverviewEndpoint(host: string): string; /** GET alert list (agent_logs); filters / pagination go in the query string. */ export declare function securityAgentLogsEndpoint(host: string): string; export declare function mcpWebSearchPath(): string; /** GET /api/v1/deployments/{deployed_model}/capacity-instances */ export declare function deploymentCapacityInstancesPath(code: string): string; /** GET /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id} */ export declare function deploymentCapacityInstancePath(code: string, id: string): string; /** PUT /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id}/scale */ export declare function deploymentCapacityInstanceScalePath(code: string, id: string): string; /** PUT /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id}/renew */ export declare function deploymentCapacityInstanceRenewPath(code: string, id: string): string; /** PUT /api/v1/deployments/{deployed_model}/update-overflowstrategy */ export declare function deploymentOverflowPath(code: string): string; /** GET /api/v1/deployments/{deployed_model}/capacity-operations/{operation_id} */ export declare function deploymentCapacityOperationPath(code: string, id: string): string; export declare function ragEndpoint(workspaceId: string, path: string): string; /** AgentStudio workspace files; template uploads send source=sandbox_template. */ export declare function agentStudioFilesPath(): string; /** Default Sandbox origin when no shared base URL was configured (cn-beijing only). */ export declare function sandboxBaseUrl(workspaceId: string): string; /** Sandbox service prefix, appended to the selected origin just like AgentStudio SDK paths. */ export declare function sandboxApiPath(path: string): string; /** Build the default workspace-scoped absolute Sandbox control-plane URL. */ export declare function sandboxEndpoint(workspaceId: string, path: string): string; export declare const SANDBOX_PATHS: { readonly sandboxes: "/sandboxes"; readonly sandboxList: "/v2/sandboxes"; readonly templates: "/templates"; readonly templateCreate: "/v3/templates"; readonly templateList: "/v2/templates"; }; export declare function sandboxInstancePath(sandboxId: string): string; export declare function sandboxInstanceActionPath(sandboxId: string, action: "connect" | "pause" | "resume"): string; export declare function sandboxTemplatePath(templateId: string): string; export declare function sandboxTemplateBuildStatusPath(templateId: string, buildId: string): string; export declare const RAG_PATHS: { readonly indexList: "/api/v1/indices/rag/index/list"; readonly indexCreateV2: "/api/v1/indices/rag/index/create_v2"; readonly indexUpdate: "/api/v1/indices/rag/index/update"; readonly indexDelete: "/api/v1/indices/rag/index/delete"; readonly indexMonitor: "/api/v1/indices/rag/index/monitor"; readonly indexFiles: "/api/v1/indices/rag/index/files"; readonly indexDeleteFile: "/api/v1/indices/rag/index/delete_file"; readonly indexJobCreate: "/api/v1/indices/rag/index/job/create"; readonly indexJobStatus: "/api/v1/indices/rag/index_job/status"; readonly chunkList: "/api/v1/indices/rag/index/chunklist"; readonly chunkCreate: "/api/v1/indices/rag/index/chunk/create"; readonly chunkUpdate: "/api/v1/indices/rag/index/chunk/update"; readonly chunkDelete: "/api/v1/indices/rag/index/chunk/delete"; readonly agentList: "/api/v1/indices/rag/app/list"; readonly agentGet: "/api/v1/indices/rag/app/get"; readonly agentCreate: "/api/v1/indices/rag/app/create"; readonly agentUpdate: "/api/v1/indices/rag/app/update"; readonly agentDeploy: "/api/v1/indices/rag/app/deploy"; readonly agentDelete: "/api/v1/indices/rag/app/delete"; readonly agentCopy: "/api/v1/indices/rag/app/copy"; readonly applyFileUploadLease: "/api/v1/connector/dash/applyFileUploadLease"; readonly addFile: "/api/v1/connector/dash/addFile"; readonly addFilesFromAuthorizedOss: "/api/v1/connector/dash/addFilesFromAuthorizedOss"; readonly batchUpdateFileTag: "/api/v1/connector/dash/batchUpdateFileTag"; readonly listFile: "/api/v1/connector/dash/listFile"; readonly describeFile: "/api/v1/connector/dash/describeFile"; readonly deleteFile: "/api/v1/connector/dash/deleteFile"; readonly addConnector: "/api/v1/connector/dash/addConnector"; readonly getConnector: "/api/v1/connector/dash/getConnector"; readonly listCategory: "/api/v1/connector/dash/listCategory"; readonly addCategory: "/api/v1/connector/dash/addCategory"; readonly deleteCategory: "/api/v1/connector/dash/deleteCategory"; }; //#endregion //#region src/client/image-routes.d.ts /** * DashScope image APIs differ by model family: * * Generate (T2I): * - sync multimodal + messages: qwen-image*, wan2.7-image*, z-image* * - async image-generation + messages: wan2.6-t2i*, wan2.6-image* * (wan2.6-image sync multimodal requires 1–4 images, so pure T2I must be async) * - async text2image + prompt: wan2.5/2.2/2.1-t2i*, wanx*-t2i* * * Edit (I2I): * - sync multimodal + messages(+images): qwen-image-3.0*, qwen-image-2.0*, qwen-image-edit*, wan2.6-image*, wan2.7-image* * (pure T2I models such as z-image / qwen-image-plus / qwen-image-max are NOT edit models) * - async image2image + prompt/images: wan2.5-i2i* * - async image2image + function/base_image_url: *imageedit* (e.g. wanx2.1-imageedit) * - async image-generation + messages(+images): other async fallbacks */ type ImageApiKind = "sync-multimodal" | "async-image-generation" | "async-text2image" | "async-image2image"; /** Model-family size presets — not inferred from sync/async. */ type ImageSizeProfile = "qwen-image-2.0" | "qwen-image-fixed" | "wan27" | "z-image" | "wan26" | "wan-legacy" | "wanx-v1" | "wan25-i2i"; type ImageInputStyle = "messages" | "prompt" | "prompt-images" | "function-base-image"; interface ImageApiRoute { kind: ImageApiKind; path: string; /** True when the call is synchronous (no X-DashScope-Async / task poll). */ useSync: boolean; /** How to shape `input` in the request body. */ inputStyle: ImageInputStyle; /** Ratio → pixel map family for `--size`. */ sizeProfile: ImageSizeProfile; /** * CLI default when `--prompt-extend` is omitted. * `undefined` means omit the parameter (leave to DashScope default). */ promptExtendDefault?: boolean; } /** True when the model family can use sync multimodal for generate. */ export declare function isSyncMultimodalImageModel(model: string): boolean; /** wan2.5 / wan2.2 / wan2.1 / wanx text-to-image models use the legacy prompt API. */ export declare function isLegacyText2ImageModel(model: string): boolean; /** wan2.5-i2i uses the legacy image2image prompt+images API. */ export declare function isLegacyImage2ImageModel(model: string): boolean; /** wanx*-imageedit uses function + base_image_url (not prompt+images). */ export declare function isWanxFunctionImageEditModel(model: string): boolean; export declare function resolveImageSizeProfile(model: string): ImageSizeProfile; /** Official / CLI defaults for prompt_extend when the flag is omitted. */ export declare function resolvePromptExtendDefault(model: string): boolean | undefined; export declare function resolveImageGenerateApi(model: string): ImageApiRoute; export declare function resolveImageEditApi(model: string): ImageApiRoute; //#endregion //#region src/client/asr-routes.d.ts /** * DashScope ASR APIs differ by model family: * * - async file transcription (`.../audio/asr/transcription`): * fun-asr*, paraformer* (non-realtime), *-filetrans, sensevoice* * language via `parameters.language_hints`; optional `input.context` / * `parameters.vocabulary` (model-dependent effective range) * - sync multimodal (`.../aigc/multimodal-generation/generation`): * - qwen3: `{ content: [{ audio }] }` + optional `asr_options.language` * (qwen3-asr-flash*) — no vocabulary / context fields in this body shape * - input-audio: `{ type: input_audio, input_audio.data }` + * `format`/`sample_rate` + optional `language_hints` / * `vocabulary_id` / `vocabulary`; optional leading `input_text` for context * (fun-asr-flash*, qwen-audio-*-asr-flash*) * - realtime / streaming: WebSocket — not supported by `speech recognize` */ type AsrApiKind = "async-filetrans" | "sync-flash" | "unsupported"; /** Sync-flash request body shape differs by Flash protocol family. */ type AsrFlashFamily = "qwen3" | "input-audio"; interface AsrApiRoute { kind: AsrApiKind; path: string; /** True when the call is synchronous (no X-DashScope-Async / task poll). */ useSync: boolean; /** * Async transcription request input style. * - `file_urls`: classic async models (fun-asr / paraformer / qwen-audio filetrans...) * - `file_url`: qwen3-asr-flash-filetrans family */ asyncInputStyle?: "file_urls" | "file_url"; /** * Async transcription language field style. * - `language_hints`: fun-asr / paraformer / qwen-audio filetrans... * - `language`: qwen3-asr-flash-filetrans* */ asyncLanguageStyle?: "language_hints" | "language"; flashFamily?: AsrFlashFamily; /** Human-readable reason when kind is unsupported. */ unsupportedReason?: string; } /** * Resolve which DashScope ASR API a model should use for file recognition. * Unknown models default to async-filetrans (preserves existing CLI behavior). */ export declare function resolveAsrApi(model: string): AsrApiRoute; /** Infer audio container hint for input-audio Flash `parameters.format`. */ export declare function inferAudioFormatHint(audioUrl: string): string; interface BuildAsrFlashRequestOpts { model: string; audioUrl: string; language?: string; /** Precompiled hotword vocabulary ID; supported for input-audio Flash (fun-asr-flash* / qwen-audio-*-asr-flash). */ vocabularyId?: string; /** Instant hot words (word → weight); input-audio Flash only (command layer rejects qwen3). */ vocabulary?: Record; /** Context enhancement text; prepended as input_text before input_audio. */ context?: string; flashFamily: AsrFlashFamily; } /** Wrap plain text as a single user context message for ASR. */ export declare function buildAsrContextMessages(text: string): AsrContextMessage[]; /** * Build language fields for async ASR routes. * qwen3-asr-flash-filetrans* → `language`; other async models → `language_hints`. */ export declare function buildAsyncAsrLanguageFields(languageStyle: "language_hints" | "language", language?: string): { language_hints?: string[]; language?: string; }; /** Build a sync multimodal ASR request body for Flash models. */ export declare function buildAsrFlashRequest(opts: BuildAsrFlashRequestOpts): Record; /** * Extract recognition text from a sync Flash ASR response. * Qwen3 uses choices[].message.content; input-audio Flash uses output.text / * output.sentence.text / output.output.sentence.text. */ export declare function extractAsrFlashText(response: Record, flashFamily: AsrFlashFamily): string; /** * Normalize async ASR task transcription items: * - classic models: `output.results[]` * - qwen3-asr-flash-filetrans*: `output.result.transcription_url` */ export declare function collectAsrTranscriptionItems(output: { results?: Array<{ file_url?: string; transcription_url?: string; subtask_status?: string; code?: string; message?: string; }>; result?: { transcription_url?: string; }; }): Array<{ file_url?: string; transcription_url?: string; subtask_status?: string; code?: string; message?: string; }>; //#endregion //#region src/client/headers.d.ts export declare const CHANNEL = "bailian-cli"; /** Static source identifier advertised to the DashScope/Bailian OpenAPI gateway. */ export declare const OPEN_API_SOURCE = "BailianCLI"; /** Marketplace / service attribution header (HTTP names are case-insensitive). */ export declare const DASHSCOPE_SERVICE_HEADER = "X-Dashscope-Service"; type TrackingIdentity = Pick; export declare function sourceConfig(identity: TrackingIdentity): string; /** Tracking headers for Bailian/DashScope API requests. */ export declare function trackingHeaders(identity: TrackingIdentity): Record; //#endregion //#region src/client/security.d.ts /** * Whether an origin is a public DashScope gateway. The security commands derive * their per-workspace AgentStudio host by default, so a base URL that is just * the DashScope gateway is the default and is ignored; any other origin * (pre-release / private / mock) is treated as an explicit host override. */ export declare function isDashScopeGateway(origin: string): boolean; /** * Parse an Agent Security Center response body and return the business payload. * * The backend serves these through the Zelda "DataV2" double-envelope — the same * shape the console gateway returns (see console/models.ts unwrapResponse): * * { code, successResponse, requestId, * data: { success, errorCode, errorMsg, * DataV2: { ret: ["SUCCESS::…"], * data: { success, failed, data: } } } } * * The payload lives at `data.DataV2.data.data`. The legacy flat envelope * `{ success, data, errorCode, errorMsg }` is still accepted so any endpoint * that has not migrated keeps working. A failed or unrecognized shape throws * with the raw body attached (surfaced by --output json) for diagnosis. */ export declare function parseSecurityBody(raw: string, contentType?: string | null): T | null; /** * GET a Security Center endpoint and unwrap its envelope. * * `url` is an absolute AgentStudio URL (see securityOverviewEndpoint / * securityAgentLogsEndpoint, or a --base-url override); the Client uses it * verbatim and injects the Bearer token. Genuine HTTP errors (non-2xx) surface * through the Client transport; only HTTP 200 bodies reach parseSecurityBody. * Returns null when the server reports success with no payload. */ export declare function securityGet(client: Client, url: string): Promise; //#endregion //#region src/client/instrumented-fetch.d.ts /** * fetch-compatible signature, structurally identical to the SDK-side `FetchLike` * seam. Declared locally so core stays free of SDK imports. */ type FetchImplementation = (input: string | URL | Request, init?: RequestInit) => Promise; /** * A transparent fetch wrapper carrying the client-layer cross-cutting request * concerns (UA, tracking headers, `--verbose` logging) for network stacks that * bypass {@link request} — e.g. an embedded SDK's provider clients. Deliberately * transport-only: no auth injection, no baseUrl handling, no timeout, and no * error mapping, so the caller's response semantics (status handling, SSE, * conflict detection) stay intact. */ export declare function createInstrumentedFetch(deps: HttpDeps): FetchImplementation; //#endregion //#region src/client/bailian-control.d.ts /** Shared inputs for every BailianControl OpenAPI call (AK/SK passed explicitly). */ interface BailianControlAuth { identity: Identity; settings: Settings; baseUrl: string; regionId: string; accessKeyId: string; accessKeySecret: string; securityToken?: string; } interface CreateUserReqDTO { outerKey: string; nickName: string; userName: string; } /** * Create a Bailian console user via the BailianControl OpenAPI (`CreateUser`), * signed with Alibaba Cloud AK/SK. Mirrors {@link generateCLIAccessToken}: the * caller passes AK/SK explicitly, so this needs no stored credential. */ export declare function createBailianControlUser(opts: BailianControlAuth & { reqDTO: CreateUserReqDTO; }): Promise; /** List workspaces (used to resolve the agent id for permission changes). */ export declare function listBailianControlWorkspaces(opts: BailianControlAuth): Promise; /** * Authorize a user's servicer permissions via `ResetPolicies4Agent`. The single * `data` param carries the console payload re-encoded as a JSON string. */ export declare function resetBailianControlPolicies4Agent(opts: BailianControlAuth & { outerKey: string; agentId: number; policyIndexList?: number[]; }): Promise; //#endregion //#region src/client/stream.d.ts interface ServerSentEvent { event?: string; data: string; id?: string; } export declare function parseSSE(response: Response): AsyncGenerator; //#endregion //#region src/console/gateway.d.ts type ConsoleSite = "domestic" | "international"; /** * Resolved console gateway settings (same defaults as {@link callConsoleGateway}). * 参数只需 settings 的 console 三元组;dry-run 展示分支直接传 settings。 */ export declare function effectiveConsoleGatewayConfig(config: Pick): { consoleRegion: string; consoleSite: ConsoleSite; consoleSwitchAgent?: number; }; interface ConsoleGatewayRequest { /** Console API name, e.g. zeldaEasy.broadscope-bailian.freeTrial.queryFreeTierQuota */ api: string; data: Record; } /** Console-call signature shared by catalog helpers (`client.console` or an anonymous call). */ type ConsoleCall = (api: string, data: Record) => Promise; /** * Build an anonymous (token-less) gateway caller for public catalog APIs such * as `listFoundationModels` — no console login required. */ export declare function anonymousConsoleCall(config: Pick): ConsoleCall; /** * Invoke a Bailian **console** OpenAPI via the CLI gateway (`/cli/api.json`). * 目标(region/site/switchAgent)与 token 均由调用方解析后传入:Client.console 传 * ConsoleCredential;公共目录类 API(如 advisor 的模型目录)可不带 token 匿名调用。 */ interface ConsoleGatewayTarget { region: string; site: ConsoleSite; switchAgent?: number; token?: string; } export declare function callConsoleGateway(target: ConsoleGatewayTarget, timeoutSec: number, { api, data }: ConsoleGatewayRequest, settings?: Pick): Promise; //#endregion //#region src/console/models.d.ts export declare const MODEL_LIST_API = "zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels"; export declare const PREDICT_CONFIG_API = "zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig"; /** Unwrap the DataV2 double-envelope that console gateway returns. */ export declare function unwrapResponse(result: Record): Record; interface ModelListParams { pageNo?: number; pageSize?: number; name?: string; providers?: string[]; capabilities?: string[]; } interface ModelListResult { total: number; models: Record[]; } /** Page the console model-list API. `call` makes the gateway request (e.g. `client.console`). */ export declare function fetchModelList(call: ConsoleCall, params?: ModelListParams): Promise; /** Page through every model-list page and return all raw model items. */ export declare function fetchModelListAll(call: ConsoleCall, params?: Omit): Promise[]>; /** * Look up a single model by exact id. The server's `name` filter is a * substring match, so an exact `model` equality check narrows the result * (e.g. avoids `qwen3-8b` matching `qwen3-8b-v2`). */ export declare function findModelByName(call: ConsoleCall, modelName: string): Promise | null>; interface ModelPriceInfo { type?: string; priceUnit?: string; price?: string | number; [key: string]: unknown; } /** Retirement notice for one service of a model. */ interface ModelOfflineNotice { /** Public announcement URL; empty when the platform published none. */ announceUrl?: string; /** Local-time `YYYY-MM-DD HH:mm:ss`; absent once the model is already offline. */ offlineTime?: string; } /** Per-service retirement notices, keyed by service name (`inference`, …). */ interface ModelOfflineInfo { inference?: ModelOfflineNotice; } /** A single snippet: `{ code, … }` under one language of one API style. */ interface ModelSampleSnippet { code?: string; [key: string]: unknown; } /** sdk → api style → language → snippet (e.g. `openai.completionsAPI.python`). */ type ModelSampleCodeV2 = Record>>; interface ModelGroupItem { model: string; name: string; description?: string; shortDescription?: string; provider?: string; capabilities?: string[]; features?: string[]; contextWindow?: number; maxOutputTokens?: number; maxInputTokens?: number; inferenceMetadata?: Record; prices?: ModelPriceInfo[]; qpmInfo?: Record>; docUrl?: string; versionTag?: string; openSource?: boolean; category?: string; predictConfig?: PredictConfigEntry[]; /** Present once the model has been retired; an ISO timestamp. */ offlineAt?: string; /** Present once retirement has been announced, before or after it takes effect. */ offlineInfo?: ModelOfflineInfo; sampleCodeV2?: ModelSampleCodeV2; [key: string]: unknown; } interface ModelGroup { model: string; name: string; description?: string; updateAt?: string; items: ModelGroupItem[]; [key: string]: unknown; } interface ModelGroupParams { pageNo?: number; pageSize?: number; name?: string; providers?: string[]; capabilities?: string[]; features?: string[]; contextWindows?: string[]; querySampleCode?: boolean; } interface ModelGroupResult { total: number; groups: ModelGroup[]; } /** Fetch model families with optional filters and query flags. */ export declare function fetchModelGroups(call: ConsoleCall, params?: ModelGroupParams): Promise; /** Flatten family groups into their individual model items. */ export declare function flattenModelGroups(groups: ModelGroup[]): ModelGroupItem[]; /** * Fetch every model item in the catalog. The first page yields `total`; the * remaining pages are fetched concurrently because ranking needs the whole set. */ export declare function fetchModelGroupsAll(call: ConsoleCall, params?: Omit): Promise; /** Fetch a single model family with all detail flags enabled. */ export declare function fetchModelDetail(call: ConsoleCall, modelKey: string): Promise; interface PredictConfigEntry { name: string; key: string; default?: unknown; tip?: string; range?: unknown; } /** Fetch the input parameter schema for a specific model. */ export declare function fetchPredictConfig(call: ConsoleCall, modelId: string): Promise; //#endregion //#region src/config/paths.d.ts export declare function getConfigDir(): string; export declare function getConfigPath(): string; export declare function getCredentialsPath(): string; export declare function ensureConfigDir(): Promise; //#endregion //#region src/config/profile-presets.d.ts interface ModelProfilePreset { baseUrl: string; defaultTextModel: string; defaultVideoModel: string; defaultImageToVideoModel: string; defaultReferenceToVideoModel: string; defaultImageModel: string; defaultSpeechModel: string; defaultSpeechRecognitionModel: string; apiKeyCapabilities: readonly string[]; } type ApiKeyLoginKind = "token-plan" | "ordinary" | "unknown"; /** Defaults materialized when logging into a well-known model profile. */ export declare function getModelProfilePreset(configName?: string): ModelProfilePreset | undefined; /** Classify only the key formats that affect automatic Profile routing. */ export declare function getApiKeyLoginKind(apiKey: string): ApiKeyLoginKind; //#endregion //#region src/config/model-base-url.d.ts /** * Normalize a model-service base URL to its origin. * CLI endpoints append their own API paths, so user-provided paths, query * parameters, and fragments must not remain in the stored or resolved base URL. */ export declare function normalizeModelBaseUrl(input: string): string; //#endregion //#region src/output/formatter.d.ts type OutputFormat = "text" | "json"; export declare function detectOutputFormat(flagValue?: string): OutputFormat; export declare function formatOutput(data: unknown, format: OutputFormat): string; //#endregion //#region src/output/json.d.ts export declare function formatJson(data: unknown): string; export declare function formatErrorJson(code: number, message: string, hint?: string): string; //#endregion //#region src/output/text.d.ts export declare function formatText(data: unknown): string; //#endregion //#region src/files/upload.d.ts interface UploadOptions { apiKey: string; model: string; filePath: string; identity: TrackingIdentity; signal?: AbortSignal; } /** Encode a local image as a Data URI. */ export declare function imageFileToDataUri(filePath: string): string; /** Keep dry-run output readable and avoid echoing the complete inline image. */ export declare function redactDataUri(input: string): string; /** * Upload a local file to DashScope temporary storage and return the oss:// URL. * The URL is valid for 48 hours. */ export declare function uploadFile(opts: UploadOptions): Promise; /** * Check if a string looks like a local file path (not a URL). */ export declare function isLocalFile(input: string): boolean; /** * Resolve a file argument: if it's a local path, upload it and return the oss:// URL. * If it's already a URL, return as-is. */ export declare function resolveFileUrl(input: string, apiKey: string, model: string, opts: { identity: TrackingIdentity; signal?: AbortSignal; }): Promise; //#endregion //#region src/dataset/types.d.ts /** * Dataset API types. * * Maps DashScope `/api/v1/files` responses. The same endpoint backs every * dataset purpose the platform supports today (fine-tune training, * evaluation, etc.) — these types are deliberately purpose-agnostic so new * purposes can be plugged in without schema changes. */ /** A single uploaded dataset file as returned by the platform. */ export interface DatasetFile { /** File ID — the only stable handle for downstream consumers. */ file_id: string; /** Original filename uploaded by the user. */ name: string; /** Bytes. */ size?: number; /** Content hash (server-computed). */ md5?: string; /** Free-form purpose tag, e.g. "fine-tune", "evaluation". */ purpose?: string; /** Optional internal/external URL (kept for parity with the API). */ url?: string; /** Free-form description if the user supplied one at upload time. */ description?: string; /** Server-side creation timestamp (string, format per platform). */ gmt_create?: string; } /** GET /api/v1/files response. */ export interface DatasetListResponse { request_id?: string; data?: { files?: DatasetFile[]; total?: number; page_no?: number; page_size?: number; }; } /** GET /api/v1/files/{file_id} response. */ export interface DatasetGetResponse { request_id?: string; data?: DatasetFile; } /** * POST /compatible-mode/v1/files response (OpenAI-compatible). * * Flat shape — there is no `data` envelope on success. `id` is the file handle * to pass to fine-tune jobs; `purpose` is echoed back so callers can confirm * it landed. On business-level failure (HTTP 200 + `data.failed_uploads`) * `id` is absent and `data.failed_uploads[]` carries the platform's reason. */ export interface DatasetUploadResponse { request_id?: string; /** File ID — the handle returned to callers (e.g. `file-ft-…`). */ id?: string; /** Always `"file"` for this endpoint. */ object?: string; /** Bytes. */ bytes?: number; /** Original filename uploaded by the user. */ filename?: string; /** Purpose tag, e.g. `"fine-tune"`, `"file-extract"`, `"batch"`. */ purpose?: string; /** Platform processing state, e.g. `"processed"`. */ status?: string; /** Creation timestamp (Unix seconds). */ created_at?: number; /** * Failure envelope: HTTP 200 + business failure. When present the upload * did NOT produce a file_id; callers must treat this as an error. Common * cause: server-side schema rejection (e.g. malformed JSONL slipped past * the local pre-flight). */ data?: { failed_uploads?: Array<{ code?: string; message?: string; file_name?: string; }>; }; } /** DELETE /api/v1/files/{file_id} response. */ export interface DatasetDeleteResponse { request_id?: string; data?: { deleted?: boolean; file_id?: string; }; } //#endregion //#region src/dataset/api.d.ts export interface DatasetUploadParams { filePath: string; /** * Purpose tag forwarded to the platform. Defaults to "fine-tune" because * the API requires the field, but callers should set this explicitly when * uploading evaluation or other dataset kinds. */ purpose?: string; signal?: AbortSignal; } /** * POST /compatible-mode/v1/files (multipart/form-data) * * Streams the file from disk so we don't buffer 300MB into memory. Node's * `fetch` accepts a `Blob` produced from a Readable stream via `Response`'s * body shim, but the simplest portable approach (and the one used in * `files/upload.ts`) is to wrap the buffer in a Blob. Here we use `Blob` * with a stream-backed lazy `arrayBuffer()` for >50MB files via * `Response`'s helper to avoid the buffer doubling. Fall back to readFileSync * for small files where streaming overhead isn't worth it. */ export declare function uploadDataset(client: Client, params: DatasetUploadParams): Promise; export interface DatasetListParams { pageNo?: number; pageSize?: number; purpose?: string; signal?: AbortSignal; } /** GET /api/v1/files */ export declare function listDatasets(client: Client, params?: DatasetListParams): Promise; /** GET /api/v1/files/{file_id} */ export declare function getDataset(client: Client, fileId: string, signal?: AbortSignal): Promise; /** DELETE /api/v1/files/{file_id} */ export declare function deleteDataset(client: Client, fileId: string, signal?: AbortSignal): Promise; //#endregion //#region src/dataset/validate/types.d.ts /** * Validator types — the registry contract that every format adheres to. * * Design (Plan B from the architecture review): * - A `ValidatorSpec` is a plain object, not a class. Adding a new format = * one new file exporting one constant + one line in the registry. * - Common pre-flight checks (existence, size, extension) live in `common.ts` * and are applied by `validateDataset` before the format-specific validator * runs, so individual specs only handle structural concerns. */ interface ValidateOpts { /** When true, validators should do exhaustive checks (e.g. parse every line). */ fullValidate?: boolean; /** Optional max bytes override (defaults to 300MB at the registry level). */ maxBytes?: number; /** Optional abort signal for long-running scans. */ signal?: AbortSignal; /** * Record-schema selector for formats that carry more than one schema under * the same extension. Today only the `.jsonl` ChatML family honors it: * - `"chatml"` — `{messages: [...]}` (SFT). `chosen`/`rejected` ignored. * - `"dpo"` — `{messages: [...], chosen: {role,content}, rejected: {...}}`. * Every record MUST carry `chosen` + `rejected`. * - `"cpt"` — `{text: "..."}` (continual pre-training). Raw text only, * no `messages[]`. * - `undefined` — auto-detect per record: a record with `chosen` or * `rejected` is validated as DPO, one with `text` (and no * `messages`) as CPT, otherwise as ChatML. * `finetune create` sets this from `--training-type` (dpo* → "dpo", * cpt → "cpt") so a malformed dataset fails at validate time, not on the * platform ten minutes in. */ schema?: DatasetSchema; /** * Model identifier (`--model`) forwarded for schema-agnostic cross-checks — * e.g. the video validator uses it to verify a `kf2v` model is paired with * first+last-frame data. Optional: absent for bare file-id flows. */ model?: string; } /** The schemas a `.jsonl` record can be validated against. */ type DatasetSchema = "chatml" | "dpo" | "cpt" | "tts" | "image" | "video"; type ValidationSeverity = "error" | "warning"; interface ValidationIssue { severity: ValidationSeverity; /** Stable machine-readable key, e.g. "EMPTY_FILE", "MALFORMED_JSON". */ code: string; /** Human-readable message. */ message: string; /** 1-indexed line number for line-oriented formats. */ line?: number; /** Optional path inside the offending row, e.g. "messages[2].role". */ path?: string; } interface ValidationStats { /** Total observed records (rows / samples / messages, depending on format). */ totalRecords?: number; /** Records actually deep-checked (sampled). */ sampledRecords?: number; /** Total file bytes. */ bytes?: number; /** Wall time spent in the scan (ms). */ durationMs?: number; } interface ValidationResult { valid: boolean; format: string; filePath: string; errors: ValidationIssue[]; warnings: ValidationIssue[]; stats: ValidationStats; } interface ValidatorSpec { /** Human-readable format identifier, e.g. "jsonl". */ format: string; /** Lower-cased file extensions handled by this validator (include dot). */ extensions: string[]; /** Format-specific check. Pre-flight (existence/size) is applied by the registry. */ validate(filePath: string, opts: ValidateOpts): Promise; } //#endregion //#region src/finetune/profiles/types.d.ts /** * Data modality detected by the inspector from file content. * * The inspector peeks at the first record of a JSONL or the `data.jsonl` inside * a ZIP to determine what kind of data the file carries. This is orthogonal to * the training type — `sft-lora` accepts both `.jsonl` (text) and `.zip` * (audio / image / video). * * `"image-i2i"` is a subtype of `"image"` — the first record contains an * `input_img` field (image-to-image). `"video-kf2v"` is a subtype of `"video"` * — the first record contains a `last_frame_path` field (first+last-frame video, * Wan kf2v). Profiles can branch on subtypes to adjust hyper-parameter defaults * or cross-check the chosen `--model`. Callers that don't care about a subtype * can normalise `"image-i2i"` → `"image"` and `"video-kf2v"` → `"video"`. */ type DataModality = "text" | "audio" | "image" | "image-i2i" | "video" | "video-kf2v"; /** * A training profile. One per `--training-type` CLI value. * * The profile owns all modality-specific branching internally — callers * (`create.ts`) interact with it through a uniform interface and never need * to know whether the data is text, audio, or something else. */ interface TrainingProfile { /** CLI vocabulary: the value users pass to `--training-type`. */ clientTrainingType: string; /** Server `training_type` for the POST /fine-tunes request body. */ serverTrainingType: string; /** File extensions this profile accepts (lower-case, with dot). */ acceptedExtensions: string[]; /** * Validate the training data file. The profile internally routes to the * correct validator based on `modality` (detected by the data inspector). */ validate(filePath: string, modality: DataModality, opts: ValidateOpts): Promise; /** * Build the `hyper_parameters` object for the API request. Merges user-supplied * flags with modality-specific defaults (e.g. audio TTS uses `lm_max_epoch` / * `fm_max_epoch`, text SFT uses `n_epochs` / `batch_size`). */ resolveHyperParameters(modality: DataModality, flags: Record): Record; /** * Whether a specific pre-flight gate should be skipped for the given modality. * Common gates: `"batch_size"` (samples must exceed batch_size), etc. * Audio TTS skips the batch-size gate (no batch_size hyper-parameter). */ shouldSkipGate(gate: string, modality: DataModality): boolean; /** * Whether the model-capability pre-flight check should be skipped. * Audio models (e.g. cosyvoice-v3-flash) report `supports.sft = false` in * `listFoundationModels` but the API accepts `efficient_sft` — the check * would incorrectly block the submission. */ shouldSkipCapabilityCheck(modality: DataModality): boolean; } //#endregion //#region src/dataset/inspect.d.ts /** * Inspect a file and return its data modality. * * `.jsonl` → read the first non-blank line, parse JSON, check fields. * `.zip` → locate `data.jsonl` inside the archive, read its first line. * * Image data returns `"image"` (T2I) or `"image-i2i"` (I2I, first record * has `input_img`). Callers that don't distinguish can normalise to `"image"`. * * Throws USAGE if the file extension is not `.jsonl` or `.zip`, or if the * content cannot be parsed. */ export declare function detectModality(filePath: string): Promise; //#endregion //#region src/dataset/validate/registry.d.ts /** Lookup the validator that handles a given file extension. */ export declare function pickValidator(filePath: string): ValidatorSpec; /** Allow tests / future plugins to inject extra validators. Idempotent. */ export declare function registerValidator(spec: ValidatorSpec): void; /** * Top-level entry point. Applies common pre-flight (existence/size/extension) * then defers to the format-specific validator. */ export declare function validateDataset(filePath: string, opts?: ValidateOpts): Promise; /** Read-only view of the active registry — handy for tests / `--help`. */ export declare function listSupportedFormats(): { format: string; extensions: string[]; }[]; //#endregion //#region src/dataset/validate/common.d.ts /** * The platform caps SFT/DPO text dataset uploads at 200MB per file. * `bl dataset upload` enforces this client-side so users learn early. * CPT uses 300MB (see MAX_CPT_BYTES); API general upload is also 300MB. */ export declare const MAX_DATASET_BYTES: number; /** * CPT text dataset size cap — 300 MB per the platform docs. * CPT requires at least 50M tokens; larger files are expected. */ export declare const MAX_CPT_BYTES: number; /** * Image / video ZIP size cap — 2 GB per the platform docs. Used by * `bl dataset upload` for media schemas and by the `sft-lora` training * profile for image / video validation. */ export declare const MAX_MEDIA_ZIP_BYTES: number; /** * Parse a `--schema` CLI value into a `DatasetSchema` (or `undefined` for * auto-detect). Single source of truth for the schema vocabulary so `dataset * validate`, `dataset upload`, and any future caller agree on accepted values * and error wording. Throws USAGE for anything unrecognized. */ export declare function parseDatasetSchemaFlag(value: string | undefined): DatasetSchema | undefined; //#endregion //#region src/dataset/validate/format.d.ts /** * Format a single validation issue as a one-line string. * * Shared across every entry point that surfaces dataset validation results * (`dataset validate`, `dataset upload`, `finetune create`) so the error * presentation stays consistent regardless of which command ran the validator. */ export declare function formatIssue(issue: ValidationIssue): string; //#endregion //#region src/finetune/types.d.ts /** * Fine-tune job API types. * * Maps DashScope `/api/v1/fine-tunes` request/response shapes (snake_case * preserved verbatim — callers decide how to surface fields). */ /** Hyper-parameters honored by text/thinking/vision SFT models. */ export interface FineTuneHyperParameters { /** Number of training epochs. */ n_epochs?: number; batch_size?: number; /** Sent as a string to avoid JSON-number precision loss (e.g. "1.6e-5"). */ learning_rate?: string; max_length?: number; /** Train/validation split ratio when no validation file is provided. */ split?: number; lr_scheduler_type?: string; /** Future-compat: arbitrary additional fields are forwarded as-is. */ [k: string]: unknown; } /** POST /api/v1/fine-tunes request body. */ export interface CreateFineTuneRequest { /** Base model ID, or a previously fine-tuned model ID for continued training. */ model: string; training_file_ids: string[]; /** * Server-supported values: `cpt | sft | efficient_sft | dpo_full | dpo_lora`. * * NOTE — current bailian-cli scope: `sft` (default) and `efficient_sft`. * Other values are rejected by the CLI at parse time so users get an * immediate error instead of a vague server-side rejection. This type * stays open as `string` for forward compatibility (so adding `dpo_lora` * later is a CLI-only change). */ training_type: string; validation_file_ids?: string[]; hyper_parameters?: FineTuneHyperParameters; /** Display name for the job (optional, server generates if omitted). */ job_name?: string; /** Output model name. Either bring your own or let the server generate one. */ model_name?: string; /** Suffix appended by the platform; field is `finetuned_output_suffix` (NOT `suffix`). */ finetuned_output_suffix?: string; } /** GET /api/v1/fine-tunes/{id}/logs response. */ export interface FineTuneLogEntry { /** Server-defined log line — schema varies; preserve as-is. */ [k: string]: unknown; } export interface GetFineTuneLogsResponse { request_id?: string; output?: { logs?: Array; total?: number; page_no?: number; page_size?: number; [k: string]: unknown; }; data?: { logs?: Array; total?: number; page_no?: number; page_size?: number; [k: string]: unknown; }; } /** A single checkpoint as returned by the platform. */ export interface FineTuneCheckpoint { checkpoint?: string; checkpoint_id?: string; full_name?: string; job_id?: string; model_name?: string; model_display_name?: string; /** SUCCEEDED | PENDING | FAILED | … */ status?: string; step?: number; epoch?: number; create_time?: string; expire_time?: string; output_model_deleted?: boolean; metrics?: Record; [k: string]: unknown; } /** * GET /api/v1/fine-tunes/{job_id}/checkpoints response. * * Real shape: `output` is an array of checkpoints directly (NOT wrapped in * `{ checkpoints: [...] }`). The wrapped form is preserved as a fallback for * older deployments. */ export interface ListCheckpointsResponse { request_id?: string; output?: FineTuneCheckpoint[] | { checkpoints?: FineTuneCheckpoint[]; total?: number; [k: string]: unknown; }; data?: FineTuneCheckpoint[] | { checkpoints?: FineTuneCheckpoint[]; total?: number; [k: string]: unknown; }; } /** GET /api/v1/fine-tunes/{job_id}/export/{checkpoint}?model_name= response. */ export interface ExportCheckpointResponse { request_id?: string; output?: { /** Resulting deployable model name. */ model_name?: string; [k: string]: unknown; }; data?: { model_name?: string; [k: string]: unknown; }; } /** POST /api/v1/fine-tunes/{id}/cancel response. */ export interface CancelFineTuneResponse { request_id?: string; output?: FineTuneJob; data?: FineTuneJob; } /** DELETE /api/v1/fine-tunes/{id} response. */ export interface DeleteFineTuneResponse { request_id?: string; output?: { deleted?: boolean; job_id?: string; [k: string]: unknown; }; data?: { deleted?: boolean; job_id?: string; [k: string]: unknown; }; } /** A single fine-tune job record as returned by the platform. */ export interface FineTuneJob { job_id?: string; job_name?: string; model?: string; base_model?: string; training_type?: string; /** PENDING | RUNNING | SUCCEEDED | FAILED | CANCELED */ status?: string; finetuned_output?: string; finetuned_output_suffix?: string; model_name?: string; training_file_ids?: string[]; validation_file_ids?: string[]; hyper_parameters?: FineTuneHyperParameters; /** Server-side timestamps (DashScope uses snake_case `create_time` / `end_time`). */ create_time?: string; end_time?: string; /** Legacy field names — kept for backward compatibility with older deployments. */ gmt_create?: string; gmt_modified?: string; /** Free-form additional fields are preserved by callers. */ [k: string]: unknown; } /** POST /api/v1/fine-tunes response. */ export interface CreateFineTuneResponse { request_id?: string; /** Modern DashScope shape. */ output?: FineTuneJob; /** Legacy shape for older platform builds. */ data?: FineTuneJob; } /** GET /api/v1/fine-tunes response. */ export interface ListFineTunesResponse { request_id?: string; output?: { jobs?: FineTuneJob[]; total?: number; page_no?: number; page_size?: number; }; data?: { jobs?: FineTuneJob[]; total?: number; page_no?: number; page_size?: number; }; } /** GET /api/v1/fine-tunes/{job_id} response. */ export interface GetFineTuneResponse { request_id?: string; output?: FineTuneJob; data?: FineTuneJob; } //#endregion //#region src/finetune/api.d.ts /** POST /api/v1/fine-tunes */ export declare function createFineTune(client: Client, body: CreateFineTuneRequest, signal?: AbortSignal): Promise; export interface ListFineTunesParams { pageNo?: number; pageSize?: number; status?: string; /** Filter by base model ID (server-side). */ model?: string; signal?: AbortSignal; } /** GET /api/v1/fine-tunes */ export declare function listFineTunes(client: Client, params?: ListFineTunesParams): Promise; /** GET /api/v1/fine-tunes/{job_id} */ export declare function getFineTune(client: Client, jobId: string, signal?: AbortSignal): Promise; /** POST /api/v1/fine-tunes/{job_id}/cancel */ export declare function cancelFineTune(client: Client, jobId: string, signal?: AbortSignal): Promise; /** DELETE /api/v1/fine-tunes/{job_id} */ export declare function deleteFineTune(client: Client, jobId: string, signal?: AbortSignal): Promise; export interface GetFineTuneLogsParams { pageNo?: number; pageSize?: number; signal?: AbortSignal; } /** GET /api/v1/fine-tunes/{job_id}/logs */ export declare function getFineTuneLogs(client: Client, jobId: string, params?: GetFineTuneLogsParams): Promise; /** GET /api/v1/fine-tunes/{job_id}/checkpoints */ export declare function listCheckpoints(client: Client, jobId: string, signal?: AbortSignal): Promise; /** * GET /api/v1/fine-tunes/{job_id}/export/{checkpoint}?model_name={name} * * Publishes a training checkpoint as a deployable model — required before * `deploy create` can target it. The platform may auto-export the best * checkpoint on SUCCEEDED, but explicit export is the canonical path. */ export declare function exportCheckpoint(client: Client, jobId: string, checkpoint: string, modelName: string, signal?: AbortSignal): Promise; //#endregion //#region src/finetune/capability.d.ts /** * Training-type vocabulary exposed to users. * * Convention: the bare method name is **full-parameter** tuning; the `-lora` * suffix is the LoRA variant. This holds for `sft` and `dpo` (both have a * full + lora pair). `cpt` is the exception — the platform only supports * full-parameter CPT (no `cpt-lora` exists server-side), so it has no lora * sibling. * * Each CLI value maps 1:1 to a server `training_type`. The mapping happens at * the interface boundary (request body), so the rest of the CLI never sees the * raw server strings (`efficient_sft`, `dpo_full`, ...). */ export declare const TRAINING_TYPE_MAP: { readonly sft: { readonly server: "sft"; readonly method: "sft"; readonly variant: "full"; }; readonly "sft-lora": { readonly server: "efficient_sft"; readonly method: "sft"; readonly variant: "lora"; }; readonly dpo: { readonly server: "dpo_full"; readonly method: "dpo"; readonly variant: "full"; }; readonly "dpo-lora": { readonly server: "dpo_lora"; readonly method: "dpo"; readonly variant: "lora"; }; readonly cpt: { readonly server: "cpt"; readonly method: "cpt"; readonly variant: "full"; }; }; export type TrainingTypeCli = keyof typeof TRAINING_TYPE_MAP; /** All accepted CLI training-type values (for whitelisting / help text). */ export declare const TRAINING_TYPES_CLI: readonly TrainingTypeCli[]; /** Default training type when `--training-type` is omitted. */ export declare const DEFAULT_TRAINING_TYPE: TrainingTypeCli; /** Subset of `supports` relevant to training capability. */ interface ModelSupports { sft?: boolean; dpo?: boolean; cpt?: boolean; [key: string]: unknown; } /** * A model record's training-capability fields. The full listFoundationModels * item carries many more fields; only these are consulted here. */ export interface ModelCapability { model?: string; supports?: ModelSupports; trainingTypes?: Record; [key: string]: unknown; } /** True when `value` is one of the accepted CLI training types. */ export declare function isTrainingTypeCli(value: string): value is TrainingTypeCli; /** The (method, variant) pair a CLI training type resolves to. */ export declare function trainingTypeMethodVariant(value: TrainingTypeCli): { method: string; variant: string; }; /** * Whether a model supports the given CLI training type. * * A model supports `[-lora]` when both: * 1. `supports. === true` (the high-level capability gate), and * 2. `trainingTypes.` includes the corresponding variant * (`full` for the bare name, `lora` for the `-lora` suffix). */ export declare function modelSupportsTrainingType(model: ModelCapability | undefined | null, value: TrainingTypeCli): boolean; /** * Every CLI training type a model supports, in canonical order * (sft, sft-lora, dpo, dpo-lora, cpt). Empty when the model carries no * capability metadata or supports none. */ export declare function listSupportedTrainingTypes(model: ModelCapability | undefined | null): TrainingTypeCli[]; /** * Fetch a single model's foundation metadata by name (console gateway * `listFoundationModels` with a `name` filter). No console login required — * `listFoundationModels` is a public API, so only a DashScope API key is needed. * * Returns the first exact-model match, or `null` when nothing matches (the * server's `name` filter is a substring match, so we additionally require an * exact `model` equality to avoid e.g. `qwen3-8b` matching `qwen3-8b-v2`). */ export declare function fetchModelCapability(settings: Settings, modelName: string): Promise; //#endregion //#region src/finetune/preflight.d.ts /** Stable issue code for "too few training samples for the batch size". */ export declare const INSUFFICIENT_SAMPLES_CODE = "INSUFFICIENT_SAMPLES"; export interface BatchSizeGateInput { /** * Total training-sample count across all `--datasets` files. Sourced from * `validateDataset`'s `stats.totalRecords` (summed per file). The gate only * fires when this is known — i.e. every dataset token was a local file that * was validated; bare file-id tokens yield no count and fall through to the * platform. */ recordCount: number; /** * Effective batch_size the job will run with — after the CLI's clamp * ([8, 1024]) and small-file auto-adjust, or the platform default (16) when * neither the user nor auto-adjust set one. */ batchSize: number; } export interface BatchSizeGateResult { ok: boolean; /** Present when `!ok`, in the same shape `validateDataset` issues use. */ issue?: ValidationIssue; /** Actionable guidance; callers surface it as the `BailianError` detail. */ hint?: string; } /** * Pre-flight the platform's "training samples must exceed batch_size" rule. * * The platform rejects a job whose number of training samples is not greater * than batch_size, but only surfaces that ~10 minutes into the run (after data * processing). This gate fails fast, before upload or quota consumption. * * Conservative by design — never false-positives: with the platform's default * 0.9 train split, training samples = 0.9 * recordCount <= recordCount, so * `recordCount <= batchSize` implies training samples <= batchSize implies * certain platform failure. Borderline counts (records just above batchSize) * may still fail on the platform; that's an acceptable false negative for a * pre-check, and the hint nudges users to leave margin for the split. */ export declare function preflightBatchSizeGate(input: BatchSizeGateInput): BatchSizeGateResult; //#endregion //#region src/finetune/profiles/registry.d.ts /** Look up a profile by its CLI training-type name. Throws USAGE if unknown. */ export declare function getProfile(clientTrainingType: string): TrainingProfile; /** All registered CLI training-type names (for help text / whitelisting). */ export declare function listTrainingTypes(): string[]; //#endregion //#region src/finetune/price.d.ts export declare const TRAINING_MODEL_PRICE_API = "zeldaEasy.broadscope-platform.modelCenter.getModelPrice"; export declare const CALC_DATASETS_TOKENS_API = "zeldaEasy.broadscope-platform.modelInstance.calculateDatasetsTotalTokens"; export declare const ESTIMATE_FINETUNE_TOKENS_API = "zeldaEasy.broadscope-platform.modelInstance.estimateFinetuneTokens"; export interface TrainingModelPrice { price?: string; priceUnit?: string; modelId?: string; [key: string]: unknown; } export interface TokenEstimate { estimatedDatasetConsumedTokensMinPerEpoch?: number; estimatedDatasetConsumedTokensMaxPerEpoch?: number; estimatedMixedConsumedTokensMinPerEpoch?: number; estimatedMixedConsumedTokensMaxPerEpoch?: number; [key: string]: unknown; } /** * Training unit price for a model. `price` is denominated in `priceUnit` * (typically "千Token" — yuan per 1000 tokens). */ export declare function fetchTrainingModelPrice(client: Client, modelId: string): Promise; /** * Estimate training tokens for SFT / DPO jobs. * Returns a per-epoch min/max range; multiply by `n_epochs` for the total. */ export declare function estimateSftDpoTokens(client: Client, datasetIds: string[], hyperParams: { nEpochs: number; batchSize: number; maxLength: number; }): Promise; /** * Estimate training tokens for CPT jobs. * * The console API requires `hyperParams` as a **JSON string** with a full * `userDefinedObj` payload (captured from the console frontend), plus several * top-level fields (`algorithmType`, `bizType`, `priority`, …). Only * `n_epochs` / `max_length` materially affect the estimate; the remaining * hyper-parameters are fixed defaults. */ export declare function estimateCptTokens(client: Client, model: string, datasetIdsCsv: string, nEpochs: number): Promise; //#endregion //#region src/deploy/types.d.ts /** * Model-deployment API types. * * Maps DashScope `/api/v1/deployments` request/response shapes (snake_case * preserved verbatim — callers decide how to surface fields). */ /** A single deployment record as returned by the platform. */ export interface Deployment { /** Unique deployed-model identifier — used as the `model` parameter when invoking the deployed model. */ deployed_model?: string; /** Human-friendly display name set at creation time. */ name?: string; /** Underlying model identifier (e.g. fine-tuned output or catalog model). */ model_name?: string; /** Catalog base model. */ base_model?: string; /** PENDING | RUNNING | STOPPED | FAILED */ status?: string; /** Billing plan: mu | cu | ptu | lora (Token-billed). */ plan?: string; /** Spec descriptor for MU plan, e.g. "MU1". */ model_unit_spec?: string; /** Charge type, e.g. "post_paid". */ charge_type?: string; /** Capacity in plan units. */ capacity?: number; base_capacity?: number; ready_capacity?: number; /** Rate limits (per minute). */ rpm_limit?: number; tpm_limit?: number; /** PTU-only token-rate limits. */ input_tpm?: number; output_tpm?: number; /** Aggregate effective reservation capacity, in kTPM. */ ptu_capacity?: ReservationCapacity; /** ptu_fast | ptu_default | future service tiers. */ ptu_service_tier?: string; pre_paid_info?: PrePaidInfo; pre_paid_instance_id?: string; pre_paid_gmt_expired?: string; /** enable | disable | future overflow strategies. */ overflow_strategy?: string; fail_reason?: string; operation_id?: string; instance_id?: string; enable_thinking?: boolean; max_context_length?: number; workspace_id?: string; creator?: string; modifier?: string; gmt_create?: string; gmt_modified?: string; /** Free-form additional fields are preserved by callers. */ [k: string]: unknown; } /** Reservation capacity returned by queries; separate from legacy PTU write input. */ export interface ReservationCapacity { /** Input capacity in kTPM (1 kTPM = 1000 tokens/minute); zero is valid. */ input_tpm?: number; /** Output capacity in kTPM; zero is valid. */ output_tpm?: number; [key: string]: unknown; } /** Prepaid purchase and renewal configuration returned by queries. */ export interface PrePaidInfo { /** Purchase / renewal duration in days. */ duration?: number; auto_renewal?: boolean; /** Automatic renewal duration in days. */ auto_renewal_duration?: number; /** Renewal cycle unit, e.g. Day. */ auto_renewal_cycle?: string; [key: string]: unknown; } /** A capacity instance returned by list/detail queries, including released instances. */ export interface CapacityInstance { /** The deployment's ModelCode. Identifiers are opaque strings. */ model_service_id?: string; instance_id?: string; /** pre_paid | post_paid | future charge types. */ charge_type?: string; /** Instance lifecycle state; future states are preserved. */ status?: string; deleted?: boolean; /** Currently confirmed serving capacity. */ effective_capacity?: ReservationCapacity; /** Configured / contracted capacity, which may remain while stopped or suspended. */ configured_capacity?: ReservationCapacity; /** Pending target, not effective capacity; may be absent or null in a stable state. */ target_capacity?: ReservationCapacity | null; pre_paid_info?: PrePaidInfo; gmt_expired?: string; can_scale?: boolean; can_renew?: boolean; can_delete?: boolean; fail_reason?: string; gmt_created?: string; gmt_modified?: string; gmt_deleted?: string; [key: string]: unknown; } /** A capacity operation returned by a query; no state or identifier normalization. */ export interface CapacityOperation { operation_id?: string; /** Original operation request ID, distinct from the query response's request_id. */ request_id?: string; /** CREATE | SCALE | RENEW | DELETE | STOP | REFUND | future operation types. */ operation_type?: string; /** PROCESSING | SUCCEEDED | FAILED | future operation states. */ operation_status?: string; model_service_id?: string; instance_id?: string; from_status?: string; current_status?: string; error_code?: string; error_message?: string; gmt_created?: string; gmt_finished?: string; [key: string]: unknown; } /** A single deployable model record (GET /deployments/models). */ export interface DeployableModel { model_name?: string; base_model?: string; /** custom | public | base | … */ model_source?: string; /** Supported plans for `custom` (fine-tuned) models, e.g. ["mu","lora"]. */ supported_plans?: string[]; /** * Nested plan info for `base` (catalog) models. Each entry describes one * plan and (when applicable) its deployment templates. * - plan: "mu" | "ptu_v2" | "cu" | … * - templates: required when plan="mu" — picks deploy_spec / charge_type / role configs * - cu_specs: required when plan="cu" — light/basic etc */ plans?: Array<{ plan?: string; templates?: Array; cu_specs?: string[]; [k: string]: unknown; }>; display_name?: string; description?: string; version?: string; status?: string; gmt_create?: string; gmt_modified?: string; [k: string]: unknown; } /** A single deployment template (only used by `plan=mu` base models). */ export interface DeployableTemplate { template_id?: string; template_name?: string; template_desc?: string; /** pre_paid | post_paid */ charge_type?: string; /** SYSTEM | CUSTOM */ template_source?: string; /** COUPLED | SEPERATED */ template_type?: string; template_version?: string; deploy_spec?: string; /** Role-specific resource specs. Either `unified` (COUPLED) or `prefill` + `decode` (SEPERATED). */ roles?: { unified?: { model_unit_spec?: string; capacity_unit_per_instance?: number; capacity_unit_init?: number; }; prefill?: { model_unit_spec?: string; capacity_unit_per_instance?: number; capacity_unit_init?: number; }; decode?: { model_unit_spec?: string; capacity_unit_per_instance?: number; capacity_unit_init?: number; }; [k: string]: unknown; }; [k: string]: unknown; } /** POST /api/v1/deployments request body. */ export interface CreateDeploymentRequest { /** Required. The catalog or fine-tuned model identifier. */ model_name: string; /** Optional display name; PTU creation generates one when omitted. */ name?: string; /** Required. Billing plan: mu | cu | ptu | lora. CLI defaults to "lora". */ plan: string; /** Required for PTU creation; distinct from instance billing_method. */ charge_type?: "pre_paid" | "post_paid"; /** PTU performance tier; the service defaults to ptu_fast. */ service_tier?: "ptu_fast" | "ptu_default"; /** Optional ModelCode suffix; generated by the service when omitted. */ suffix?: string; /** Required for prepaid PTU creation; omitted for postpaid. */ pre_paid_info?: PrePaidInfo; /** Required by API even for token-billed (lora) plans where it is ignored — CLI injects 1. */ capacity?: number; /** Deploy spec id (e.g. "MU1", "dps-..."), sent as `deploy_spec` in POST body. */ deploy_spec?: string; /** Required PTU capacity in kTPM; values are forwarded without conversion. */ ptu_capacity?: PtuCapacity; /** * AIGC generation config for fine-tuned Wan video (i2v/kf2v) LoRA deployments. * Ignored by non-video plans. See `AigcConfig`. */ aigc_config?: AigcConfig; /** Future-compat: arbitrary additional fields are forwarded as-is. */ [k: string]: unknown; } /** * AIGC generation config — used when deploying fine-tuned Wan video (i2v/kf2v) * LoRA models. Controls how prompts are applied at inference time: * - use_input_prompt=false: ignore the caller's prompt, use the preset * `prompt` template instead (the common LoRA case). * - use_input_prompt=true: honor the caller's prompt. * `lora_prompt_default` is the default trigger-word phrase appended for the LoRA. */ export interface AigcConfig { use_input_prompt?: boolean; prompt?: string; lora_prompt_default?: string; } /** Legacy PTU input shape, retained for source compatibility. */ export interface PtuCapacity { /** Input capacity in kTPM. */ input_tpm?: number; /** Output capacity in kTPM. */ output_tpm?: number; /** @deprecated Current reservation models do not support separate thinking-output capacity. */ thinking_output_tpm?: number; } /** POST /api/v1/deployments response. */ export interface CreateDeploymentResponse { request_id?: string; output?: Deployment; data?: Deployment; } /** GET /api/v1/deployments response. */ export interface ListDeploymentsResponse { request_id?: string; output?: { deployments?: Deployment[]; total?: number; page_no?: number; page_size?: number; [k: string]: unknown; }; data?: { deployments?: Deployment[]; total?: number; page_no?: number; page_size?: number; [k: string]: unknown; }; } /** GET /api/v1/deployments/{deployed_model} response. */ export interface GetDeploymentResponse { request_id?: string; output?: Deployment; data?: Deployment; } /** GET /api/v1/deployments/{deployed_model}/capacity-instances response. */ export interface ListCapacityInstancesResponse { request_id?: string; output?: { records?: CapacityInstance[]; /** Total record count, not the current page's records. */ items?: number; page?: number; itemsPerPage?: number; pageCount?: number; [key: string]: unknown; }; data?: ListCapacityInstancesResponse["output"]; [key: string]: unknown; } /** GET /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id} response. */ export interface GetCapacityInstanceResponse { request_id?: string; output?: CapacityInstance; data?: CapacityInstance; [key: string]: unknown; } /** GET /api/v1/deployments/{deployed_model}/capacity-operations/{operation_id} response. */ export interface GetCapacityOperationResponse { request_id?: string; output?: CapacityOperation; data?: CapacityOperation; [key: string]: unknown; } /** Instance writes return an operation, including HTTP 200 responses with status FAILED. */ export type CapacityOperationResponse = GetCapacityOperationResponse; /** POST /api/v1/deployments/{deployed_model}/capacity-instances request body. */ export interface CreateCapacityInstanceRequest { billing_method: "PRE_PAY" | "POST_PAY"; ptu_capacity: ReservationCapacity; /** Required for PRE_PAY; omitted for POST_PAY. */ pre_paid_info?: PrePaidInfo; } /** PUT /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id}/scale body. */ export interface ScaleCapacityInstanceRequest { /** Absolute target capacity for this instance, not a delta or deployment total. */ ptu_capacity: ReservationCapacity; /** Omit to reuse saved prepaid information; do not send for postpaid. */ pre_paid_info?: PrePaidInfo; order_type?: "UPGRADE" | "DOWNGRADE"; } /** PUT /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id}/renew body. */ export interface RenewCapacityInstanceRequest { pre_paid_info: PrePaidInfo; /** Required to be true when changing capacity; defaults to false on the service. */ is_change?: boolean; ptu_capacity?: ReservationCapacity; } /** PUT /api/v1/deployments/{deployed_model}/update-overflowstrategy response. */ export type UpdateDeploymentOverflowResponse = GetDeploymentResponse; /** DELETE /api/v1/deployments/{deployed_model} response, including legacy deleted flags. */ export interface DeleteDeploymentResponse { request_id?: string; output?: Deployment & { deleted?: boolean; }; data?: Deployment & { deleted?: boolean; }; } /** GET /api/v1/deployments/models response. */ export interface ListDeployableModelsResponse { request_id?: string; output?: { models?: DeployableModel[]; total?: number; page_no?: number; page_size?: number; [k: string]: unknown; }; data?: { models?: DeployableModel[]; total?: number; page_no?: number; page_size?: number; [k: string]: unknown; }; } /** PUT /api/v1/deployments/{deployed_model}/scale request body. */ export interface ScaleDeploymentRequest { /** New capacity in legacy MU plan units. */ capacity?: number; /** Required for PTU when more than one undeleted instance exists. */ instance_id?: string; /** Absolute PTU target capacity for the selected instance, in kTPM. */ ptu_capacity?: ReservationCapacity; pre_paid_info?: PrePaidInfo; order_type?: "UPGRADE" | "DOWNGRADE"; /** Legacy top-level PTU fields retained for source compatibility. */ input_tpm?: number; output_tpm?: number; [k: string]: unknown; } /** PUT /api/v1/deployments/{deployed_model}/scale response. */ export interface ScaleDeploymentResponse { request_id?: string; output?: Deployment; data?: Deployment; } /** * PUT /api/v1/deployments/{deployed_model} request body. * * Update rate limits — at least one of `rpm_limit` / `tpm_limit` is required. * - rpm_limit: requests per minute * - tpm_limit: tokens per minute */ export interface UpdateDeploymentRequest { rpm_limit?: number; tpm_limit?: number; [k: string]: unknown; } /** PUT /api/v1/deployments/{deployed_model} response. */ export interface UpdateDeploymentResponse { request_id?: string; output?: Deployment; data?: Deployment; } //#endregion //#region src/deploy/api.d.ts /** Caller-owned idempotency key; wrappers never generate keys or retry writes. */ export interface CapacityWriteOptions { requestId?: string; signal?: AbortSignal; } /** POST /api/v1/deployments; initial ModelCode creation has no instance-idempotency guarantee. */ export declare function createDeployment(client: Client, body: CreateDeploymentRequest, signal?: AbortSignal): Promise; export interface ListDeploymentsParams { pageNo?: number; pageSize?: number; plan?: string; signal?: AbortSignal; } /** GET /api/v1/deployments */ export declare function listDeployments(client: Client, params?: ListDeploymentsParams): Promise; /** GET /api/v1/deployments/{deployed_model} */ export declare function getDeployment(client: Client, deployedModel: string, signal?: AbortSignal): Promise; export interface ListCapacityInstancesParams { pageNo?: number; pageSize?: number; includeDeleted?: boolean; statuses?: string[]; chargeTypes?: string[]; signal?: AbortSignal; } /** GET /api/v1/deployments/{deployed_model}/capacity-instances */ export declare function listCapacityInstances(client: Client, code: string, params?: ListCapacityInstancesParams): Promise; /** GET /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id} */ export declare function getCapacityInstance(client: Client, code: string, id: string, signal?: AbortSignal): Promise; /** GET /api/v1/deployments/{deployed_model}/capacity-operations/{operation_id} */ export declare function getCapacityOperation(client: Client, code: string, id: string, signal?: AbortSignal): Promise; /** * POST /api/v1/deployments/{deployed_model}/capacity-instances * All instance writes return operations verbatim; callers must check operation_status, even on HTTP 200. */ export declare function createCapacityInstance(client: Client, code: string, body: CreateCapacityInstanceRequest, options?: CapacityWriteOptions): Promise; /** PUT /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id}/scale */ export declare function scaleCapacityInstance(client: Client, code: string, id: string, body: ScaleCapacityInstanceRequest, options?: CapacityWriteOptions): Promise; /** PUT /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id}/renew */ export declare function renewCapacityInstance(client: Client, code: string, id: string, body: RenewCapacityInstanceRequest, options?: CapacityWriteOptions): Promise; /** DELETE /api/v1/deployments/{deployed_model}/capacity-instances/{instance_id}; no JSON body. */ export declare function deleteCapacityInstance(client: Client, code: string, id: string, options?: CapacityWriteOptions & { reason?: string; }): Promise; /** PUT /api/v1/deployments/{deployed_model}/update-overflowstrategy */ export declare function updateDeploymentOverflow(client: Client, code: string, strategy: "enable" | "disable", signal?: AbortSignal): Promise; /** DELETE /api/v1/deployments/{deployed_model} */ export declare function deleteDeployment(client: Client, deployedModel: string, signal?: AbortSignal): Promise; export interface ListDeployableModelsParams { pageNo?: number; pageSize?: number; /** Catalog version filter, e.g. "v1.0". */ version?: string; /** Source filter: "custom" (fine-tuned outputs) | "public" | …. */ modelSource?: string; signal?: AbortSignal; } /** GET /api/v1/deployments/models */ export declare function listDeployableModels(client: Client, params?: ListDeployableModelsParams): Promise; /** PUT /api/v1/deployments/{deployed_model}/scale */ export declare function scaleDeployment(client: Client, deployedModel: string, body: ScaleDeploymentRequest, signal?: AbortSignal, requestId?: string): Promise; /** * PUT /api/v1/deployments/{deployed_model}/update * * Update rate limits. At least one of `rpm_limit` / `tpm_limit` must be set. */ export declare function updateDeployment(client: Client, deployedModel: string, body: UpdateDeploymentRequest, signal?: AbortSignal): Promise; //#endregion //#region src/deploy/constants.d.ts /** * Deploy-domain constants — billing plans, billing methods and template * charge types. Centralised here so no `deploy` command carries a magic * string for these server-contract values. */ /** Billing plan (`--plan` value, matches the server's deployment plan). */ export declare const DEPLOY_PLAN: { /** Token-billed; the CLI default. */ readonly LORA: "lora"; /** Token-billed, provisioned throughput. */ readonly PTU: "ptu"; /** Model-unit-billed. */ readonly MU: "mu"; }; export type DeployPlan = (typeof DEPLOY_PLAN)[keyof typeof DEPLOY_PLAN]; /** CLI default plan when `--plan` is omitted. */ export declare const DEFAULT_DEPLOY_PLAN: DeployPlan; /** Deployment target modality — fixes the default plan when `--plan` is omitted. */ export type DeployModality = "text" | "audio" | "image"; /** * Default plan per modality when `--plan` is omitted. * * The contract differs by modality (verified against the DashScope docs): * - text / image LoRA outputs deploy Token-billed (`lora`) — the image * fine-tune guide's deploy example uses `plan: "lora"`. * - CosyVoice (audio TTS) outputs deploy model-unit-billed (`mu`) — the * speech-synthesis guide fixes `plan: "mu"` and requires deploy_spec / * capacity / billing_method (all auto-picked by the mu strategy). */ export declare function defaultDeployPlan(modality: DeployModality): DeployPlan; /** Billing method (`billing_method`, plan=mu only). */ export declare const BILLING_METHOD: { /** Post-paid (currently the only server-supported value). */ readonly POST_PAY: "POST_PAY"; /** Pre-paid. */ readonly PRE_PAY: "PRE_PAY"; }; export type BillingMethod = (typeof BILLING_METHOD)[keyof typeof BILLING_METHOD]; /** Default billing method for plan=mu when `--billing-method` is omitted. */ export declare const DEFAULT_BILLING_METHOD: BillingMethod; /** Template charge type (`charge_type`) returned by the deployable-models catalog. */ export declare const CHARGE_TYPE: { readonly POST_PAID: "post_paid"; readonly PRE_PAID: "pre_paid"; }; export type ChargeType = (typeof CHARGE_TYPE)[keyof typeof CHARGE_TYPE]; //#endregion //#region src/deploy/reservation.d.ts /** Shared flags for reservation creation, scaling and renewal; capacity is in kTPM. */ export interface ReservationFlags { inputTpm?: number; outputTpm?: number; duration?: number; autoRenewal?: boolean; autoRenewalDuration?: number; autoRenewalCycle?: string; } /** Validate paired capacity locally; model-specific steps and limits belong to the service. */ export declare function validateReservationCapacity(flags: ReservationFlags, required: boolean): string | undefined; /** Build validated capacity without converting units or dropping zero. */ export declare function buildReservationCapacity(flags: ReservationFlags): ReservationCapacity; export declare function hasPrepaidFlags(flags: ReservationFlags): boolean; /** Validate a complete prepaid block whenever any prepaid field is supplied. */ export declare function validatePrepaidFlags(flags: ReservationFlags, required: boolean): string | undefined; /** Build validated prepaid information, preserving explicit false and omitting absent fields. */ export declare function buildPrepaidInfo(flags: ReservationFlags): PrePaidInfo | undefined; //#endregion //#region src/deploy/plans.d.ts /** Plan-relevant subset of `deploy create` flags (parsed flags satisfy this shape). */ export interface CreatePlanFlags extends ReservationFlags { plan?: string; deploySpec?: string; capacity?: number; billingMethod?: string; chargeType?: string; serviceTier?: string; suffix?: string; thinkingOutputTpm?: number; } export interface PlanContext { client: Client; /** True in --dry-run: strategies must skip side-effecting catalog lookups. */ dryRun: boolean; /** CLI bin name, for usage hints in error messages. */ binName: string; flags: CreatePlanFlags; /** Underlying model identifier (`--model`). */ model: string; /** Optional console display name (`--name`); PTU can use the generated name. */ name?: string; } export interface PlanResolved { /** * Plan-specific fields to merge into the request body. The shared envelope * (`{model_name, name, plan}`) is added by the caller. */ body: Record; } export interface PlanStrategy { /** Plan id, matches `--plan` CLI value. */ name: string; /** Returns an error message when required flags are missing; undefined to pass. */ validateFlags(flags: CreatePlanFlags): string | undefined; /** * Resolve plan-specific bits to a body fragment. May call into the API * (e.g. mu auto-picks a template from the deployable-models catalog). */ resolve(ctx: PlanContext): Promise; } /** * Registry of supported plans. Adding a new plan = one entry here. The * catalog lists some additional plan names (e.g. `ptu_v2`) that are NOT * accepted by the create endpoint, so the dispatcher in the command will * reject anything outside this table with a clear USAGE error. */ export declare const STRATEGIES: Record; /** Throws USAGE if `plan` is not in the strategy table. */ export declare function pickPlanStrategy(plan: string): PlanStrategy; //#endregion //#region src/deploy/lifecycle.d.ts export declare const DEPLOY_START_API = "zeldaEasy.broadscope-platform.modelInstance.startModelService"; export declare const DEPLOY_STOP_API = "zeldaEasy.broadscope-platform.modelInstance.stopModelService"; export declare const DEPLOY_LIST_INDEPENDENT_API = "zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel"; export interface ModelServiceEntry { modelServiceId?: string; deployedModel?: string; deployed_model?: string; status?: string; modelName?: string; model_name?: string; plan?: string; [key: string]: unknown; } /** Start (bring online) a stopped deployment. */ export declare function startModelService(client: Client, modelServiceId: string): Promise>; /** Stop (take offline) a running deployment. Stops billing for mu/ptu plans. */ export declare function stopModelService(client: Client, modelServiceId: string): Promise>; /** * List independently deployed models (console domain). * Used for precheck status verification and ID mapping. * Paginates internally to return all entries. */ export declare function listIndependentDeployedModels(client: Client): Promise; /** * Find a deployment entry by its identifier in the console-domain list. * Matches against `modelServiceId`, `deployedModel`, or `deployed_model`. */ export declare function findDeploymentEntry(entries: ModelServiceEntry[], deployedModel: string): ModelServiceEntry | undefined; //#endregion //#region src/speech/vocabulary.d.ts /** Fixed model id for the hot-word customization endpoint. */ export declare const SPEECH_BIASING_MODEL = "speech-biasing"; interface VocabularyEntry { text: string; weight: number; lang?: string; } interface VocabularyListItem { vocabulary_id?: string; gmt_create?: string; gmt_modified?: string; /** OK | UNDEPLOYED — UNDEPLOYED vocabularies are silently ignored by ASR. */ status?: string; } interface VocabularyEnvelope { request_id?: string; output?: T; usage?: { count?: number; }; } interface VocabularyRequest { model: string; input: Record; } /** Shared request body builder for dry-run and live calls. */ export declare function buildVocabularyRequest(action: string, input: Record): VocabularyRequest; export declare function createVocabulary(client: Client, params: { targetModel: string; prefix: string; vocabulary: VocabularyEntry[]; }, signal?: AbortSignal): Promise>; export declare function listVocabularies(client: Client, params?: { prefix?: string; pageIndex?: number; pageSize?: number; }, signal?: AbortSignal): Promise>; export declare function queryVocabulary(client: Client, vocabularyId: string, signal?: AbortSignal): Promise>; export declare function updateVocabulary(client: Client, vocabularyId: string, vocabulary: VocabularyEntry[], signal?: AbortSignal): Promise>>; export declare function deleteVocabulary(client: Client, vocabularyId: string, signal?: AbortSignal): Promise>>; //#endregion //#region src/speech/vocabulary-input.d.ts /** * Instant hot words for `recognize --vocabulary`. * The API field is a flat word→weight object, so an array is a usage error here. */ export declare function parseInstantVocabulary(raw: string): Record; /** * Vocabulary create/update --words. * Accepts the same word→weight object as recognize, or the API entry array * when per-entry lang is needed. Array form ignores the optional lang param. */ export declare function parseVocabularyEntries(raw: string, lang?: string): VocabularyEntry[]; //#endregion //#region src/types/command-pack.d.ts /** Current Command Pack protocol version understood by this release. */ export declare const COMMAND_PACK_API_VERSION: 1; /** `package.json#bailianCli` metadata for a Command Pack package. */ interface CommandPackMeta { type: "command-pack"; apiVersion: number; /** ESM entry path relative to the package root. */ entry: string; /** Optional minimum compatible bailian-cli version. */ minCliVersion?: string; } /** Explicit credential delegation surface available only to trusted Command Packs. */ interface CommandPackCredentials { apiKey(): ApiKeyCredential; } interface CommandPackOutputOptions { /** Custom text-mode representation; JSON mode always serializes the primary data. */ text?: string; } /** Stable stdout surface supplied by the host. */ interface CommandPackOutput { result(data: unknown, options?: CommandPackOutputOptions): void; line(value: string): void; write(chunk: string): void; } interface CommandPackErrorOptions { hint?: string; cause?: unknown; } /** Host-native semantic error factories; throw the returned Error. */ interface CommandPackErrors { general(message: string, options?: CommandPackErrorOptions): Error; usage(message: string, hint?: string): Error; timeout(message?: string, options?: CommandPackErrorOptions): Error; } /** Stable API 1 execution context. It deliberately contains no raw credentials. */ interface CommandPackContext { identity: Identity; settings: Settings; flags: ParsedFlags; client: Client; output: CommandPackOutput; errors: CommandPackErrors; } /** Privileged context available only when product policy grants raw API-key access. */ type CommandPackApiKeyContext = CommandPackContext & { credentials: CommandPackCredentials; }; /** Command shape exported by an API 1 Command Pack. */ interface CommandPackCommand = CommandPackContext> extends Omit, "run"> { run(ctx: C): Promise; } /** A Command Pack explicitly maps product command paths to command implementations. */ type CommandPack = Record>; //#endregion //#region src/types/security.d.ts /** A capability / protection switch keyed by a stable code. */ interface SecurityToggle { key: string; enabled: boolean; /** Protection entries carry an asset count; absent for some (e.g. external_agent). */ count?: number | null; } /** Detection card: `hit` is the headline number, `scanned` the total. */ interface SecurityScanStat { hit: number | null; scanned: number | null; } /** Protection overview — fixed to the last 24 hours, no request params. */ interface SecurityOverview { capabilities?: SecurityToggle[] | null; protection?: SecurityToggle[] | null; content_safety?: SecurityScanStat | null; file_scan?: SecurityScanStat | null; skill_scan?: SecurityScanStat | null; contentSafety?: SecurityScanStat | null; fileScan?: SecurityScanStat | null; skillScan?: SecurityScanStat | null; } type SecurityRiskLevel = "high" | "medium" | "low"; /** A single alert row from agent_logs. */ interface SecurityAlert { alert_id: string; risk_level?: SecurityRiskLevel | null; risk_name?: string | null; risk_desc?: string | null; asset_type?: string | null; asset_name?: string | null; app_id?: string | null; app_name?: string | null; agent_name?: string | null; status?: string | null; source?: string | null; /** Millisecond timestamp string; some environments return ISO 8601 instead. */ check_time?: string | null; handle_time?: string | null; vendor?: string | null; } /** agent_logs list — cursor paginated; `next_page` is null on the last page. */ interface SecurityAlertList { stats?: { total?: number | null; high?: number | null; medium?: number | null; low?: number | null; } | null; data?: SecurityAlert[] | null; next_page?: string | number | null; } //#endregion //#region src/utils/filename.d.ts export declare function generateFilename(prefix: string, prompt: string): string; //#endregion //#region src/utils/output-dir.d.ts /** * Resolve the output directory for generated files. * * Priority: * 1. User-specified dir (e.g. --out-dir flag) * 2. Config file output_dir * 3. Default: ~/bailian-output/ * * Optionally appends a subdirectory (e.g. 'images', 'videos', 'speech'). * Creates the directory if it doesn't exist. */ export declare function resolveOutputDir(settings: Settings, options?: { flagDir?: string; subDir?: string; }): string; //#endregion //#region src/utils/token.d.ts export declare function maskToken(token: string): string; //#endregion //#region src/utils/object.d.ts /** * Generic object-cleaning utilities. */ /** * Remove all keys whose value is `undefined` from a plain object (in-place). * Returns the same reference for chaining convenience. * * ```ts * const params = { a: 1, b: undefined }; * stripUndefined(params); // { a: 1 } * ``` */ export declare function stripUndefined>(obj: T): T; //#endregion //#region src/utils/fs.d.ts export declare function readTextFromPathOrStdin(path: string): string; //#endregion //#region src/utils/concurrency.d.ts /** * Run async task factories with a bounded concurrency pool. * Returns results in the same order as the input tasks array. */ export declare function runWithConcurrency(tasks: Array<() => Promise>, limit: number): Promise; //#endregion //#region src/utils/boolean-flag.d.ts /** Parse true/false from CLI flags (e.g. `--watermark `). */ export declare function parseBooleanValue(value: unknown, label?: string): boolean; export declare function parseOptionalBooleanValue(value: unknown, label?: string): boolean | undefined; /** * Resolve a tri-state boolean CLI flag (`--name `). * Returns `defaultWhenUnset` when the flag is omitted. */ export declare function resolveBooleanFlag(flagValue: unknown, defaultWhenUnset: boolean | undefined, label?: string): boolean | undefined; /** Resolve `--watermark`; command flag overrides config, then defaults to true. */ export declare function resolveWatermark(flagValue: unknown, configuredValue?: boolean): boolean; //#endregion //#region src/telemetry/event.d.ts interface TrackingEvent { command: string; timestamp: string; durationMs: number; success: boolean; errorMessage?: string; exitCode?: number; httpStatus?: number; requestId?: string; cliVersion: string; nodeVersion: string; os: string; authMethod?: AuthRequirement; params?: Record; } export declare function createTrackingEvent(opts: { command: string; durationMs: number; success: boolean; error?: { message?: string; exitCode?: number; httpStatus?: number; requestId?: string; }; cliVersion: string; authMethod?: AuthRequirement; params?: Record; }): TrackingEvent; //#endregion //#region src/telemetry/sink.d.ts /** * 尽力等待所有在途的埋点发送完成(best-effort)。 * * 1. 先调用 `_sendAll` 排空 tracker 内部的去抖队列,把还卡在 500ms 合并窗口里 * 的事件立刻推上网络。 * 2. 然后用硬超时 race 所有已追踪的 fetch promise。 * * 埋点永远不应阻塞 CLI:调用方应传入较短的超时(例如 1000ms),并始终与超时 * race。错误与超时一律静默吞掉。 */ export declare function flushTelemetry(timeoutMs?: number): Promise; export declare function localSink(event: TrackingEvent): Promise; export declare function remoteSink(event: TrackingEvent): Promise; //#endregion //#region src/telemetry/tracker.d.ts /** 遥测只记录命令声明的鉴权域,不接触具体凭证能力。 */ interface TrackingDeps { identity: Identity; settings: Settings; authMethod?: AuthRequirement; } export declare function trackCommandExecution(deps: TrackingDeps, commandPath: string[], flags: Record, fn: () => Promise): Promise; //#endregion //#region src/advisor/types.d.ts type Modality = "Text" | "Image" | "Video" | "Audio"; type Complexity = "single" | "pipeline"; type Budget = "low" | "medium" | "high"; type ContextNeed = "standard" | "large" | "extra-large"; type QualityPreference = "flagship" | "balanced" | "cost-optimized"; type Capability = "TG" | "Reasoning" | "VU" | "IG" | "VG" | "TTS" | "ASR" | "Realtime-ASR" | "Realtime-Text-to-Speech" | "Realtime-Audio-Translate" | "Realtime-Omni" | "Multimodal-Omni" | "ME" | "TR" | "3D-generation"; type Feature = "function-calling" | "web-search" | "structured-outputs" | "prefix-completion"; type ModelCategory = "Flagship" | "Cost-optimized"; type PreferenceMode = "unconstrained" | "scoped" | "comparison" | "alternative"; interface ModelPreference { mode: PreferenceMode; targets?: string[]; excludes?: string[]; } export declare const Modalities: { readonly Text: "Text"; readonly Image: "Image"; readonly Video: "Video"; readonly Audio: "Audio"; }; export declare const Complexities: { readonly Single: "single"; readonly Pipeline: "pipeline"; }; export declare const Budgets: { readonly Low: "low"; readonly Medium: "medium"; readonly High: "high"; }; export declare const ContextNeeds: { readonly Standard: "standard"; readonly Large: "large"; readonly ExtraLarge: "extra-large"; }; export declare const QualityPreferences: { readonly Flagship: "flagship"; readonly Balanced: "balanced"; readonly CostOptimized: "cost-optimized"; }; export declare const Capabilities: { readonly TG: "TG"; readonly Reasoning: "Reasoning"; readonly VU: "VU"; readonly IG: "IG"; readonly VG: "VG"; readonly TTS: "TTS"; readonly ASR: "ASR"; readonly RealtimeASR: "Realtime-ASR"; readonly RealtimeTTS: "Realtime-Text-to-Speech"; readonly RealtimeAudioTranslate: "Realtime-Audio-Translate"; readonly RealtimeOmni: "Realtime-Omni"; readonly MultimodalOmni: "Multimodal-Omni"; readonly ME: "ME"; readonly TR: "TR"; readonly ThreeDGeneration: "3D-generation"; }; export declare const Features: { readonly FunctionCalling: "function-calling"; readonly WebSearch: "web-search"; readonly StructuredOutputs: "structured-outputs"; readonly PrefixCompletion: "prefix-completion"; }; export declare const ModelCategories: { readonly Flagship: "Flagship"; readonly CostOptimized: "Cost-optimized"; }; interface IntentSegment { step: string; inputModality: Modality[]; outputModality: Modality[]; requiredCapabilities: Capability[]; } interface IntentProfile { complexity: Complexity; segments?: IntentSegment[]; taskSummary: string; scenarioHints: string[]; /** * LLM-refined, self-contained English description of the need, optimized for * semantic matching against model descriptions. Used as the embedding query * for soft-track recall. Empty when intent analysis degrades (recall then * falls back to the raw user query). */ semanticQuery: string; inputModality: Modality[]; outputModality: Modality[]; requiredCapabilities: Capability[]; requiredFeatures: Feature[]; budget: Budget; contextNeed: ContextNeed; qualityPreference: QualityPreference; confidence: number; modelPreference?: ModelPreference; } interface ModelPrice { type: string; unit: string; price: string; } interface QpmLimit { count_limit: number; count_limit_period: number; usage_limit: number; usage_limit_field: string; usage_limit_period: number; } interface ModelProfile { model: string; name: string; description: string; provider: string; capabilities: string[]; features: string[]; contextWindow?: number; maxOutputTokens?: number; docUrl?: string; inferenceMetadata?: { request_modality?: Modality[]; response_modality?: Modality[]; }; shortDescription?: string; category?: ModelCategory; collectionTag?: string; maxInputTokens?: number; prices?: ModelPrice[]; qpmInfo?: Record; versionTag?: string; openSource?: boolean; family?: string; familyName?: string; } interface RecommendedModel { model: string; name: string; reason: string; highlights: string[]; category?: ModelCategory; contextWindow?: number; maxOutputTokens?: number; docUrl?: string; } interface PipelineStep { step: string; recommendations: RecommendedModel[]; warnings?: string[]; } interface SingleResult { type: "single"; recommendations: RecommendedModel[]; } interface PipelineResult { type: "pipeline"; summary: string; steps: PipelineStep[]; } type RecommendResult = SingleResult | PipelineResult; //#endregion //#region src/advisor/cache.d.ts interface GetModelsOptions { onPrepareStart?: () => void; } export declare function getModels(settings: Settings, options?: GetModelsOptions): Promise; //#endregion //#region src/advisor/constants/scoring.d.ts export declare const SEMANTIC_TOP_K = 20; //#endregion //#region src/advisor/intent.d.ts /** * Analyze the user's input to produce an IntentProfile. * * Calls `qwen3.6-flash` via the OpenAI-compatible chat endpoint to extract * structured intent fields: taskSummary, modalities, capabilities, budget, * qualityPreference, modelPreference (mode/targets/excludes), and more. * * On failure, degrades gracefully to DEFAULT_INTENT with confidence 0. */ export declare function analyzeIntent(client: Client, input: string): Promise; //#endregion //#region src/advisor/recall.d.ts interface ScoredCandidate { model: ModelProfile; score: number; /** Normalized [0,1] preference-satisfaction score (capability/feature/context/quality). */ hardScore?: number; /** Cosine similarity [0,1] between the semantic query and the model embedding. */ softScore?: number; } export declare function recallCandidates(models: ModelProfile[], intent: IntentProfile): ScoredCandidate[]; //#endregion //#region src/advisor/recall-semantic.d.ts export declare function isSemanticAvailable(): boolean; export declare function recallSemantic(client: Client, models: ModelProfile[], query: string, topK: number, intent?: IntentProfile): Promise; //#endregion //#region src/advisor/recommend.d.ts interface RecommendOptions { onThinking?: (text: string) => void; onContentStart?: () => void; enableThinking?: boolean; } export declare function buildDocLink(docUrl?: string): string | undefined; export declare function rankModels(client: Client, candidates: ScoredCandidate[], intent: IntentProfile, userInput: string, top: number, options?: RecommendOptions): Promise; //#endregion //#region src/advisor/sync.d.ts /** * Check and sync Wiki data. Runs silently; never throws. * @returns Whether data was actually updated (for testing/debugging) */ export declare function maybeSyncWikiData(): Promise; //#endregion //#region src/advisor/sources/types.d.ts interface ModelSource { name: string; available(): boolean; load(): Promise; } //#endregion //#region src/install/method.d.ts /** How the CLI was installed on this machine. */ type InstallMethod = "binary" | "npm" | "brew" | "winget" | "unknown"; /** Product that currently ships standalone binary artifacts (`bl` / `bailian`). */ export declare const BINARY_PRODUCT_CLIENT_NAME = "bailian-cli"; type InstallMethodIdentity = { clientName: string; }; /** * True when running a Bun-compiled standalone executable * rather than via the Node/npm entry shim. * * Binary entrypoints set `BAILIAN_COMPILED=1` before other code runs. */ export declare function isCompiledBinary(): boolean; /** Infer install method when no marker file / env override is present. */ export declare function detectInstallMethod(): InstallMethod; /** * Read the persisted install method, falling back to detection. * * When `identity` is provided, prefer `install-method.`. * Legacy `~/.bailian/install-method` is only consulted for `bailian-cli` * so other products (e.g. kscli) are not polluted by a shared binary marker. */ export declare function getInstallMethod(identity?: InstallMethodIdentity): InstallMethod; /** * Install method for update / auto-update routing. * Only `bailian-cli` may follow the binary channel; other products always use npm * even if env or a mistaken marker claims `binary`. */ export declare function getUpdateInstallMethod(identity: { clientName: string; npmPackage: string; }): InstallMethod; /** * Persist install method under `~/.bailian/install-method.` (best-effort). * For `bailian-cli`, also write the legacy `install-method` file for older readers. */ export declare function writeInstallMethodSync(method: InstallMethod, identity?: InstallMethodIdentity): void; //#endregion //#region src/install/cdn.d.ts /** * End-user binary download base (OSS). CI publishes release assets and rolling * channel manifests here via the FC release channel * (tools/release/lib/oss-direct-upload.mjs): the runner uploads through * FC-presigned URLs and holds no OSS credentials itself. * * Layout under the base: * v/.zip —— per-version zip (Windows installer, `bl update`, old Unix install.sh) * v/.tar.gz —— unix install.sh default (darwin / linux); same inner binary * SHA256SUMS —— checksums for zip and tar.gz * manifest.json —— stable install/update pointer (rolling-manifest shape) * latest.json —— stable alias; same body as manifest.json * sync-release.json —— official channel/verify rolling pointer (all bailian-cli * channel publishes overwrite this; npm dist-tag is separate) * * Legacy `{name}.json` files may still exist on CDN; install may resolve them, but * release tooling no longer creates per-dist-tag manifests. * * Override with `BAILIAN_CLI_CDN`. */ export declare const DEFAULT_CLI_CDN_BASE = "https://bailian-wiki.oss-cn-hangzhou.aliyuncs.com/release"; /** GitHub Releases base — used when writing manifests attached to gh release assets. */ export declare const GITHUB_RELEASES_BASE = "https://github.com/modelstudioai/cli/releases"; /** User-facing install entry (docs / update hints); asset downloads still use getCliCdnBase(). */ export declare const DEFAULT_INSTALL_SCRIPT_URL = "https://bailian.aliyun.com/cli/install.sh"; export declare const DEFAULT_INSTALL_PS1_URL = "https://bailian.aliyun.com/cli/install.ps1"; export declare function getCliCdnBase(): string; /** * Rolling manifest URL at the CDN base root. * Stable (`latest` / `stable` / empty) → `manifest.json`. * Official verify line → `sync-release.json` (`channel=sync-release`). * Other names still map to `{channel}.json` for backward compatibility only. * All share the same rolling-manifest shape from binary-build. */ export declare function channelManifestUrl(channel?: string): string; /** Immutable per-version asset: `{base}/v{version}/{fileName}`. */ export declare function releaseAssetUrl(version: string, fileName: string): string; /** Platform triple used in asset names: `bl---[.exe]`. */ export declare function detectBinaryPlatform(): { os: string; arch: string; fileSuffix: string; }; /** Release download asset: `bl---.zip`. */ export declare function binaryAssetFileName(version: string, os: string, arch: string, _exe?: boolean): string; /** * Unix install.sh archive: `bl---.tar.gz`. * Windows has no tar.gz (PowerShell Expand-Archive uses zip). */ export declare function binaryTarFileName(version: string, os: string, arch: string): string | undefined; /** Uncompressed binary name inside the zip. */ export declare function binaryInnerFileName(version: string, os: string, arch: string, exe?: boolean): string; //#endregion //#region src/install/unzip-asset.d.ts /** * Extract `entryName` (or the first non-directory entry) from `zipPath` to `destPath`. * Returns the archive entry basename that was extracted. */ export declare function extractZipEntryToFile(zipPath: string, destPath: string, entryName?: string): Promise; //#endregion //#region src/skills/types.d.ts /** * Data structures for the unified skill publishing protocol (symmetric with FC publisher skills-publish.mjs). * * Remote layout (public-read OSS, the sole data source for `bl skill`): * /index.json — skill catalog (SkillsIndex) * //sha256-.tar.br — content-addressed skill object (tar + brotli); * entry.object names the exact file, so index.json is the single atomic commit point. * Legacy fallback: //skill.tar.br (entries without object) * * Local layout: * ~/.bailian/skills// — canonical install directory * ~/.bailian/skills/skill-lock.json — installation fact records (SkillLockFile) */ /** A single skill entry in index.json */ interface SkillIndexEntry { /** Reserved for the skill's own semantic version (x.y.z); not yet populated by the publisher */ version?: string; /** Beijing-time publish timestamp; refreshed whenever content changes — the human-facing release marker */ publishedAt?: string; /** Extracted by the publisher from README.md first paragraph or SKILL.md frontmatter */ description?: string; /** Deterministic content fingerprint; the CLI uses this as the change-detection token (install/outdated) */ contentHash?: string; /** Compression format identifier, currently always "tar.br" */ compression?: string; /** * Content-addressed object file name under //, e.g. "sha256-.tar.br". * Absent on legacy entries — client falls back to the fixed key "skill.tar.br". */ object?: string; } interface SkillsIndex { updatedAt?: string; /** key = skill name (i.e. OSS directory name, download path, local install dir name) */ skills: Record; } /** Installation facts for a single skill in skill-lock.json */ interface SkillLockEntry { /** Content fingerprint at install time; compared against the remote index to detect updates */ contentHash?: string; /** Publish timestamp of the installed revision (for display) */ publishedAt?: string; installedAt: string; /** Reserved: future support for github/gitlab and other sources */ sourceType: "oss"; description?: string; /** Fan-out link/copy paths to each agent; used for precise reclamation on remove */ links?: string[]; } interface SkillLockFile { version: 1; skills: Record; } /** * Skill statuses for list: * installed — lock record exists, dir on disk, content fingerprint matches remote * outdated — lock record exists, dir on disk, remote content fingerprint differs * not-installed — present in remote, absent locally * missing — lock record exists but dir was deleted (reinstall can fix) * untracked — dir on disk but no install record (manually placed or synced by other channels) */ type SkillStatus = "installed" | "outdated" | "not-installed" | "missing" | "untracked"; interface SkillStatusRow { name: string; status: SkillStatus; /** Publish timestamp of the remote revision (or local, for delisted skills) */ publishedAt?: string; description?: string; } //#endregion //#region src/skills/registry.d.ts export declare function getSkillRegistryBaseUrl(): string; /** * Fetch the remote skill index. No local caching — the diff comparison is always * "live remote index vs local skill-lock.json". * Silent background channels (advisor sync) may pass a tighter timeout and attempts=1 * than the interactive defaults. */ export declare function fetchSkillsIndex(timeoutMs?: number, attempts?: number): Promise; /** Resolve which file to download for a skill: content-addressed object, else legacy fixed key */ export declare function resolveAssetFileName(entry?: SkillIndexEntry): string; /** Download the tar.br archive for a single skill (one skill = one GET) */ export declare function downloadSkillAsset(name: string, entry?: SkillIndexEntry, attempts?: number): Promise; //#endregion //#region src/skills/lock.d.ts /** * Local skill state: canonical directory + skill-lock.json. * * The lock only records "installation facts" (version, timestamp, fan-out links) and never * caches the remote index — list/update diffs are always "live remote index vs lock". * Paths follow the config.json directory logic (BAILIAN_CONFIG_DIR can redirect everything). */ export declare function getSkillsDir(): string; export declare function getSkillLockPath(): string; export declare function emptySkillLock(): SkillLockFile; /** * Read installation records. Returns an empty lock when the file is absent (first install), * corrupted, or has an unrecognized version — an empty lock is a valid initial state, not an * error; subsequent install actions will rebuild correct records. */ export declare function readSkillLock(): SkillLockFile; export declare function writeSkillLock(lock: SkillLockFile): void; /** * Merge-update a single skill's installation record (read-modify-write). * Shallow-merges with the existing entry: fields not provided in patch (typically links — * agent fan-out records) are preserved, preventing "install-only, no fan-out" sync channels * like postinstall/advisor from overwriting link records established by bl skill add. */ export declare function upsertSkillLockEntry(name: string, patch: SkillLockEntry): void; //#endregion //#region src/skills/sanitize.d.ts /** * Sanitize a skill name into a safe directory name (semantics aligned with vercel-labs/skills sanitizeName): * skill names come from the remote index (untrusted input) and are interpolated into file paths, so they * must be disinfected first — path separators/drive letters/whitespace/Windows-illegal chars are collapsed * to hyphens, `..` is destroyed, leading/trailing `.-` are stripped. * * `bl skill` uses this as an "equivalence check": if the sanitized name differs from the original, * installation is rejected outright (the publisher already has an isomorphic allowlist; this is client-side defense-in-depth). */ export declare function sanitizeSkillName(name: string): string; /** Whether the skill name is already a safe directory name (unchanged after sanitization) */ export declare function isSafeSkillName(name: string): boolean; //#endregion //#region src/skills/names.d.ts /** * Parse --name: `all` or a comma-separated list of skill names (deduplicated, trimmed). * `all` cannot be mixed with specific names. */ export declare function parseSkillNames(raw: string | undefined, defaultAll: boolean): string[] | "all"; //#endregion //#region src/skills/validate.d.ts /** * Skill validity check (aligned with vercel-labs/skills parseSkillMd semantics): * 1. SKILL.md exists as a regular file at the directory root * 2. frontmatter is valid YAML delimited by `---` * 3. name / description fields exist and are non-empty strings * * Validation happens in the temp dir before writing to canonical — any failure rolls back the entire install. */ interface SkillMeta { name: string; description: string; } export declare function validateSkillDir(dir: string, skillName: string): SkillMeta; //#endregion //#region src/skills/extract.d.ts /** tar 条目路径必须是相对路径且不含 ..,防止 tar-slip 逃逸解包目录 */ export declare function isSafeEntryName(name: string): boolean; /** Brotli decompress + tar-stream extract into destDir (per-entry path safety check). */ export declare function extractTarBr(tarBrBuffer: Buffer, destDir: string): Promise; /** * Recompute the publisher's deterministic content hash over an extracted directory: * regular files sorted by "/"-separated relative path (code-unit order, same as the * publisher's byte-order sort for ASCII paths), sha256 accumulating relPath + bytes. * Symmetric with computeContentHash in FC skills-publish.mjs. */ export declare function computeDirContentHash(dir: string): string; /** * Atomic swap: replace destDir with the extracted content from tmpDir. * tmpDir must be on the same volume as destDir (same parent) for renameSync to be atomic. */ export declare function atomicSwap(tmpDir: string, destDir: string): void; //#endregion //#region src/skills/agents.d.ts /** * Agent fan-out: after a skill lands in the canonical dir (~/.bailian/skills/), * symlink it into each detected AI agent's global skills directory so that a single * install becomes visible across all agents. * * Detection semantics: if the agent's config dir exists → agent is installed → create link; * otherwise skip (never create ~/.xxx dirs that pollute home). When a new agent is installed * later, any subsequent `bl skill add/update` will fill in missing links (self-healing). */ interface AgentTarget { id: string; displayName: string; /** Global directory where this agent reads skills from */ skillsDir: string; /** 任一存在即判定"本机装了该 agent" */ detectDirs: string[]; } /** * Computed on each call (depends on homedir / XDG_CONFIG_HOME / cwd; easy to override in tests). * Registry mirrors the vercel-labs/skills agent list, minus agents that cannot participate in * global symlink fan-out (eve: no global dir, upstream forces direct writes; promptscript: * project-only). Shared-dir agents (Cline/Warp/Zed/Kimi/… read ~/.agents/skills; Amp/Replit * read $XDG_CONFIG_HOME/agents/skills) are folded into the universal pseudo-agents' detectDirs. */ export declare function getAgentTargets(): AgentTarget[]; export declare function detectInstalledAgents(): AgentTarget[]; interface LinkResult { agent: string; path: string; mode: "symlink" | "copy" | "skipped"; reason?: string; } /** * Fan out a skill from canonical to each agent's skills dir. * Stale links created by this tool are rebuilt; recorded copy-fallback artifacts * (real dirs at paths present in recordedLinks) are replaced with fresh content; * any other existing files/dirs are always skipped (never delete user content). * Falls back to copy when symlink fails (e.g. Windows without Developer Mode). */ export declare function linkSkillToAgents(name: string, agents?: AgentTarget[], recordedLinks?: string[]): LinkResult[]; /** * Fan-out workflow: link to agents AND compute the next lock ledger in one step. * Shared by bl skill add/update (fresh install and self-healing) and advisor wiki sync, * so every channel applies the same ledger-merge rules. */ interface FanoutOutcome { results: LinkResult[]; /** Agent ids that actually received a link/copy this run (skipped ones excluded) */ linkedAgents: string[]; /** Next lock links ledger; see merge rules in fanOutSkillToAgents */ links: string[]; } /** * Fan out and merge the resulting paths with the previously recorded ledger: * - effective paths from this run are recorded; * - recorded paths NOT visited this run are preserved (agent uninstalled/undetected — * the artifact may still exist and must stay reclaimable by bl skill remove); * - recorded paths that failed transiently this run are preserved for the same reason; * - recorded paths confirmed foreign this run (unmanaged skip) are dropped — the user * replaced our artifact, and keeping the record would let remove delete user content. */ export declare function fanOutSkillToAgents(name: string, agents?: AgentTarget[], recordedLinks?: string[]): FanoutOutcome; /** * Collect paths that unlinkSkillFromAgents would reclaim (read-only). * Same candidate set and eligibility rules as the mutating unlink: managed * symlinks anywhere under the agent registry (including historical links not * in lock), plus recorded copy-fallback directories. */ export declare function planUnlinkSkillFromAgents(name: string, recordedLinks?: string[]): string[]; /** * Reclaim fan-out artifacts for a skill across all agent dirs. * Symlinks pointing to canonical are removed (including historical links not in lock, * via defensive scan of the full registry); real directories are only removed if recorded * in lock (copy-fallback artifacts). A single failure does not block the rest. */ export declare function unlinkSkillFromAgents(name: string, recordedLinks?: string[]): string[]; //#endregion //#region src/skills/installer.d.ts /** * Skill installer: download → extract to tmpdir (with tar-slip check) → validate SKILL.md → * atomic swap into canonical. Canonical is only touched after all validations pass; on any failure * the current installation is preserved and temp artifacts are cleaned up in finally. */ interface InstalledSkill { name: string; path: string; meta: SkillMeta; } /** Install from an in-memory tar.br archive (the download-and-onwards half of installSkill; test-friendly) */ export declare function installSkillFromBuffer(name: string, tarBrBuffer: Buffer, expectedContentHash?: string): Promise; /** Install a single skill by index entry (download + validate + write to disk) */ export declare function installSkill(name: string, entry: SkillIndexEntry, downloadAttempts?: number): Promise; /** Remove the skill directory under canonical; returns whether it was actually deleted (dir absent → false) */ export declare function removeSkillDir(name: string): boolean; /** * Build a skill-lock entry from an index entry + effective fan-out link paths. * Single source of truth for the "installation fact" shape shared by bl skill add/update, * advisor wiki sync, and any future install channel. */ export declare function buildSkillLockEntry(entry: SkillIndexEntry, links: string[]): SkillLockEntry; interface SkillInstallRecord { /** Ready-to-persist lock entry (links = effective fan-out paths) */ lockEntry: SkillLockEntry; /** Ids of agents that actually received a link/copy (skipped ones excluded) */ linkedAgents: string[]; } /** * Full install workflow for one skill: install into canonical, fan out to agents, and build * the lock entry recording the merged links ledger. Callers decide how to persist the lock * entry (batch writeSkillLock for commands, best-effort upsertSkillLockEntry for silent channels). * recordedLinks = the skill's previously recorded fan-out paths from the lock; lets the * fan-out replace copy-fallback artifacts and keeps unvisited paths reclaimable. * downloadAttempts = registry fetch attempts (undefined → interactive default; silent * background channels pass 1 to fail fast instead of stalling the host command). */ export declare function installSkillWithFanout(name: string, entry: SkillIndexEntry, agents?: AgentTarget[], recordedLinks?: string[], downloadAttempts?: number): Promise; //#endregion //#region src/skills/status.d.ts /** * Three-way reconciliation for list: remote index (live) × skill-lock.json (installation facts) × disk (ground truth). */ /** Scan skill directories under canonical (skipping hidden entries, tmp/backup remnants, and plain files) */ export declare function listSkillDirsOnDisk(): string[]; export declare function computeSkillStatuses(index: SkillsIndex, lock: SkillLockFile, diskNames: string[]): SkillStatusRow[]; //#endregion export type { AcsQueryParams, AcsSignConfig, AgentTarget, AnyCommand, ApiErrorBody, ApiKeyCredential, ApiKeyLoginKind, ApiKeyResolutionSourceSelection, AppCompletionRequest, AppCompletionResponse, AppStreamChunk, AsrApiKind, AsrApiRoute, AsrContextMessage, AsrFlashFamily, AuthPersistPatch, AuthRequirement, AuthState, AuthStore, BailianControlAuth, Budget, BuildAsrFlashRequestOpts, Capability, ChatChoice, ChatMessage, ChatMessageContent, ChatRequest, ChatResponse, ChatResponseFormat, ChatTool, ClientOpenApiJsonOpts, ClientOpenApiQueryOpts, ClientRequestOpts, Command, CommandContext, CommandPack, CommandPackApiKeyContext, CommandPackCommand, CommandPackContext, CommandPackCredentials, CommandPackErrorOptions, CommandPackErrors, CommandPackManager, CommandPackMeta, CommandPackMutationResult, CommandPackOutput, CommandPackOutputOptions, CommandPackReport, CommandRisk, CommandRiskLevel, Complexity, ConfigFile, ConfigProfiles, ConfigStore, ConnectBailianMcpOptions, ConsoleCall, ConsoleCredential, ConsoleGatewayRequest, ConsoleGatewayTarget, ConsoleSite, ContextNeed, CreateUserReqDTO, CredentialSource, DashScopeASRRequest, DashScopeASRTaskResult, DashScopeASRTranscriptionItem, DashScopeAsyncResponse, DashScopeImageRequest, DashScopeImageSyncResponse, DashScopeKnowledgeRetrieveRequest, DashScopeKnowledgeRetrieveResponse, DashScopeTTSRequest, DashScopeTTSResponse, DashScopeTTSStreamChunk, DashScopeTaskResponse, DashScopeVideoEditRequest, DashScopeVideoRefRequest, DashScopeVideoRequest, DataModality, DatasetSchema, FanoutOutcome, Feature, FetchImplementation, FlagDef, FlagsDef, GetModelsOptions, HttpDeps, Identity, ImageApiKind, ImageApiRoute, ImageInputStyle, ImageSizeProfile, InstallMethod, InstallMethodIdentity, InstalledSkill, IntentProfile, IntentSegment, KnowledgeChatContentPart, KnowledgeChatMessage, KnowledgeChatRequest, KnowledgeChatStreamChunk, KnowledgeSearchRequest, KnowledgeSearchResponse, Language, LinkResult, LocalizedText, McpConnectedClient, McpTool, McpToolResult, MemoryAddRequest, MemoryAddResponse, MemoryMessage, MemoryNode, MemoryNodeListResponse, MemoryNodeUpdateRequest, MemorySearchRequest, MemorySearchResponse, Modality, ModelCategory, ModelGroup, ModelGroupItem, ModelGroupParams, ModelGroupResult, ModelListParams, ModelListResult, ModelOfflineInfo, ModelOfflineNotice, ModelPreference, ModelPrice, ModelPriceInfo, ModelProfile, ModelSampleCodeV2, ModelSampleSnippet, ModelSource, OpenApiCredential, OutputFormat, ParsedFlags, PipelineResult, PipelineStep, PredictConfigEntry, PreferenceMode, ProfileAttribute, ProfileSchemaCreateRequest, ProfileSchemaCreateResponse, QpmLimit, QualityPreference, RagAddCategoryData, RagAddCategoryResponse, RagAddConnectorResponse, RagAddFileData, RagAddFileResponse, RagAgentConfig, RagAgentDetail, RagAgentGetData, RagAgentGetResponse, RagAgentListData, RagAgentListResponse, RagAgentMutationData, RagAgentMutationResponse, RagAgentRow, RagBatchUpdateTagResponse, RagCategory, RagChunkListData, RagChunkListResponse, RagChunkNode, RagChunkNodeMetadata, RagConnectorInfo, RagConnectorResponse, RagCreateIndexV2Data, RagCreateIndexV2Response, RagDataCenterFile, RagDeleteFileData, RagDeleteFileResponse, RagDescribeFileResponse, RagGetConnectorResponse, RagIndexFileRow, RagIndexFilesData, RagIndexFilesResponse, RagIndexJobDoc, RagIndexJobStatusData, RagIndexJobStatusResponse, RagIndexListData, RagIndexListResponse, RagIndexRow, RagJobCreateData, RagJobCreateResponse, RagListCategoryData, RagListCategoryResponse, RagListFileData, RagListFileResponse, RagMonitorData, RagMonitorResponse, RagMutationResponse, RagOssImportData, RagOssImportFileResult, RagOssImportResponse, RagQpsMonitorData, RagResponse, RagStorageMonitorData, RagUploadLeaseData, RagUploadLeaseParam, RagUploadLeaseResponse, RecommendOptions, RecommendResult, RecommendedModel, Region, RequestOpts, ResolutionSources, ResponsesOutputContent, ResponsesOutputItem, ResponsesRequest, ResponsesResponse, ResponsesStreamEvent, ScoredCandidate, SecurityAlert, SecurityAlertList, SecurityOverview, SecurityRiskLevel, SecurityScanStat, SecurityToggle, ServerSentEvent, Settings, SingleResult, SkillIndexEntry, SkillInstallRecord, SkillLockEntry, SkillLockFile, SkillMeta, SkillStatus, SkillStatusRow, SkillsIndex, SourceFlags, StreamChoice, StreamChunk, TrackingEvent, TrackingIdentity, TrainingProfile, UserProfileResponse, ValidateOpts, ValidationIssue, ValidationResult, ValidationSeverity, ValidationStats, ValidatorSpec, VocabularyEntry, VocabularyEnvelope, VocabularyListItem, VocabularyRequest };