bailian-cli-core 2.5.1 → 2.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +95 -20
- package/dist/index.mjs +2 -2
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -682,6 +682,10 @@ interface UserProfileValueUpdateRequest {
|
|
|
682
682
|
memory_library_id?: string;
|
|
683
683
|
}
|
|
684
684
|
interface KnowledgeSearchRequest {
|
|
685
|
+
kb_search_configs?: Array<{
|
|
686
|
+
id: string;
|
|
687
|
+
search_filters?: unknown[];
|
|
688
|
+
}>;
|
|
685
689
|
query: string;
|
|
686
690
|
agent_id: string;
|
|
687
691
|
/** "beta" targets the debug draft; a numeric version targets that published version; defaults to the latest published version */
|
|
@@ -706,8 +710,15 @@ interface KnowledgeSearchResponse {
|
|
|
706
710
|
doc_url?: string;
|
|
707
711
|
pipeline_id?: string;
|
|
708
712
|
workspace_id?: string;
|
|
709
|
-
page_number?: number;
|
|
710
|
-
image_url?: string;
|
|
713
|
+
page_number?: number | number[];
|
|
714
|
+
image_url?: string | string[];
|
|
715
|
+
video_url?: string[];
|
|
716
|
+
audio_url?: string[];
|
|
717
|
+
clip_start_time?: number;
|
|
718
|
+
clip_end_time?: number;
|
|
719
|
+
clip_description?: string;
|
|
720
|
+
audio_segments?: Array<Record<string, unknown>>;
|
|
721
|
+
[key: string]: unknown;
|
|
711
722
|
_knowledge_type?: string;
|
|
712
723
|
_citation_index?: number;
|
|
713
724
|
_score?: number;
|
|
@@ -725,16 +736,22 @@ type KnowledgeChatContentPart = {
|
|
|
725
736
|
};
|
|
726
737
|
};
|
|
727
738
|
interface KnowledgeChatMessage {
|
|
728
|
-
role: "user" | "assistant";
|
|
739
|
+
role: "user" | "assistant" | "tool";
|
|
740
|
+
tool_call_id?: string;
|
|
741
|
+
tool_calls?: unknown[];
|
|
742
|
+
[key: string]: unknown;
|
|
729
743
|
content: string | KnowledgeChatContentPart[];
|
|
730
744
|
}
|
|
731
745
|
interface KnowledgeChatRequest {
|
|
732
746
|
input: {
|
|
733
747
|
messages: KnowledgeChatMessage[];
|
|
748
|
+
request_id?: string;
|
|
734
749
|
};
|
|
735
750
|
parameters: {
|
|
736
751
|
agent_options: {
|
|
737
752
|
agent_id: string;
|
|
753
|
+
session_files?: string[];
|
|
754
|
+
enable_cache_control?: boolean;
|
|
738
755
|
/** "beta" targets the debug draft; a numeric version targets that published version; defaults to the latest published version */
|
|
739
756
|
agent_version?: string;
|
|
740
757
|
user?: {
|
|
@@ -746,24 +763,35 @@ interface KnowledgeChatRequest {
|
|
|
746
763
|
stream: boolean;
|
|
747
764
|
}
|
|
748
765
|
interface KnowledgeChatStreamChunk {
|
|
749
|
-
output
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
766
|
+
output?: {
|
|
767
|
+
request_id?: string;
|
|
768
|
+
choices?: Array<{
|
|
769
|
+
message?: {
|
|
770
|
+
role?: string;
|
|
771
|
+
content?: string | KnowledgeChatContentPart[];
|
|
754
772
|
tool_calls?: unknown[];
|
|
773
|
+
additional_kwargs?: {
|
|
774
|
+
extra_json?: Record<string, unknown> | string;
|
|
775
|
+
[key: string]: unknown;
|
|
776
|
+
};
|
|
755
777
|
extra?: {
|
|
756
778
|
group?: string;
|
|
757
779
|
step_change?: string;
|
|
758
780
|
step?: string;
|
|
781
|
+
[key: string]: unknown;
|
|
759
782
|
};
|
|
783
|
+
[key: string]: unknown;
|
|
760
784
|
};
|
|
761
|
-
finish_reason
|
|
785
|
+
finish_reason?: string;
|
|
786
|
+
[key: string]: unknown;
|
|
762
787
|
}>;
|
|
788
|
+
[key: string]: unknown;
|
|
763
789
|
};
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
790
|
+
usage?: Record<string, unknown>;
|
|
791
|
+
code?: string | number;
|
|
792
|
+
message?: string;
|
|
793
|
+
request_id?: string;
|
|
794
|
+
[key: string]: unknown;
|
|
767
795
|
}
|
|
768
796
|
interface DashScopeTTSRequest {
|
|
769
797
|
model: string;
|
|
@@ -918,6 +946,9 @@ interface RagIndexRow {
|
|
|
918
946
|
name: string;
|
|
919
947
|
description?: string;
|
|
920
948
|
dataType?: string;
|
|
949
|
+
knowledgeType?: string | null;
|
|
950
|
+
knowledgeScene?: string | null;
|
|
951
|
+
multimodalEmbeddingModelName?: string | null;
|
|
921
952
|
embeddingModelName?: string;
|
|
922
953
|
embeddingDimension?: number;
|
|
923
954
|
chunkSize?: number;
|
|
@@ -937,7 +968,7 @@ interface RagIndexRow {
|
|
|
937
968
|
}
|
|
938
969
|
interface RagIndexListData {
|
|
939
970
|
rows?: RagIndexRow[];
|
|
940
|
-
|
|
971
|
+
total_count?: number;
|
|
941
972
|
[key: string]: unknown;
|
|
942
973
|
}
|
|
943
974
|
type RagIndexListResponse = RagResponse<RagIndexListData>;
|
|
@@ -957,6 +988,24 @@ interface RagIndexFilesData {
|
|
|
957
988
|
[key: string]: unknown;
|
|
958
989
|
}
|
|
959
990
|
type RagIndexFilesResponse = RagResponse<RagIndexFilesData>;
|
|
991
|
+
/** POST list/index/file/details, preserving the server's mixed field casing. */
|
|
992
|
+
interface RagIndexFileDetailRow extends RagIndexFileRow {
|
|
993
|
+
chunkSize?: number;
|
|
994
|
+
overlapSize?: number;
|
|
995
|
+
separator?: string;
|
|
996
|
+
chunkMode?: string;
|
|
997
|
+
enableHeaders?: boolean;
|
|
998
|
+
categoryId?: string;
|
|
999
|
+
categoryName?: string;
|
|
1000
|
+
tags?: string[];
|
|
1001
|
+
}
|
|
1002
|
+
type RagIndexFileDetailsResponse = RagResponse<{
|
|
1003
|
+
rows?: RagIndexFileDetailRow[];
|
|
1004
|
+
total_count?: number;
|
|
1005
|
+
page_number?: number;
|
|
1006
|
+
page_size?: number;
|
|
1007
|
+
[key: string]: unknown;
|
|
1008
|
+
}>;
|
|
960
1009
|
/**
|
|
961
1010
|
* GET index_job/status (verified against the live API)
|
|
962
1011
|
* Gotcha: the overall job state lives in `ingestion_status` (PENDING/RUNNING/COMPLETED,
|
|
@@ -1713,6 +1762,13 @@ type ParsedFlags<F extends FlagsDef> = { [K in keyof F as IsRequired<F[K]> exten
|
|
|
1713
1762
|
type AuthRequirement = "apiKey" | "console" | "openapi" | "none";
|
|
1714
1763
|
/** 所有命令都可用的全局 flag。 */
|
|
1715
1764
|
export declare const GLOBAL_FLAGS: {
|
|
1765
|
+
introspect: {
|
|
1766
|
+
type: "switch";
|
|
1767
|
+
description: {
|
|
1768
|
+
"en-US": string;
|
|
1769
|
+
"zh-CN": string;
|
|
1770
|
+
};
|
|
1771
|
+
};
|
|
1716
1772
|
output: {
|
|
1717
1773
|
type: "string";
|
|
1718
1774
|
valueHint: string;
|
|
@@ -1887,7 +1943,11 @@ export declare function credentialFlagDefs(cmd: {
|
|
|
1887
1943
|
* resolved configuration surface, `identity` for product identity, and `flags`
|
|
1888
1944
|
* for parsed arguments. Never handle tokens or baseUrl.
|
|
1889
1945
|
*/
|
|
1890
|
-
interface CommandContext<F extends FlagsDef = FlagsDef> {
|
|
1946
|
+
interface CommandContext<F extends FlagsDef = FlagsDef, Prepared = undefined> {
|
|
1947
|
+
/** Resolve a unique registered product path; older hosts may omit this capability. */
|
|
1948
|
+
commandPath?: (command: AnyCommand) => string[] | undefined;
|
|
1949
|
+
/** Read-only preparation result, supplied only after the runtime confirmation gate. */
|
|
1950
|
+
prepared?: Prepared;
|
|
1891
1951
|
/** 静态产品身份(binName/version/npmPackage/clientName)。 */
|
|
1892
1952
|
identity: Identity;
|
|
1893
1953
|
/**
|
|
@@ -1920,8 +1980,20 @@ type CommandRiskLevel = "high";
|
|
|
1920
1980
|
interface CommandRisk {
|
|
1921
1981
|
level: CommandRiskLevel;
|
|
1922
1982
|
message: LocalizedText;
|
|
1983
|
+
reason?: "destructive" | "billing";
|
|
1984
|
+
}
|
|
1985
|
+
interface CommandNotice {
|
|
1986
|
+
code: string;
|
|
1987
|
+
message: LocalizedText;
|
|
1988
|
+
url?: string;
|
|
1989
|
+
}
|
|
1990
|
+
interface CommandPreparation<Prepared> {
|
|
1991
|
+
data: Prepared;
|
|
1992
|
+
preview: unknown;
|
|
1993
|
+
risk: CommandRisk | null;
|
|
1994
|
+
notices: readonly CommandNotice[];
|
|
1923
1995
|
}
|
|
1924
|
-
interface Command<F extends FlagsDef = FlagsDef> {
|
|
1996
|
+
interface Command<F extends FlagsDef = FlagsDef, Prepared = undefined> {
|
|
1925
1997
|
description: LocalizedText;
|
|
1926
1998
|
/** Credential this command requires. See {@link AuthRequirement}. */
|
|
1927
1999
|
auth: AuthRequirement;
|
|
@@ -1932,6 +2004,8 @@ interface Command<F extends FlagsDef = FlagsDef> {
|
|
|
1932
2004
|
* remote request or local write; runtime only owns the confirmation gate.
|
|
1933
2005
|
*/
|
|
1934
2006
|
risk?: CommandRisk;
|
|
2007
|
+
/** Authenticated, read-only planning. Never write files, request leases, or mutate resources. */
|
|
2008
|
+
prepare?: (ctx: CommandContext<F>) => Promise<CommandPreparation<Prepared>>;
|
|
1935
2009
|
/** Usage line arg portion, e.g. "--prompt <text> [flags]". Manually written. */
|
|
1936
2010
|
usageArgs?: string;
|
|
1937
2011
|
/** Example args (without the `<bin> <path>` prefix). */
|
|
@@ -1946,13 +2020,13 @@ interface Command<F extends FlagsDef = FlagsDef> {
|
|
|
1946
2020
|
* May be async for read-only local preflight. Runtime awaits it before auth
|
|
1947
2021
|
* and confirmation. Do not perform remote requests or local writes here.
|
|
1948
2022
|
*/
|
|
1949
|
-
validate?: (flags: ParsedFlags<F>) =>
|
|
1950
|
-
run: (ctx: CommandContext<F>) => Promise<void>;
|
|
2023
|
+
validate?: (flags: ParsedFlags<F>) => LocalizedText | undefined | Promise<LocalizedText | undefined>;
|
|
2024
|
+
run: (ctx: CommandContext<F, Prepared>) => Promise<void>;
|
|
1951
2025
|
}
|
|
1952
2026
|
/** Type-erased command for heterogeneous storage (registry / context). */
|
|
1953
|
-
type AnyCommand = Command<any>;
|
|
2027
|
+
type AnyCommand = Command<any, any>;
|
|
1954
2028
|
/** Identity wrapper whose only job is to infer `F` from `spec.flags`. */
|
|
1955
|
-
export declare function defineCommand<F extends FlagsDef>(spec: Command<F>): Command<F>;
|
|
2029
|
+
export declare function defineCommand<F extends FlagsDef, Prepared = undefined>(spec: Command<F, Prepared>): Command<F, Prepared>;
|
|
1956
2030
|
//#endregion
|
|
1957
2031
|
//#region src/config/loader.d.ts
|
|
1958
2032
|
/**
|
|
@@ -2184,6 +2258,7 @@ export declare const RAG_PATHS: {
|
|
|
2184
2258
|
readonly indexUpdate: "/api/v1/indices/rag/index/update";
|
|
2185
2259
|
readonly indexDelete: "/api/v1/indices/rag/index/delete";
|
|
2186
2260
|
readonly indexMonitor: "/api/v1/indices/rag/index/monitor";
|
|
2261
|
+
readonly indexFileDetails: "/api/v1/indices/rag/list/index/file/details";
|
|
2187
2262
|
readonly indexFiles: "/api/v1/indices/rag/index/files";
|
|
2188
2263
|
readonly indexDeleteFile: "/api/v1/indices/rag/index/delete_file";
|
|
2189
2264
|
readonly indexJobCreate: "/api/v1/indices/rag/index/job/create";
|
|
@@ -5254,4 +5329,4 @@ export declare function installSkillWithFanout(name: string, entry: SkillIndexEn
|
|
|
5254
5329
|
export declare function listSkillDirsOnDisk(): string[];
|
|
5255
5330
|
export declare function computeSkillStatuses(index: SkillsIndex, lock: SkillLockFile, diskNames: string[]): SkillStatusRow[];
|
|
5256
5331
|
//#endregion
|
|
5257
|
-
export type { AcsQueryParams, AcsSignConfig, AgentTarget, AnyCommand, ApiErrorBody, ApiKeyCredential, ApiKeyLoginKind, ApiKeyResolutionSourceSelection, AppCompletionRequest, AppCompletionResponse, AppStreamChunk, AsrApiKind, AsrApiRoute, AsrContextMessage, AsrFlashFamily, AuthPersistPatch, AuthRequirement, AuthState, AuthStore, BailianControlAuth, Budget, BuildAsrFlashRequestOpts, CallerAttribution, 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, 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, MemoryAddAsyncResponse, MemoryAddRequest, MemoryContentPart, MemoryEvent, MemoryEventResourceType, MemoryEventResponse, MemoryEventResult, MemoryEventStatus, MemoryExtractScene, MemoryMessage, MemoryNode, MemoryNodeDetailResponse, MemoryNodeListResponse, MemoryNodeUpdateRequest, MemoryPlanVersion, MemorySearchRequest, MemorySearchResponse, MemorySkillExportResponse, MemoryToolCall, MemoryType, 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, ProfileSchemaAttribute, ProfileSchemaAttributeOperation, ProfileSchemaCreateRequest, ProfileSchemaCreateResponse, ProfileSchemaDetailResponse, ProfileSchemaListResponse, ProfileSchemaSummary, ProfileSchemaUpdateRequest, 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, TrackingDeps, TrackingEvent, TrackingIdentity, TrainingProfile, UserProfileAttribute, UserProfileResponse, UserProfileValueItem, UserProfileValueUpdateRequest, ValidateOpts, ValidationIssue, ValidationResult, ValidationSeverity, ValidationStats, ValidatorSpec, VocabularyEntry, VocabularyEnvelope, VocabularyListItem, VocabularyRequest };
|
|
5332
|
+
export type { AcsQueryParams, AcsSignConfig, AgentTarget, AnyCommand, ApiErrorBody, ApiKeyCredential, ApiKeyLoginKind, ApiKeyResolutionSourceSelection, AppCompletionRequest, AppCompletionResponse, AppStreamChunk, AsrApiKind, AsrApiRoute, AsrContextMessage, AsrFlashFamily, AuthPersistPatch, AuthRequirement, AuthState, AuthStore, BailianControlAuth, Budget, BuildAsrFlashRequestOpts, CallerAttribution, Capability, ChatChoice, ChatMessage, ChatMessageContent, ChatRequest, ChatResponse, ChatResponseFormat, ChatTool, ClientOpenApiJsonOpts, ClientOpenApiQueryOpts, ClientRequestOpts, Command, CommandContext, CommandNotice, CommandPack, CommandPackApiKeyContext, CommandPackCommand, CommandPackContext, CommandPackCredentials, CommandPackErrorOptions, CommandPackErrors, CommandPackManager, CommandPackMeta, CommandPackMutationResult, CommandPackOutput, CommandPackOutputOptions, CommandPackReport, CommandPreparation, CommandRisk, CommandRiskLevel, Complexity, ConfigFile, ConfigProfiles, ConfigStore, ConnectBailianMcpOptions, ConsoleCall, ConsoleCredential, ConsoleGatewayRequest, ConsoleGatewayTarget, ConsoleSite, ContextNeed, CreateUserReqDTO, CredentialSource, DashScopeASRRequest, DashScopeASRTaskResult, DashScopeASRTranscriptionItem, DashScopeAsyncResponse, DashScopeImageRequest, DashScopeImageSyncResponse, 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, MemoryAddAsyncResponse, MemoryAddRequest, MemoryContentPart, MemoryEvent, MemoryEventResourceType, MemoryEventResponse, MemoryEventResult, MemoryEventStatus, MemoryExtractScene, MemoryMessage, MemoryNode, MemoryNodeDetailResponse, MemoryNodeListResponse, MemoryNodeUpdateRequest, MemoryPlanVersion, MemorySearchRequest, MemorySearchResponse, MemorySkillExportResponse, MemoryToolCall, MemoryType, 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, ProfileSchemaAttribute, ProfileSchemaAttributeOperation, ProfileSchemaCreateRequest, ProfileSchemaCreateResponse, ProfileSchemaDetailResponse, ProfileSchemaListResponse, ProfileSchemaSummary, ProfileSchemaUpdateRequest, 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, RagIndexFileDetailRow, RagIndexFileDetailsResponse, 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, TrackingDeps, TrackingEvent, TrackingIdentity, TrainingProfile, UserProfileAttribute, UserProfileResponse, UserProfileValueItem, UserProfileValueUpdateRequest, ValidateOpts, ValidationIssue, ValidationResult, ValidationSeverity, ValidationStats, ValidatorSpec, VocabularyEntry, VocabularyEnvelope, VocabularyListItem, VocabularyRequest };
|
package/dist/index.mjs
CHANGED
|
@@ -9,7 +9,7 @@ import{createRequire as e}from"node:module";import{appendFileSync as t,createRea
|
|
|
9
9
|
`).replace(/\r/g,`
|
|
10
10
|
`).split(`
|
|
11
11
|
`);r=t.pop()??``;for(let n of t){let t=bn(n,e,i);e=t.event,t.completed&&(yield t.completed)}}break}if(r+=n.decode(o,{stream:!0}),r.length>i)throw new P(`SSE stream exceeded the maximum buffer size.`,N.GENERAL);let{lines:s,rest:c}=yn(r);r=c;for(let t of s){let n=bn(t,e,i);e=n.event,n.completed&&(yield n.completed)}}r.length>0&&(e=bn(r,e,i).event),e.data!==void 0&&(yield{data:e.data,event:e.event,id:e.id})}finally{await t.cancel().catch(()=>{}),t.releaseLock()}}function Sn(e){return String(e)}var Cn=class{sseUrl;messageUrl;nextId=1;deps;authToken;abortController;pending=/* @__PURE__ */ new Map;endpointReady;resolveEndpoint;rejectEndpoint;closed=!1;streamEnded=!1;constructor(e,t,n){this.deps=e,this.sseUrl=t,this.authToken=n,this.endpointReady=new Promise((e,t)=>{this.resolveEndpoint=e,this.rejectEndpoint=t})}async initialize(){if(!this.authToken)throw new P(`This command needs a model-domain API key.`,N.AUTH);await this.openSse();let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP SSE] Session initialized`),console.error(`[MCP SSE] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}close(){this.closed||(this.closed=!0,this.abortController?.abort(),this.failPending(new P(`MCP SSE session closed.`,N.GENERAL)),this.messageUrl=void 0)}failPending(e){for(let[,t]of this.pending)t.reject(e);this.pending.clear()}markStreamEnded(e){this.streamEnded=!0,this.messageUrl=void 0,this.failPending(e)}async openSse(){if(this.abortController)return;this.abortController=new AbortController;let e=this.deps.settings.timeout*1e3,t=!1,n=setTimeout(()=>{t=!0,this.abortController?.abort()},e),r={Accept:`text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(r.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&console.error(`> GET ${this.sseUrl}`);let i;try{i=await fetch(this.sseUrl,{method:`GET`,headers:r,signal:this.abortController.signal})}catch(e){throw clearTimeout(n),this.abortController=void 0,this.closed?new P(`MCP SSE session closed.`,N.GENERAL):t?new P(`MCP SSE timed out waiting for response headers.`,N.TIMEOUT):e}if(this.deps.settings.verbose&&console.error(`< ${i.status} ${i.statusText}`),!i.ok){let e=`MCP request failed: ${i.status} ${i.statusText}`;try{let t=await i.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(r){throw clearTimeout(n),this.abortController=void 0,this.closed?new P(`MCP SSE session closed.`,N.GENERAL):t?new P(`MCP SSE timed out reading error response body.`,N.TIMEOUT):new P(e,N.GENERAL,void 0,{cause:r})}throw clearTimeout(n),this.abortController=void 0,new P(e,N.GENERAL)}clearTimeout(n),this.consumeSse(i).catch(e=>{if(this.closed)return;let t=e instanceof P?e:new P(`MCP SSE stream failed: ${e instanceof Error?e.message:String(e)}`,N.GENERAL);this.rejectEndpoint?.(t),this.streamEnded||this.markStreamEnded(t)});let a=Tn(e,`MCP SSE timed out waiting for endpoint event.`);try{await Promise.race([this.endpointReady,a.promise])}finally{a.cancel()}}async consumeSse(e){for await(let t of xn(e)){if(this.closed)break;if(t.event===`endpoint`){let e=t.data.trim();if(!e)continue;this.messageUrl=wn(this.sseUrl,e),this.resolveEndpoint?.(),this.resolveEndpoint=void 0,this.rejectEndpoint=void 0;continue}if(t.event===`message`||t.event===void 0){let e;try{e=JSON.parse(t.data)}catch{continue}if(typeof e.id!=`number`&&typeof e.id!=`string`)continue;let n=Sn(e.id),r=this.pending.get(n);if(!r)continue;this.pending.delete(n),r.resolve(e)}}if(!this.closed){if(!this.messageUrl){let e=new P(`MCP SSE stream ended before endpoint event.`,N.GENERAL);throw this.rejectEndpoint?.(e),e}this.markStreamEnded(new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL))}}async rpc(e,t){if(this.closed||this.streamEnded)throw new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL);let n=this.nextId++,r=Sn(n),i={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},a=this.deps.settings.timeout*1e3,o=new Promise((e,t)=>{this.pending.set(r,{resolve:e,reject:t})});o.catch(()=>void 0);let s=Tn(a,`MCP SSE timed out waiting for response to ${e}.`);try{if(await this.postMessage(i),this.closed||this.streamEnded)throw new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL);let e=await Promise.race([o,s.promise]);if(e.error)throw new P(`MCP error (${e.error.code}): ${e.error.message}`,N.GENERAL);return e.result}catch(e){throw this.pending.delete(r),e}finally{s.cancel()}}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.postMessage(n)}async postMessage(e){if(this.closed||this.streamEnded)throw new P(`MCP SSE stream ended unexpectedly.`,N.GENERAL);if(!this.messageUrl)throw new P(`MCP SSE message endpoint is not ready.`,N.GENERAL);let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.deps.settings.verbose&&(console.error(`> POST ${this.messageUrl}`),console.error(`> Method: ${e.method}`));let n=En(this.deps.settings.timeout*1e3,this.abortController?.signal),r;try{try{r=await fetch(this.messageUrl,{method:`POST`,headers:t,body:JSON.stringify(e),signal:n.signal})}catch(e){throw this.closed?new P(`MCP SSE session closed.`,N.GENERAL):e}if(this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch(t){throw this.closed?new P(`MCP SSE session closed.`,N.GENERAL):n.timedOut?new P(`MCP SSE timed out reading error response body.`,N.TIMEOUT):new P(e,N.GENERAL,void 0,{cause:t})}throw new P(e,N.GENERAL)}}finally{n.cleanup()}}};function wn(e,t){let n,r;try{r=new URL(e),n=new URL(t,e)}catch{throw new P(`MCP SSE endpoint is not a valid URL: ${t}`,N.GENERAL)}if(n.origin!==r.origin)throw new P(`MCP SSE endpoint origin mismatch: expected ${r.origin}, got ${n.origin}`,N.GENERAL);return n.toString()}function Tn(e,t){let n,r=new Promise((r,i)=>{n=setTimeout(()=>{n=void 0,i(new P(t,N.TIMEOUT))},e)});return r.catch(()=>void 0),{promise:r,cancel:()=>{n!==void 0&&(clearTimeout(n),n=void 0)}}}function En(e,t){let n=new AbortController,r={timedOut:!1},i=setTimeout(()=>{r.timedOut=!0,n.abort()},e),a=()=>n.abort(t?.reason),o=()=>{clearTimeout(i),t?.removeEventListener(`abort`,a)};return t?.aborted?a():t?.addEventListener(`abort`,a,{once:!0}),n.signal.addEventListener(`abort`,o,{once:!0}),{signal:n.signal,cleanup:o,get timedOut(){return r.timedOut}}}function Dn(e){return`/api/v1/mcps/${e}/mcp`}function On(e){return`/api/v1/mcps/${e}/sse`}function kn(e){return e instanceof P&&/^MCP request failed:\s*405\b/i.test(e.message)}function An(e){return e instanceof P&&/^MCP request failed:\s*(405|404)\b/i.test(e.message)}async function jn(e){let{deps:t,authToken:n,httpUrl:r,sseUrl:i,serverCode:a,urlOverride:o}=e;if(o){let e=new Mn(t,o,n);try{return await e.initialize(),{client:e,url:o}}catch(e){if(!An(e))throw e}let r=new Cn(t,o,n);try{return await r.initialize(),{client:r,url:o}}catch(e){throw r.close(),e}}let s=new Mn(t,r,n);try{return await s.initialize(),{client:s,url:r}}catch(e){if(!kn(e)||a===`WebSearch`)throw e}let c=new Cn(t,i,n);try{return await c.initialize(),{client:c,url:i}}catch(e){throw c.close(),e}}var Mn=class{url;sessionId;nextId=1;deps;authToken;constructor(e,t,n){this.deps=e,this.url=t,this.authToken=n}async initialize(){if(!this.authToken)throw new P(`This command needs a model-domain API key.`,N.AUTH);let e=await this.rpc(`initialize`,{protocolVersion:`2025-03-26`,capabilities:{},clientInfo:{name:this.deps.identity.clientName,version:this.deps.identity.version}});this.deps.settings.verbose&&(console.error(`[MCP] Session initialized: ${this.sessionId??`no session`}`),console.error(`[MCP] Server: ${JSON.stringify(e)}`)),await this.notify(`notifications/initialized`)}async listTools(){return(await this.rpc(`tools/list`)).tools||[]}async callTool(e,t){return await this.rpc(`tools/call`,{name:e,arguments:t})}async rpc(e,t){let n=this.nextId++,r={jsonrpc:`2.0`,id:n,method:e,...t?{params:t}:{}},i=await this.send(r),a=await this.readJsonRpcResponse(i,n);if(a.error)throw new P(`MCP error (${a.error.code}): ${a.error.message}`,N.GENERAL);return a.result}async notify(e,t){let n={jsonrpc:`2.0`,method:e,...t?{params:t}:{}};await this.send(n)}async readJsonRpcResponse(e,t){return(e.headers.get(`content-type`)||``).includes(`text/event-stream`)?await this.readJsonRpcFromSse(e,t):await e.json()}async readJsonRpcFromSse(e,t){let n=String(t);for await(let t of xn(e)){if(t.event&&t.event!==`message`)continue;let e;try{e=JSON.parse(t.data)}catch{continue}if(e.id!=null&&String(e.id)===n)return e}throw new P(`MCP SSE response stream ended without a matching JSON-RPC response.`,N.GENERAL)}async send(e){let t={"Content-Type":`application/json`,Accept:`application/json, text/event-stream`,"User-Agent":`${this.deps.identity.clientName}/${this.deps.identity.version}`,...z(this.deps.identity)};this.authToken&&(t.Authorization=`Bearer ${this.authToken}`),this.sessionId&&(t[`Mcp-Session-Id`]=this.sessionId),this.deps.settings.verbose&&(console.error(`> POST ${this.url}`),console.error(`> Method: ${e.method}`));let n=this.deps.settings.timeout*1e3,r=await fetch(this.url,{method:`POST`,headers:t,body:JSON.stringify(e),signal:AbortSignal.timeout(n)});this.deps.settings.verbose&&console.error(`< ${r.status} ${r.statusText}`);let i=r.headers.get(`Mcp-Session-Id`)||r.headers.get(`mcp-session-id`);if(i&&(this.sessionId=i),!r.ok){let e=`MCP request failed: ${r.status} ${r.statusText}`;try{let t=await r.text();t&&(e+=` - ${t.slice(0,500)}`)}catch{}throw new P(e,N.GENERAL)}return r}},Nn=class{deps;constructor(e){this.deps=e}get http(){return{identity:this.deps.identity,settings:this.deps.settings}}requireApi(){if(!this.deps.apiCred)throw new P(`This command needs a model-domain API key.`,N.AUTH);return this.deps.apiCred}requireOpenApi(){if(!this.deps.openApiCred)throw new P(`This command needs Alibaba Cloud OpenAPI AK/SK credentials.`,N.AUTH);return this.deps.openApiCred}get baseUrl(){return this.deps.apiCred?.baseUrl??this.deps.baseUrl}exportApiCredential(){return this.deps.apiCred}bailianMcpRegistrationHeaders(){return{Authorization:`Bearer ${this.requireApi().token}`,...z(this.deps.identity)}}url(e,t){return(this.deps.baseUrlIsDefault&&t?t():this.baseUrl)+e}toOpts({path:e,...t}){let n=this.requireApi();return{...t,url:/^https?:\/\//.test(e)?e:n.baseUrl+e,headers:{...t.headers,Authorization:`Bearer ${n.token}`}}}request(e){return Qt(this.http,this.toOpts(e))}requestJson(e){return nn(this.http,this.toOpts(e))}uploadFile(e,t,n={}){return gn(e)?_n(e,this.requireApi().token,t,{...n,identity:this.deps.identity,timeout:this.deps.settings.timeout}):Promise.resolve(e)}resolveImageInput(e,t,n={}){return gn(e)?this.usesTokenPlanEndpoint()?Promise.resolve(pn(e)):this.uploadFile(e,t,{signal:n.signal}):Promise.resolve(e)}usesTokenPlanEndpoint(){try{return/^token-plan\.[a-z0-9-]+\.maas\.aliyuncs\.com$/i.test(new URL(this.baseUrl).hostname)}catch{return!1}}mcp(e){let t=/^https?:\/\//.test(e)?e:this.requireApi().baseUrl+e;return new Mn(this.http,t,this.deps.apiCred?.token)}connectBailianMcp(e,t){return this.requireApi(),jn({deps:this.http,authToken:this.deps.apiCred?.token,httpUrl:this.url(Dn(e)),sseUrl:this.url(On(e)),serverCode:e,urlOverride:t})}async console(e,t){if(!this.deps.consoleCred)throw new P(`This command needs a console access token.`,N.AUTH);let n={api:e,data:t},{timeout:r}=this.deps.settings;try{return await Wt(this.deps.consoleCred,r,n,this.deps.settings)}catch(e){if(!(e instanceof P)||e.exitCode!==N.AUTH||!e.message.includes(`not logged in`))throw e;let t=this.deps.consoleCred,i,a=await Rn({identity:this.deps.identity,settings:{...this.deps.settings,consoleRegion:t.region,consoleSite:t.site,consoleSwitchAgent:t.switchAgent},baseUrl:this.deps.baseUrl,validateToken:async e=>{i=await Wt({...t,token:e},r,n,this.deps.settings)}});if(!a)throw e;return this.deps.consoleCred={...t,token:a},i}}openApiQueryJson(e){return this.openApiJson(e)}async openApiJson(e){let t=this.requireOpenApi(),n=e.body===void 0?``:JSON.stringify(e.body),r=e.queryParams?rn(e.queryParams):``,i=`https://${e.host}${e.path}${r?`?${r}`:``}`,a=an({accessKeyId:t.accessKeyId,accessKeySecret:t.accessKeySecret,securityToken:t.securityToken,action:e.action,version:e.version,body:n,host:e.host,pathname:e.path,method:e.method,queryString:r});this.deps.settings.verbose&&(process.stderr.write(`> ${e.method} ${i}\n`),process.stderr.write(`> x-acs-action: ${e.action} (version ${e.version})\n`),process.stderr.write(`> AK: ${Gt(t.accessKeyId)}\n`),t.securityToken&&process.stderr.write(`> STS token: ${Gt(t.securityToken)}\n`),r&&process.stderr.write(`> query: ${r}\n`),n&&process.stderr.write(`> body: ${n}\n`));let o=this.deps.settings.timeout*1e3,s=await fetch(i,{method:e.method,headers:{...a,...z(this.deps.identity)},body:n||void 0,signal:AbortSignal.timeout(o)}),c=await s.text();this.deps.settings.verbose&&(process.stderr.write(`< ${s.status} ${s.statusText}\n`),process.stderr.write(`< ${c}\n`));let l;try{l=JSON.parse(c)}catch{throw new P(`${s.status} ${s.statusText} - ${c.slice(0,500)}`,N.GENERAL)}if(!s.ok||l.Success===!1)throw new P(`${l.Code||s.status} - ${l.Message||s.statusText}`,N.GENERAL);return l}};const Pn=/* @__PURE__ */ new Map([[`cn-beijing`,`modelstudio.cn-beijing.aliyuncs.com`],[`ap-southeast-1`,`modelstudio.ap-southeast-1.aliyuncs.com`]]);function Fn(e,t){let n=e.consoleRegion;if(!n){let e;try{e=new URL(t).hostname}catch{}n=e===`dashscope.aliyuncs.com`?`cn-beijing`:e===`dashscope-intl.aliyuncs.com`?`ap-southeast-1`:e?.match(/^[a-z0-9-]+\.(cn-beijing|ap-southeast-1)\.maas\.aliyuncs\.com$/)?.[1]}if(!n||!Pn.has(n))throw new P(`Cannot resolve a supported CLI token region. / 无法确定受支持的 CLI token 地域。`,N.USAGE,`Set console_region to cn-beijing or ap-southeast-1. / 请配置 console_region 为 cn-beijing 或 ap-southeast-1。`);return{region:n,site:e.consoleSite??`domestic`,switchAgent:e.consoleSwitchAgent}}async function In(e,t){let n=await Wt(e,t.timeout,{api:`zeldaEasy.cornerstone-portal.cs-console.loginInfo`,data:{}},t);if(n?.data?.success!==!0)throw new P(`Console token validation did not return success. / 控制台 token 校验未返回成功结果。`,N.GENERAL,void 0,{rawResponse:JSON.stringify(n)})}async function Ln(e){let{identity:t,settings:n,baseUrl:r,accessKeyId:i,accessKeySecret:a,securityToken:o}=e,s=new Nn({identity:t,settings:n,baseUrl:r,openApiCred:{accessKeyId:i,accessKeySecret:a,securityToken:o,source:`flag`}}),c=Fn(n,r),l=Pn.get(c.region),u=await s.openApiQueryJson({host:l,path:`/modelstudio/cli/generateAccessToken`,action:`GenerateCLIAccessToken`,version:`2026-02-10`,method:`POST`,queryParams:{}});if(typeof u.cliAccessToken!=`string`||!u.cliAccessToken.trim())throw new P(`CLI token response is missing cliAccessToken. / CLI token 响应缺少有效的 cliAccessToken。`,N.GENERAL);return{...u,cliAccessToken:u.cliAccessToken.trim()}}async function Rn(e){let t=e.settings.configName,n=R(t),r=n.access_key_id,i=n.access_key_secret;if(!r||!i)return null;e.settings.verbose&&process.stderr.write(`Refreshing access token...
|
|
12
|
-
`);let a=(await Ln({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,accessKeyId:r,accessKeySecret:i,securityToken:n.security_token})).cliAccessToken;e.validateToken?await e.validateToken(a):await In({...Fn(e.settings,e.baseUrl),token:a},e.settings);let o=R(t);return o.access_token=a,await Ct(o,t),a}function zn(e,t){if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new F(`Workspace ID must contain only letters, digits, hyphens or underscores. / Workspace ID 只能包含字母、数字、连字符或下划线。`);return`https://${e}.cn-beijing.maas.aliyuncs.com${t}`}function Bn(){return`/compatible-mode/v1/chat/completions`}function Vn(){return`/compatible-mode/v1/responses`}function Hn(){return`/compatible-mode/v1/systemone`}function Un(){return`/api/v1/services/aigc/image-generation/generation`}function Wn(){return`/api/v1/services/aigc/multimodal-generation/generation`}function Gn(){return`/api/v1/services/aigc/text2image/image-synthesis`}function Kn(){return`/api/v1/services/aigc/image2image/image-synthesis`}function qn(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function Jn(){return`/api/v1/services/aigc/image2video/video-synthesis`}function Yn(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function Xn(){return`/api/v1/models/limits`}function Zn(){return`/api/v1/models/permissions`}function Qn(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function $n(e,t){return zn(e,t)}function er(){return`/api/v2/apps/memory/add-async`}function tr(e){return`/api/v2/apps/memory/events/${encodeURIComponent(e)}`}function nr(){return`/api/v2/apps/memory/memory_nodes/search`}function rr(){return`/api/v2/apps/memory/memory_nodes`}function ir(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function ar(e){return`/api/v2/apps/memory/skill/export/${encodeURIComponent(e)}`}function or(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function sr(){return`/api/v1/services/audio/asr/transcription`}function cr(){return`/api/v1/services/audio/asr/customization`}function lr(){return`/api/v2/apps/memory/profile_schemas`}function ur(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}`}function dr(e){return`${ur(e)}/user_profile`}function fr(e){return`${ur(e)}/profile_values`}function pr(e,t=`cn-beijing`){return`https://${e}.${t}.maas.aliyuncs.com`}function mr(e){return zn(e,`/api/v1/indices/knowledge/search`)}function hr(e){return zn(e,`/api/v2/apps/knowledge/chat`)}function gr(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}const _r=`/api/v1/agentstudio/security`;function vr(e){return`${e}${_r}/overview`}function yr(e){return`${e}${_r}/agent_logs`}function br(){return`/api/v1/mcps/WebSearch/mcp`}function xr(){return`/compatible-mode/v1/files`}function Sr(){return`/api/v1/files`}function Cr(e){return`/api/v1/files/${encodeURIComponent(e)}`}function wr(){return`/api/v1/fine-tunes`}function Tr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function Er(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Dr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function Or(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function kr(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function Ar(){return`/api/v1/fine-tunes/compress/templates`}function jr(){return`/api/v1/fine-tunes/compress/jobs`}function Mr(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}`}function Nr(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/cancel`}function Pr(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/logs`}function Fr(){return`/api/v1/deployments`}function Ir(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function Lr(e){return`${Ir(e)}/capacity-instances`}function Rr(e,t){return`${Lr(e)}/${encodeURIComponent(t)}`}function zr(e,t){return`${Rr(e,t)}/scale`}function Br(e,t){return`${Rr(e,t)}/renew`}function Vr(e){return`${Ir(e)}/update-overflowstrategy`}function Hr(e,t){return`${Ir(e)}/capacity-operations/${encodeURIComponent(t)}`}function Ur(e){return`${Ir(e)}/scale`}function Wr(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function Gr(){return`/api/v1/deployments/models`}function Kr(e,t){return zn(e,t)}function qr(){return`/api/v1/agentstudio/files`}function Jr(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}function Yr(e){return`/api/v1/agentstudio/sandbox${e}`}function Xr(e,t){return Jr(e)+Yr(t)}const Zr={sandboxes:`/sandboxes`,sandboxList:`/v2/sandboxes`,templates:`/templates`,templateCreate:`/v3/templates`,templateList:`/v2/templates`};function Qr(e){return`${Zr.sandboxes}/${encodeURIComponent(e)}`}function $r(e,t){return`${Qr(e)}/${t}`}function ei(e){return`${Zr.templates}/${encodeURIComponent(e)}`}function ti(e,t){return`${ei(e)}/builds/${encodeURIComponent(t)}/status`}const ni={indexList:`/api/v1/indices/rag/index/list`,indexCreateV2:`/api/v1/indices/rag/index/create_v2`,indexUpdate:`/api/v1/indices/rag/index/update`,indexDelete:`/api/v1/indices/rag/index/delete`,indexMonitor:`/api/v1/indices/rag/index/monitor`,indexFiles:`/api/v1/indices/rag/index/files`,indexDeleteFile:`/api/v1/indices/rag/index/delete_file`,indexJobCreate:`/api/v1/indices/rag/index/job/create`,indexJobStatus:`/api/v1/indices/rag/index_job/status`,chunkList:`/api/v1/indices/rag/index/chunklist`,chunkCreate:`/api/v1/indices/rag/index/chunk/create`,chunkUpdate:`/api/v1/indices/rag/index/chunk/update`,chunkDelete:`/api/v1/indices/rag/index/chunk/delete`,agentList:`/api/v1/indices/rag/app/list`,agentGet:`/api/v1/indices/rag/app/get`,agentCreate:`/api/v1/indices/rag/app/create`,agentUpdate:`/api/v1/indices/rag/app/update`,agentDeploy:`/api/v1/indices/rag/app/deploy`,agentDelete:`/api/v1/indices/rag/app/delete`,agentCopy:`/api/v1/indices/rag/app/copy`,applyFileUploadLease:`/api/v1/connector/dash/applyFileUploadLease`,addFile:`/api/v1/connector/dash/addFile`,addFilesFromAuthorizedOss:`/api/v1/connector/dash/addFilesFromAuthorizedOss`,batchUpdateFileTag:`/api/v1/connector/dash/batchUpdateFileTag`,listFile:`/api/v1/connector/dash/listFile`,describeFile:`/api/v1/connector/dash/describeFile`,deleteFile:`/api/v1/connector/dash/deleteFile`,addConnector:`/api/v1/connector/dash/addConnector`,getConnector:`/api/v1/connector/dash/getConnector`,listCategory:`/api/v1/connector/dash/listCategory`,addCategory:`/api/v1/connector/dash/addCategory`,deleteCategory:`/api/v1/connector/dash/deleteCategory`},ri=[`qwen-image`,`wan2.7-image`,`z-image`],ii=[`qwen-image-3.0`,`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function ai(e,t){return t.some(t=>e.startsWith(t))}function oi(e){return ai(e,ri)||e.startsWith(`wan2.6-image`)}function si(e){return ai(e,ri)}function ci(e){return ai(e,ii)}function li(e){return/^wanx-v1(?:-|$)/i.test(e)}function ui(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||si(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||li(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function di(e){return/wan2\.5-i2i/i.test(e)}function fi(e){return/imageedit/i.test(e)}function pi(e){return e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-edit`)?`qwen-image-2.0`:e.startsWith(`qwen-image`)?`qwen-image-fixed`:e.startsWith(`wan2.7-image`)?`wan27`:e.startsWith(`z-image`)?`z-image`:e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||e.startsWith(`wan2.5-t2i`)?`wan26`:li(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:ui(e)?`wan-legacy`:`wan26`}function mi(e){if(e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function B(e,t){return{...e,sizeProfile:pi(t),promptExtendDefault:mi(t)}}function hi(e){return si(e)?B({kind:`sync-multimodal`,path:Wn(),useSync:!0,inputStyle:`messages`},e):ui(e)?B({kind:`async-text2image`,path:Gn(),useSync:!1,inputStyle:`prompt`},e):B({kind:`async-image-generation`,path:Un(),useSync:!1,inputStyle:`messages`},e)}function gi(e){return ci(e)?B({kind:`sync-multimodal`,path:Wn(),useSync:!0,inputStyle:`messages`},e):fi(e)?B({kind:`async-image2image`,path:Kn(),useSync:!1,inputStyle:`function-base-image`},e):di(e)?B({kind:`async-image2image`,path:Kn(),useSync:!1,inputStyle:`prompt-images`},e):B({kind:`async-image-generation`,path:Un(),useSync:!1,inputStyle:`messages`},e)}function _i(e){return/realtime|streaming/i.test(e)}function vi(e){return/filetrans/i.test(e)}function yi(e){return/^qwen3-asr-flash-filetrans(?:-|$)/i.test(e)}const bi=[`fun-asr-flash`,`qwen-audio`];function xi(e){return _i(e)||vi(e)?!1:!!(e.startsWith(bi[0])||e.startsWith(bi[1])&&/asr-flash/i.test(e))}function Si(e){return!(!/^qwen3-asr-flash(?:-|$)/i.test(e)||vi(e)||_i(e)||xi(e))}function Ci(e){if(_i(e))return{kind:`unsupported`,path:``,useSync:!1,unsupportedReason:`Model "${e}" is a realtime/streaming ASR model and requires a WebSocket API. Use an async filetrans model (e.g. fun-asr, qwen3-asr-flash-filetrans) or a sync flash model (e.g. qwen3-asr-flash, qwen-audio-3.0-asr-flash) with this command.`};if(vi(e)){let t=yi(e);return{kind:`async-filetrans`,path:sr(),useSync:!1,asyncInputStyle:t?`file_url`:`file_urls`,asyncLanguageStyle:t?`language`:`language_hints`}}return xi(e)?{kind:`sync-flash`,path:Wn(),useSync:!0,flashFamily:`input-audio`}:Si(e)?{kind:`sync-flash`,path:Wn(),useSync:!0,flashFamily:`qwen3`}:{kind:`async-filetrans`,path:sr(),useSync:!1,asyncInputStyle:`file_urls`,asyncLanguageStyle:`language_hints`}}function wi(e){let t=/^data:audio\/([^;,]+)/i.exec(e)?.[1]?.toLowerCase();if(t)return t===`mpeg`?`mp3`:t===`x-wav`||t===`wave`?`wav`:t;let n=(e.split(/[?#]/,1)[0]??e).match(/\.([a-zA-Z0-9]+)$/)?.[1]?.toLowerCase();return n?n===`mpeg`?`mp3`:n:`wav`}function Ti(e){return[{role:`user`,content:[{type:`input_text`,text:e}]}]}function Ei(e,t){return t?e===`language`?{language:t}:{language_hints:[t]}:{}}function Di(e){let{model:t,audioUrl:n,language:r,vocabularyId:i,vocabulary:a,context:o,flashFamily:s}=e;if(s===`input-audio`){let e={format:wi(n),sample_rate:`16000`};r&&(e.language_hints=[r]),i&&(e.vocabulary_id=i),a&&(e.vocabulary=a);let s=[];if(o)for(let e of Ti(o))s.push(e);return s.push({role:`user`,content:[{type:`input_audio`,input_audio:{data:n}}]}),{model:t,input:{messages:s},parameters:e}}let c={};r&&(c.language=r);let l={};Object.keys(c).length>0&&(l.asr_options=c);let u={model:t,input:{messages:[{role:`user`,content:[{audio:n}]}]}};return Object.keys(l).length>0&&(u.parameters=l),u}function Oi(e,t){let n=e.output;if(!n)return``;if(t===`input-audio`){if(typeof n.text==`string`&&n.text.length>0)return n.text;let e=n.sentence;if(typeof e?.text==`string`&&e.text.length>0)return e.text;let t=n.output?.sentence;return typeof t?.text==`string`?t.text:``}let r=n.choices;if(!r?.length)return``;let i=[];for(let e of r){let t=e.message;if(!t)continue;let n=t.content;if(typeof n==`string`){i.push(n);continue}if(Array.isArray(n))for(let e of n){if(typeof e==`string`){i.push(e);continue}if(e&&typeof e==`object`){let t=e;typeof t.text==`string`&&i.push(t.text)}}}return i.join(``)}function ki(e){if(e.results&&e.results.length>0)return e.results;let t=e.result?.transcription_url;return typeof t==`string`&&t.length>0?[{transcription_url:t,subtask_status:`SUCCEEDED`}]:[]}const Ai={12000090:`STS credentials unavailable — retry in a moment`,12000091:`Service-linked role creation failed — retry`,12000092:`Use the primary account to create the service-linked role`,12000093:`Cloud security service is unavailable — retry later`,12000094:`Alert query failed — treat as no data`},ji=new Set(Object.values(ze));function Mi(e){return ji.has(e.replace(/\/+$/,``))}function Ni(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}function Pi(...e){for(let t of e)if(typeof t==`string`&&t.length>0)return t}function Fi(e,t,n){let r=e??`unknown`,i=e===void 0&&t===void 0?`\nUnexpected response body (truncated): ${n.slice(0,800)}`:``;throw new P(`Security API failed: ${r} - ${t??`no message`}${i}`,N.GENERAL,Ai[r],{rawResponse:n.slice(0,500)})}function Ii(e,t){let n;try{n=JSON.parse(e)}catch{throw new P(`Security API returned non-JSON response (${t??`unknown type`}).`,N.GENERAL,void 0,{rawResponse:e.slice(0,500)})}let r=Ni(n),i=r?Ni(r.data):void 0,a=i?Ni(i.DataV2):void 0;if(a){let t=Ni(a.data),n=Array.isArray(a.ret)?a.ret.map(e=>String(e)):[],o=n.length===0||n.some(e=>e.startsWith(`SUCCESS`)),s=Pi(i?.errorCode,r?.errorCode),c=Pi(i?.errorMsg,r?.errorMsg)??(o?void 0:n.join(`; `));return(r?.successResponse===!1||i?.success===!1||t?.success===!1||t?.failed===!0||!o||s!==void 0)&&Fi(s,c,e),(t?t.data:void 0)??null}if(r&&`success`in r)return r.success||Fi(Pi(r.errorCode),Pi(r.errorMsg),e),r.data??null;if(r){let t=Pi(i?.errorCode,r.errorCode),n=Pi(i?.errorMsg,r.errorMsg);(r.successResponse===!1||i?.success===!1||t!==void 0)&&Fi(t,n,e)}if(r)return r;Fi(void 0,void 0,e)}async function Li(e,t){let n=await e.request({path:t,method:`GET`});return Ii(await n.text(),n.headers.get(`content-type`))}function Ri(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function zi(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Bi(e){return async(t,n={})=>{let r=zi(t),i=new Headers(n.headers??(t instanceof Request?t.headers:void 0));if(i.has(`user-agent`)||i.set(`User-Agent`,`${e.identity.clientName}/${e.identity.version}`),Ri(r))for(let[t,n]of Object.entries(z(e.identity)))i.set(t,n);if(e.settings.verbose){console.error(`> ${n.method??`GET`} ${r}`);let e=i.get(`authorization`);e&&console.error(`> Auth: ${Gt(e.replace(/^Bearer /,``))}`)}let a=await fetch(t,{...n,headers:i});if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}return a}}const Vi=`2024-08-16`;function Hi(e){return`bailiancontrol.${e}.aliyuncs.com`}function Ui(e){return new Nn({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function Wi(e){return Ui(e).openApiJson({host:Hi(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:Vi,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function Gi(e){return Ui(e).openApiJson({host:Hi(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:Vi,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function Ki(e){return Ui(e).openApiJson({host:Hi(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:Vi,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}const qi=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Ji=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function V(e){let t=e.data;if(!t)return e;let n=t.DataV2;if(n){let e=n.data;return e?.data??e??n}return t.data??t}async function Yi(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=V(await e(qi,{input:{pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:[],group:!0,capabilities:o,contextWindows:[]}})),c=s.total??0,l=s.list??[],u=[];for(let e of l){let t=e.items;if(t?.length)for(let e of t)u.push(e);else u.push(e)}return{total:c,models:u}}async function Xi(e,t={}){let n=t.pageSize??50,r=await Yi(e,{...t,pageNo:1,pageSize:n}),i=[...r.models],a=Math.ceil(r.total/n);for(let r=2;r<=a;r++){let a=await Yi(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function Zi(e,t){return(await Yi(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function Qi(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[],features:s=[],contextWindows:c=[],querySampleCode:l}=t,u={pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:s,group:!0,capabilities:o,contextWindows:c,queryPermissions:!0,queryApplyStatus:!0,queryActivationStatus:!0,queryPrice:!0,queryQpmInfo:!0,supports:{inference:!0}};l&&(u.querySampleCode=!0);let d=V(await e(qi,{input:u}));return{total:d.total??0,groups:d.list??[]}}function $i(e){return e.flatMap(e=>e.items??[])}async function ea(e,t={}){let n=t.pageSize??50,r=await Qi(e,{...t,pageNo:1,pageSize:n}),i=Math.max(1,Math.ceil(r.total/n)),a=[];for(let e=2;e<=i;e++)a.push(e);let o=await Promise.all(a.map(r=>Qi(e,{...t,pageNo:r,pageSize:n})));return $i([r.groups,...o.map(e=>e.groups)].flat())}async function ta(e,t){return(V(await e(`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,{input:{pageNo:1,pageSize:50,group:!0,model:t,querySampleCode:!0,queryGroupByModel:!0,queryWorkspaceLimit:!0,queryPrice:!0,queryQuota:!1,queryQpmInfo:!0,queryApplyStatus:!0,queryPermissions:!0,queryActivationStatus:!0}})).list??[])[0]??null}const na=[`name`,`key`,`default`,`tip`,`range`];function ra(e){return e.map(e=>{let t={};for(let n of na)e[n]!==void 0&&(t[n]=e[n]);return t})}async function ia(e,t){let n=V(await e(Ji,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?ra(e):null}catch{return null}return Array.isArray(n)?ra(n):null}function aa(e){return{read:()=>R(e),async write(t){let n=R(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?Le(String(r)):r;await Ct(n,e)},async unset(t){let n=R(e);for(let e of t)delete n[e];await Ct(n,e)},profiles:()=>Tt(),activate:e=>Ot(e),validateActivation:e=>Dt(e),get path(){return st()}}}async function oa(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=l(r),s=m(r),c=ie.toWeb(n(r)),u=await new Response(c).blob(),d=new FormData;d.append(`file`,u,s),d.append(`purpose`,i);let f=await e.requestJson({path:xr(),method:`POST`,body:d,signal:a});if(f.id)return{file_id:f.id,name:f.filename??s,size:f.bytes??o.size,purpose:f.purpose??i,gmt_create:f.created_at?(/* @__PURE__ */ new Date(f.created_at*1e3)).toISOString():void 0,request_id:f.request_id};let p=f.data?.failed_uploads;if(Array.isArray(p)&&p.length>0){let e=p[0]??{};throw new P(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,N.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new P(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,N.GENERAL,`The platform accepted the request but did not allocate a file_id. Retry the upload; if it recurs, contact platform support with the request id.`)}async function sa(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.purpose&&n.set(`purpose`,t.purpose);let r=Sr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function ca(e,t,n){return e.requestJson({path:Cr(t),method:`GET`,signal:n})}async function la(e,t,n){let r=await e.request({path:Cr(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const ua=209715200,da=314572800,fa=314572800,pa=2147483648;function ma(e,t=ua){if(!i(e))throw new P(`File not found: ${e}`,N.USAGE);let n=l(e);if(!n.isFile())throw new P(`Not a regular file: ${e}`,N.USAGE);if(n.size===0)throw new P(`File is empty: ${e}`,N.USAGE);if(n.size>t)throw new P(`File too large: ${(n.size/1048576).toFixed(1)}MB exceeds the ${(t/1048576).toFixed(0)}MB dataset upload cap.`,N.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function H(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function ha(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`||t===`decision`||t===`tts`||t===`image`||t===`video`)return t;throw new P(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, decision, tts, image, video. / 不支持的 --schema;可选值:chatml、dpo、cpt、decision、tts、image、video。`,N.USAGE,`Omit --schema to auto-detect per record (state/questions → decision, chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, first_frame_path/video_path → video, else ChatML). / 省略 --schema 可逐条自动识别。`)}function ga(e,t=50,n=100,r=10){if(e<=0)return[];if(e<=t+r)return Array.from({length:e},(e,t)=>t+1);let i=/* @__PURE__ */ new Set;for(let n=1;n<=Math.min(t,e);n++)i.add(n);for(let t=0;t<r;t++)i.add(e-t);let a=Math.max(1,Math.ceil(e/n));for(let n=t+1;n<=e-r;n+=a)i.add(n);return[...i].filter(t=>t>=1&&t<=e).sort((e,t)=>e-t)}const _a=/* @__PURE__ */ new Set([`system`,`user`,`assistant`,`tool`]),va=.1;function ya(e,t,n,r){let i=[],a=t=>{if(!(t in e))return;let a=e[t];(typeof a!=`number`||a<va||a>10)&&i.push(H(`error`,`INVALID_VIDEO_FPS`,`"${t}" must be a number between ${va} and 10 (got ${JSON.stringify(a)}).`,{line:n,path:`${r}.${t}`}))};a(`fps`),a(`sample_fps`);let o=t?[`fps`,`video_start`,`video_end`]:[`sample_fps`],s=t?`frame-list`:`file-path`;for(let t of o)t in e&&i.push(H(`warning`,`VIDEO_PARAM_MODE_MISMATCH`,`"${t}" does not apply to ${s} video mode and will be ignored by the platform.`,{line:n,path:`${r}.${t}`}));for(let a of[`video_start`,`video_end`])a in e&&!t&&typeof e[a]!=`number`&&i.push(H(`error`,`INVALID_VIDEO_CLIP_TIME`,`"${a}" must be a number (seconds).`,{line:n,path:`${r}.${a}`}));return i}function ba(e,t,n){let r=[];if(typeof e==`string`)return r;if(!Array.isArray(e))return r.push(H(`error`,`INVALID_CONTENT`,`"content" must be a string or an array of content items (got ${typeof e}).`,{line:t,path:n})),r;if(e.length===0)return r.push(H(`error`,`EMPTY_CONTENT_ARRAY`,`"content" array must not be empty.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(H(`error`,`INVALID_CONTENT_ITEM`,`Content item must be an object.`,{line:t,path:o}));continue}let s=a,c=`text`in s,l=`image`in s,u=`video`in s;if(!c&&!l&&!u){r.push(H(`error`,`CONTENT_ITEM_NO_KNOWN_FIELD`,`Content item must contain at least one of: "text", "image", "video".`,{line:t,path:o}));continue}if(c&&typeof s.text!=`string`&&r.push(H(`error`,`INVALID_CONTENT_TEXT`,`"text" in content item must be a string.`,{line:t,path:`${o}.text`})),l&&typeof s.image!=`string`&&r.push(H(`error`,`INVALID_CONTENT_IMAGE`,`"image" in content item must be a string.`,{line:t,path:`${o}.image`})),u){let e=s.video;if(typeof e!=`string`&&!Array.isArray(e))r.push(H(`error`,`INVALID_CONTENT_VIDEO`,`"video" in content item must be a string (file path) or an array of strings (frame list).`,{line:t,path:`${o}.video`}));else{if(Array.isArray(e))for(let n=0;n<e.length;n++)typeof e[n]!=`string`&&r.push(H(`error`,`INVALID_VIDEO_FRAME`,`Video frame list item at index ${n} must be a string.`,{line:t,path:`${o}.video[${n}]`}));r.push(...ya(s,Array.isArray(e),t,o))}}}return r}function xa(e,t,n){let r=[];if(!Array.isArray(e))return r.push(H(`error`,`INVALID_TOOL_CALLS`,`"tool_calls" must be an array.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(H(`error`,`INVALID_TOOL_CALL`,`tool_calls item must be an object.`,{line:t,path:o}));continue}let s=a;(typeof s.id!=`string`||s.id.length===0)&&r.push(H(`error`,`TOOL_CALL_MISSING_ID`,`tool_calls item must have a non-empty "id".`,{line:t,path:`${o}.id`})),s.type!==`function`&&r.push(H(`warning`,`TOOL_CALL_TYPE_NOT_FUNCTION`,`tool_calls item "type" should be "function" (got "${String(s.type)}").`,{line:t,path:`${o}.type`}));let c=s.function;if(typeof c!=`object`||!c||Array.isArray(c))r.push(H(`error`,`TOOL_CALL_MISSING_FUNCTION`,`tool_calls item must have a "function" object.`,{line:t,path:`${o}.function`}));else{let e=c;(typeof e.name!=`string`||e.name.length===0)&&r.push(H(`error`,`TOOL_CALL_FN_NO_NAME`,`tool_calls function must have a "name".`,{line:t,path:`${o}.function.name`})),typeof e.arguments!=`string`&&r.push(H(`error`,`TOOL_CALL_FN_ARGS_NOT_STRING`,`tool_calls function "arguments" must be a JSON string.`,{line:t,path:`${o}.function.arguments`}))}}return r}function Sa(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(H(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role;return(typeof a!=`string`||!_a.has(a))&&r.push(H(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant, tool.`,{line:t,path:`${n}.role`})),a===`tool`&&(typeof i.tool_call_id!=`string`||i.tool_call_id.length===0)&&r.push(H(`error`,`TOOL_MISSING_CALL_ID`,`A "tool" role message must have a non-empty "tool_call_id".`,{line:t,path:`${n}.tool_call_id`})),`content`in i?r.push(...ba(i.content,t,`${n}.content`)):(a!==`assistant`||!(`tool_calls`in i))&&r.push(H(`error`,`MISSING_CONTENT`,`"content" field is missing.`,{line:t,path:`${n}.content`})),`tool_calls`in i&&r.push(...xa(i.tool_calls,t,`${n}.tool_calls`)),`name`in i&&r.push(H(`error`,`UNSUPPORTED_FIELD_NAME`,`Field "name" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`${n}.name`})),`weight`in i&&r.push(H(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure. All assistant outputs are trained; per-line importance uses "loss_weight" (invite-only).`,{line:t,path:`${n}.weight`})),r}function Ca(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(H(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(H(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a,o=-1,s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Set;for(let e=0;e<r.length;e++){let l=r[e],u=`messages[${e}]`;n.push(...Sa(l,t,u));let d=l,f=d?.role;if(f===`system`&&(e!==0&&n.push(H(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${u}.role`})),i=!0),f===`assistant`&&(o=e,d&&Array.isArray(d.tool_calls)))for(let e of d.tool_calls){let t=e;t&&typeof t.id==`string`&&s.add(t.id)}if(f===`tool`){let e=d?.tool_call_id;typeof e==`string`&&e.length>0&&c.add(e)}a===f&&(f===`user`||f===`assistant`)&&n.push(H(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${f} messages — user/assistant turns should typically alternate.`,{line:t,path:`${u}.role`})),typeof f==`string`&&(a=f)}r.some(e=>e.role===`user`)||n.push(H(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(H(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`}));for(let e of c)s.has(e)||n.push(H(`error`,`TOOL_CALL_ID_UNMATCHED`,`tool message references tool_call_id "${e}" which does not match any assistant tool_calls[].id.`,{line:t,path:`messages`}));for(let e of s)c.has(e)||n.push(H(`warning`,`TOOL_CALL_NO_RESPONSE`,`assistant tool_calls[].id "${e}" has no matching tool response message.`,{line:t,path:`messages`}));if(o>=0)for(let e=0;e<r.length;e++){if(e===o)continue;let i=r[e];if(i?.role!==`assistant`||i&&Array.isArray(i.tool_calls))continue;let a=i?.content;wa(a)&&n.push(H(`warning`,`THINK_TAG_NOT_LAST`,`Thinking tags (<think>…</think>) should only appear in the last assistant message (or an assistant message carrying tool_calls), found at messages[${e}].`,{line:t,path:`messages[${e}].content`}))}let l=(e,r)=>{(typeof e!=`number`||e<0||e>1)&&n.push(H(`error`,`INVALID_LOSS_WEIGHT`,`"loss_weight" must be a number between 0.0 and 1.0 (got ${JSON.stringify(e)}).`,{line:t,path:r}))};`loss_weight`in e&&l(e.loss_weight,`loss_weight`);for(let e=0;e<r.length;e++){let i=r[e];i&&`loss_weight`in i&&(l(i.loss_weight,`messages[${e}].loss_weight`),(i.role!==`assistant`||e!==o)&&n.push(H(`warning`,`LOSS_WEIGHT_PLACEMENT`,`"loss_weight" is only supported on the last assistant message; found at messages[${e}] (role "${String(i.role)}").`,{line:t,path:`messages[${e}].loss_weight`})))}return`weight`in e&&n.push(H(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Record-level field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`weight`})),n}function wa(e){return typeof e==`string`?e.includes(`<think>`):Array.isArray(e)?e.some(e=>e&&typeof e==`object`&&`text`in e?typeof e.text==`string`&&e.text.includes(`<think>`):!1):!1}const Ta={name:`chatml`,detect:()=>!0,inspect:Ca};function Ea(e,t){let n=[];if(!(`text`in e))return n.push(H(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`})),n;let r=e.text;return typeof r==`string`?(r.trim().length===0&&n.push(H(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(H(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const Da={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:Ea};function Oa(e,t){let n=Ca(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=(e,n)=>{if(!Array.isArray(e))return[];let r=[];for(let i=0;i<e.length;i++){let a=e[i];if(a&&typeof a==`object`)for(let e of[`image`,`video`])e in a&&r.push(H(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support ${e} inputs; found at ${n}.content[${i}].`,{line:t,path:`${n}.content[${i}].${e}`}))}return r};`tools`in e&&n.push(H(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; remove the "tools" definition.`,{line:t,path:`tools`}));for(let e=0;e<r.length;e++){let a=r[e];if(!a)continue;let o=`messages[${e}]`;(a.role===`tool`||`tool_calls`in a)&&n.push(H(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; found ${a.role===`tool`?`role "tool"`:`"tool_calls"`} at ${o}.`,{line:t,path:o})),n.push(...i(a.content,o))}let a=r[r.length-1];a&&a.role!==`user`&&n.push(H(`error`,`DPO_LAST_MSG_NOT_USER`,`DPO "messages" must end with a "user" message (the prompt for chosen/rejected). Got "${String(a.role)}" as the last message.`,{line:t,path:`messages[${r.length-1}].role`}));let o=`chosen`in e,s=`rejected`in e;if(o||n.push(H(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),s||n.push(H(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),o){n.push(...Sa(e.chosen,t,`chosen`)),n.push(...i(e.chosen?.content,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(H(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(s){n.push(...Sa(e.rejected,t,`rejected`)),n.push(...i(e.rejected?.content,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(H(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const ka={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:Oa},Aa=[`choice`,`noul`,`score`],ja=255,Ma=2,Na=255,Pa=/* @__PURE__ */ new Set([`true`,`false`]);function U(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fa(e){return typeof e==`string`&&e.trim().length>0}function W(e,t,n,r){return{code:e,path:t,message:{"en-US":n,"zh-CN":r}}}function Ia(e,t=`state`){return Fa(e)||Array.isArray(e)&&e.length>0||U(e)&&Object.keys(e).length>0?[]:[W(`DECISION_INVALID_STATE`,t,`"${t}" must be a non-empty string, object, or array.`,`"${t}" 必须是非空字符串、对象或数组。`)]}function La(e,t){let n=`${t}.criteria`;if(!U(e))return[W(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must be an option-to-description object.`,`"${n}" 必须是“选项名到描述”的对象。`)];let r=Object.keys(e).length;if(r<1||r>255)return[W(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must contain 1-255 options (got ${r}).`,`"${n}" 必须包含 1-255 个选项(当前 ${r} 个)。`)];for(let[t,r]of Object.entries(e))if(!Fa(t)||!Fa(r))return[W(`DECISION_INVALID_CHOICE_CRITERIA`,`${n}.${t}`,`Choice option names and descriptions in "${n}" must be non-empty strings.`,`"${n}" 中的选项名和描述必须是非空字符串。`)];return[]}function Ra(e,t){let n=`${t}.criteria`;return!Array.isArray(e)||e.some(e=>!Fa(e))?[W(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must be an array of non-empty level descriptions, from low to high.`,`"${n}" 必须是从低到高排列、由非空等级描述组成的数组。`)]:e.length<2||e.length>255?[W(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must contain 2-255 levels (got ${e.length}).`,`"${n}" 必须包含 2-255 个等级(当前 ${e.length} 个)。`)]:[]}function za(e,t){if(e===void 0)return[];let n=`${t}.criteria`;return U(e)&&Object.entries(e).every(([e,t])=>Pa.has(e)&&typeof t==`string`)?[]:[W(`DECISION_INVALID_NOUL_CRITERIA`,n,`"${n}" is optional; when provided it must be an object with only "true" / "false" string descriptions.`,`"${n}" 为可选项;填写时必须是只包含 "true" / "false" 字符串描述的对象。`)]}function Ba(e,t){if(!U(e))return[W(`DECISION_QUESTION_NOT_OBJECT`,t,`"${t}" must be an object.`,`"${t}" 必须是对象。`)];let n=[];return e.instructions!==void 0&&typeof e.instructions!=`string`&&n.push(W(`DECISION_INVALID_INSTRUCTIONS`,`${t}.instructions`,`"${t}.instructions" must be a string when provided.`,`"${t}.instructions" 填写时必须是字符串。`)),e.type===`choice`?n.push(...La(e.criteria,t)):e.type===`noul`?n.push(...za(e.criteria,t)):e.type===`score`?n.push(...Ra(e.criteria,t)):n.push(W(`DECISION_INVALID_QUESTION_TYPE`,`${t}.type`,`"${t}.type" must be choice, noul, or score.`,`"${t}.type" 必须是 choice、noul 或 score。`)),n}function Va(e,t=`questions`){return U(e)&&Object.keys(e).length>0?[]:[W(`DECISION_INVALID_QUESTIONS`,t,`"${t}" must be a non-empty object keyed by question ID.`,`"${t}" 必须是以问题 ID 为键的非空对象。`)]}function Ha(e,t=`questions`){return Fa(e)?[]:[W(`DECISION_INVALID_QUESTION_ID`,t,`Question IDs must be non-empty strings.`,`问题 ID 必须是非空字符串。`)]}function Ua(e,t=`questions`){let n=Va(e,t);if(n.length>0)return n;let r=[];for(let[n,i]of Object.entries(e)){let e=Ha(n,t);if(e.length>0){r.push(...e);continue}r.push(...Ba(i,`${t}.${n}`))}return r}function G(e,t,n,r){return H(`error`,e,t,{line:n,path:r})}function Wa(e,t){return G(e.code,`${e.message[`en-US`]} / ${e.message[`zh-CN`]}`,t,e.path)}function Ga(e,t,n,r){if(!U(e))return[G(`DECISION_INVALID_TARGET`,`"${r}" must be an object containing a complete probability distribution. / "${r}" 必须是包含完整概率分布的对象。`,n,r)];let i=Object.keys(e).sort(),a=[...t].sort();if(i.length!==a.length||i.some((e,t)=>e!==a[t]))return[G(`DECISION_INVALID_TARGET_KEYS`,`"${r}" must contain exactly these keys: ${a.join(`, `)}. / "${r}" 必须且只能包含这些键:${a.join(`, `)}。`,n,r)];let o=0;for(let t of a){let i=e[t];if(typeof i!=`number`||!Number.isFinite(i)||i<0||i>1)return[G(`DECISION_INVALID_TARGET_PROBABILITY`,`"${r}.${t}" must be a finite number in [0, 1]. / "${r}.${t}" 必须是 [0, 1] 范围内的有限数字。`,n,`${r}.${t}`)];o+=i}return Math.abs(o-1)>1e-6?[G(`DECISION_TARGET_SUM_NOT_ONE`,`Probabilities in "${r}" must sum to 1 (got ${o}). / "${r}" 中的概率之和必须为 1(当前为 ${o})。`,n,r)]:[]}function Ka(e,t,n){let r=Object.keys(e.criteria);return typeof e.label!=`string`||!r.includes(e.label)?[G(`DECISION_INVALID_CHOICE_LABEL`,`"${n}.label" must be one of: ${r.join(`, `)}. / "${n}.label" 必须是以下选项之一:${r.join(`, `)}。`,t,`${n}.label`)]:e.target===void 0?[]:Ga(e.target,r,t,`${n}.target`)}function qa(e,t,n){return typeof e.label==`boolean`?e.target===void 0?[]:Ga(e.target,[`true`,`false`],t,`${n}.target`):[G(`DECISION_INVALID_NOUL_LABEL`,`"${n}.label" must be true or false. / "${n}.label" 必须是 true 或 false。`,t,`${n}.label`)]}function Ja(e,t,n){let r=e.criteria.length;if(typeof e.label!=`number`||!Number.isInteger(e.label)||e.label<0||e.label>=r)return[G(`DECISION_INVALID_SCORE_LABEL`,`"${n}.label" must be an integer from 0 to ${r-1}. / "${n}.label" 必须是 0 到 ${r-1} 之间的整数。`,t,`${n}.label`)];let i=Array.from({length:r},(e,t)=>String(t));return e.target===void 0?[]:Ga(e.target,i,t,`${n}.target`)}function Ya(e,t){let n=Ia(e.state).map(e=>Wa(e,t)),r=e.questions,i=Va(r);if(i.length>0)return n.push(...i.map(e=>Wa(e,t))),n;for(let[e,i]of Object.entries(r)){let r=Ha(e);if(r.length>0){n.push(...r.map(e=>Wa(e,t)));continue}let a=`questions.${e}`,o=Ba(i,a);if(o.length>0){n.push(...o.map(e=>Wa(e,t)));continue}let s=i;s.type===`choice`?n.push(...Ka(s,t,a)):s.type===`noul`?n.push(...qa(s,t,a)):n.push(...Ja(s,t,a))}return n}const Xa={name:`decision`,detect:e=>!(`messages`in e)&&(`questions`in e||`state`in e),inspect:Ya};function Za(e,t){let n=[];if(!(`wav_fn`in e))n.push(H(`error`,`MISSING_WAV_FN`,`Required field "wav_fn" is missing.`,{line:t,path:`wav_fn`}));else{let r=e.wav_fn;if(typeof r!=`string`)n.push(H(`error`,`INVALID_WAV_FN`,`"wav_fn" must be a string (got ${typeof r}).`,{line:t,path:`wav_fn`}));else if(r.trim().length===0)n.push(H(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(H(`error`,`WAV_FN_PREFIX`,`"wav_fn" must start with "train/" (got "${r}").`,{line:t,path:`wav_fn`}));let e=r.lastIndexOf(`.`),i=e>=0?r.slice(e).toLowerCase():``;i!==`.wav`&&n.push(H(`error`,`INVALID_AUDIO_EXT`,`"wav_fn" must reference a .wav file (got "${i||`(none)`}"). CosyVoice training audio must be WAV.`,{line:t,path:`wav_fn`}))}}if(!(`text`in e))n.push(H(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`}));else{let r=e.text;typeof r==`string`?r.trim().length===0&&n.push(H(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(H(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const Qa={name:`tts`,detect:e=>`wav_fn`in e,inspect:Za},$a=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.tif`,`.tiff`,`.webp`]);function eo(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function to(e){return/^[\x20-\x7E]+$/.test(e)}function no(e,t){let n=[];if(!(`prompt`in e))n.push(H(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(H(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(H(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(H(`error`,`MISSING_IMG_PATH`,`Required field "img_path" is missing.`,{line:t,path:`img_path`}));else{let r=e.img_path;if(typeof r!=`string`)n.push(H(`error`,`INVALID_IMG_PATH`,`"img_path" must be a string (got ${typeof r}).`,{line:t,path:`img_path`}));else if(r.trim().length===0)n.push(H(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=eo(r);$a.has(e)||n.push(H(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...$a].join(`, `)}.`,{line:t,path:`img_path`})),to(r)||n.push(H(`error`,`NON_ASCII_IMG_PATH`,`"img_path" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`img_path`}))}}if(`input_img`in e){let r=e.input_img;if(typeof r!=`string`)n.push(H(`error`,`INVALID_INPUT_IMG`,`"input_img" must be a string (got ${typeof r}).`,{line:t,path:`input_img`}));else if(r.trim().length===0)n.push(H(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=eo(r);$a.has(e)||n.push(H(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...$a].join(`, `)}.`,{line:t,path:`input_img`})),to(r)||n.push(H(`error`,`NON_ASCII_INPUT_IMG`,`"input_img" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`input_img`}))}}return n}const ro={name:`image`,detect:e=>`img_path`in e,inspect:no},io=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),ao=/* @__PURE__ */ new Set([`.mp4`,`.mov`]);function oo(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function so(e){return/^[\x20-\x7E]+$/.test(e)}function co(e,t,n,r,i,a){if(!(n in t)){r&&e.push(H(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(H(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(H(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=oo(o);i.has(s)||e.push(H(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),so(o)||e.push(H(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function lo(e,t){let n=[];if(!(`prompt`in e))n.push(H(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(H(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(H(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return co(n,e,`first_frame_path`,!0,io,t),co(n,e,`last_frame_path`,!1,io,t),co(n,e,`video_path`,!1,ao,t),n}const uo=[Qa,ro,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:lo},Xa,ka,Da,Ta];function fo(e,t){return t===void 0?uo.find(t=>t.detect(e))??Ta:uo.find(e=>e.name===t)||Ta}async function po(e,t){let r=n(e,{encoding:`utf8`}),i=x({input:r,crlfDelay:1/0}),a=[],o=0,s=0;for await(let e of i){if(t?.aborted)break;o++;let n=e.trim();if(n.length===0){s++;continue}a.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&a.push(H(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:o}))}return{totalLines:o,blankLines:s,issues:a}}async function mo(e,t,r,i,a){let o=r?null:new Set(ga(t)),s=[],c=0,l=n(e,{encoding:`utf8`}),u=x({input:l,crlfDelay:1/0}),d=0;for await(let e of u){if(a?.aborted)break;if(d++,o&&!o.has(d))continue;let t=e.trim();if(t.length===0||(c++,s.length>=30))continue;let n;try{n=JSON.parse(t)}catch(e){s.push(H(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:d}));continue}s.push(...ho(n,d,i))}return{sampled:c,issues:s}}function ho(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[H(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return fo(r,n).inspect(r,t)}const go={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await po(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[H(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await mo(e,r.totalLines,!!t.fullValidate,t.schema,t.signal),a=i.issues.filter(e=>e.severity===`error`),o=i.issues.filter(e=>e.severity===`warning`);return{valid:a.length===0,format:`jsonl`,filePath:e,errors:a,warnings:o,stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:i.sampled,durationMs:Date.now()-n}}}};function _o(e,t){return new Promise((n,r)=>{oe.open(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}i.readEntry(),i.on(`entry`,e=>{let r=e.fileName.replace(/\\/g,`/`);r===t||r.endsWith(`/${t}`)?n({entry:e,zipfile:i}):i.readEntry()}),i.on(`end`,()=>{i.close(),r(/* @__PURE__ */ Error(`Entry "${t}" not found in ZIP`))}),i.on(`error`,r)})})}function vo(e){return new Promise((t,n)=>{oe.open(e,{lazyEntries:!0},(e,r)=>{if(e||!r){n(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}let i=[];r.readEntry(),r.on(`entry`,e=>{i.push(e.fileName.replace(/\\/g,`/`)),r.readEntry()}),r.on(`end`,()=>{r.close(),t(i)}),r.on(`error`,n)})})}const yo=/^[a-zA-Z0-9_-]+$/;function bo(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):e}function xo(e){if(e===`__MACOSX`||e.startsWith(`__MACOSX/`))return!0;let t=e.split(`/`).filter(e=>e.length>0).pop()??``;return t===`.DS_Store`||t.startsWith(`._`)}function So(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){if(r.endsWith(`/`)||xo(r))continue;let e=r.split(`/`).filter(e=>e.length>0);for(let n of e){let e=bo(n),i=n.slice(e.length);e.length>0&&!yo.test(e)&&t.length<10&&t.push(H(`error`,`INVALID_FILENAME_CHARSET`,`File/folder name "${n}" contains invalid characters. Only a-z, A-Z, 0-9, underscore (_), and hyphen (-) are allowed.`,{path:r})),i.length>0&&!/^\.[a-zA-Z0-9]+$/.test(i)&&t.length<10&&t.push(H(`error`,`INVALID_FILENAME_CHARSET`,`File extension "${i}" in "${n}" contains invalid characters.`,{path:r}))}let i=e[e.length-1]??``,a=bo(i);if(a.length>120&&t.length<10&&t.push(H(`error`,`FILENAME_TOO_LONG`,`Filename "${i}" (without extension) exceeds 120 characters (got ${a.length}). Shorten the name and re-upload.`,{path:r})),a.length>0){let e=n.get(a);e===void 0?n.set(a,r):t.length<10&&t.push(H(`error`,`DUPLICATE_FILENAME`,`Filename "${i}" conflicts with "${e}" — names must be globally unique (ignoring extension) even across different folders.`,{path:r}))}}return t.length>=10&&t.push(H(`warning`,`FILENAME_ISSUES_TRUNCATED`,`More filename issues exist but reporting is capped at 10.`)),t}async function Co(e,t,n){let{entry:i,zipfile:a}=await _o(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??/* @__PURE__ */ Error(`Failed to open entry stream`));return}let s=r(n);ae(o,s).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function wo(e,t=100){let r=n(e,{encoding:`utf8`}),i=x({input:r,crlfDelay:1/0}),a=[],o=0;for await(let e of i){if(o++,a.length>=t)continue;let n=e.trim();if(n.length!==0)try{let e=JSON.parse(n);typeof e.wav_fn==`string`&&a.push(e.wav_fn),typeof e.img_path==`string`&&a.push(e.img_path),typeof e.input_img==`string`&&a.push(e.input_img),typeof e.first_frame_path==`string`&&a.push(e.first_frame_path),typeof e.last_frame_path==`string`&&a.push(e.last_frame_path),typeof e.video_path==`string`&&a.push(e.video_path),typeof e.image_fn==`string`&&a.push(e.image_fn),typeof e.video_fn==`string`&&a.push(e.video_fn)}catch{}}return{refs:a,totalLines:o}}const To={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await vo(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[H(`error`,`ZIP_OPEN_FAILED`,`Could not open ZIP archive: ${t.message}`)],warnings:[],stats:{durationMs:Date.now()-n}}}if(o.length===0)return{valid:!1,format:`zip`,filePath:e,errors:[H(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`),l=!s&&o.find(e=>e.endsWith(`/data.jsonl`));s||(l?r.push(H(`error`,`DATA_JSONL_NOT_AT_ROOT`,`"data.jsonl" must be at the ZIP root (found "${l}"). Re-package so that opening the ZIP shows data.jsonl directly, without a wrapping folder.`)):r.push(H(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav, .jpg) to their labels.`)));let u=So(o);for(let e of u)e.severity===`error`?r.push(e):i.push(e);let d=t.schema===`image`,f=t.schema===`video`,m=o.some(e=>e===`train/`||e.startsWith(`train/`)),h=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!m&&!d&&!f&&h&&i.push(H(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),d){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`)||xo(e))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return $a.has(n)});e.length<25&&r.push(H(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s&&!l)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let _=s?`data.jsonl`:o.find(e=>e.endsWith(`/data.jsonl`)),v=g(p(),`bl-zip-${ne(6).toString(`hex`)}`);a(v,{recursive:!0});let y=g(v,`data.jsonl`);try{await Co(e,_,y)}catch(t){return r.push(H(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(v,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let b=await go.validate(y,t);if(r.push(...b.errors),i.push(...b.warnings),b.valid){let{refs:e}=await wo(y),t=new Set(o),n=_.lastIndexOf(`/`),i=n>=0?_.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(H(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(v,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:b.stats.totalRecords??o.length,sampledRecords:b.stats.sampledRecords,durationMs:Date.now()-n}}}};async function Eo(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return Do(e);if(t===`.zip`)return Oo(e);throw new P(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,N.USAGE)}async function Do(e){let t=await Ao(e);if(!t)throw new P(`JSONL file is empty or contains only blank lines: ${e}`,N.USAGE);let n=ko(t);return n===`unknown`?`text`:n}async function Oo(e){let t=await jo(e,`data.jsonl`);if(!t)throw new P(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,N.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=ko(t);if(n===`unknown`)throw new P(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,N.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function ko(e){let t;try{t=JSON.parse(e)}catch{throw new P(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,N.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new P(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,N.USAGE);return`wav_fn`in t?`audio`:`img_path`in t?`input_img`in t?`image-i2i`:`image`:`first_frame_path`in t||`video_path`in t?`last_frame_path`in t?`video-kf2v`:`video`:`unknown`}function Ao(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=x({input:i,crlfDelay:1/0}),o=!1;a.on(`line`,e=>{if(o)return;let n=e.trim();n.length!==0&&(o=!0,a.close(),i.destroy(),t(n))}),a.on(`close`,()=>{o||t(null)}),a.on(`error`,r),i.on(`error`,r)})}function jo(e,t){return _o(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new P(`Failed to read "${t}" from ZIP: ${e?.message}`,N.USAGE));return}let o=x({input:a,crlfDelay:1/0}),s=!1;o.on(`line`,e=>{if(s)return;let t=e.trim();t.length!==0&&(s=!0,o.close(),a.destroy(),n.close(),r(t))}),o.on(`close`,()=>{s||(n.close(),r(null))}),o.on(`error`,e=>{n.close(),i(e)})})})).catch(e=>{if(e instanceof Error&&e.message.includes(`not found in ZIP`))return null;throw e})}const Mo=[go,To];function No(e){let t=h(e).toLowerCase(),n=Mo.find(e=>e.extensions.includes(t));if(!n){let e=Mo.flatMap(e=>e.extensions).join(`, `);throw new P(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,N.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function Po(e){Mo.some(t=>t.format===e.format)||Mo.push(e)}async function K(e,t={}){let{bytes:n}=ma(e,t.maxBytes??209715200),r=await No(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function Fo(){return Mo.map(e=>({format:e.format,extensions:[...e.extensions]}))}function Io(e){let t=[];e.line!==void 0&&t.push(`line ${e.line}`),e.path&&t.push(e.path);let n=t.length?` [${t.join(` · `)}]`:``;return` ${e.severity.toUpperCase()} ${e.code}${n}: ${e.message}`}const Lo=`decision-model-preview`,Ro=[`cn-beijing`,`ap-southeast-1`],zo=`cn-beijing`,Bo=[`label`,`target`];function Vo(e){if(!U(e))return e;let t=e.questions;return U(t)&&typeof t.type!=`string`?t:e}function Ho(e){if(!U(e))return e;let t={};for(let[n,r]of Object.entries(e)){if(!U(r)){t[n]=r;continue}let e={...r};for(let t of Bo)delete e[t];t[n]=e}return t}async function Uo(e,t,n){return e.requestJson({path:wr(),method:`POST`,body:t,signal:n})}async function Wo(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status),t.model&&n.set(`model`,t.model);let r=wr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Go(e,t,n){return e.requestJson({path:Tr(t),method:`GET`,signal:n})}async function Ko(e,t,n){return e.requestJson({path:Er(t),method:`POST`,signal:n})}async function qo(e,t,n){return e.requestJson({path:Tr(t),method:`DELETE`,signal:n})}async function Jo(e,t,n={}){let r=new URLSearchParams;n.pageNo!==void 0&&r.set(`page_no`,String(n.pageNo)),n.pageSize!==void 0&&r.set(`page_size`,String(n.pageSize));let i=Dr(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Yo(e,t,n){return e.requestJson({path:Or(t),method:`GET`,signal:n})}async function Xo(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${kr(t,n)}?${a.toString()}`,method:`GET`,signal:i})}function Zo(e,t){let n=new URLSearchParams;for(let[e,r]of Object.entries(t))r!==void 0&&r!==``&&n.set(e,String(r));return n.toString()?`${e}?${n.toString()}`:e}async function Qo(e,t={}){return e.requestJson({path:Zo(Ar(),{model:t.model,lang:t.lang}),method:`GET`,signal:t.signal})}async function $o(e,t,n){return e.requestJson({path:jr(),method:`POST`,body:t,signal:n})}async function es(e,t={}){let n=Zo(jr(),{status:t.status,model:t.model,template_id:t.templateId,quant_spec:t.quantSpec,quant_method:t.quantMethod,start_time:t.startTime,end_time:t.endTime,search_key:t.searchKey,select_key:t.selectKey,sort_order:t.sortOrder,page_no:t.pageNo,page_size:t.pageSize});return e.requestJson({path:n,method:`GET`,signal:t.signal})}async function ts(e,t,n){return e.requestJson({path:Mr(t),method:`GET`,signal:n})}async function ns(e,t,n={}){return e.requestJson({path:Zo(Pr(t),{offset:n.offset,line:n.line}),method:`GET`,signal:n.signal})}async function rs(e,t,n){return e.requestJson({path:Nr(t),method:`POST`,signal:n})}async function is(e,t,n){return e.requestJson({path:Mr(t),method:`DELETE`,signal:n})}const as={sft:{server:`sft`,method:`sft`,variant:`full`},"sft-lora":{server:`efficient_sft`,method:`sft`,variant:`lora`},dpo:{server:`dpo_full`,method:`dpo`,variant:`full`},"dpo-lora":{server:`dpo_lora`,method:`dpo`,variant:`lora`},cpt:{server:`cpt`,method:`cpt`,variant:`full`}},os=Object.keys(as),ss=`sft-lora`;function cs(e){return e in as}function ls(e){let{method:t,variant:n}=as[e];return{method:t,variant:n}}function us(e,t){if(!e)return!1;let{method:n,variant:r}=as[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function ds(e){return e?os.filter(t=>us(e,t)):[]}async function fs(e,t){return await Zi(Ht(e),t)}const ps=`INSUFFICIENT_SAMPLES`;function ms(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:ps,message:`Training dataset has ${t} sample(s), which is not greater than batch_size (${n}).`},hint:[`The platform requires the number of training samples to exceed batch_size.`,`Options:`,` • add more data (recommended: comfortably more than batch_size, since the`,` platform also holds back a default 0.9 train split),`,` • lower --batch-size (server clamps to a minimum of 8).`].join(`
|
|
12
|
+
`);let a=(await Ln({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,accessKeyId:r,accessKeySecret:i,securityToken:n.security_token})).cliAccessToken;e.validateToken?await e.validateToken(a):await In({...Fn(e.settings,e.baseUrl),token:a},e.settings);let o=R(t);return o.access_token=a,await Ct(o,t),a}function zn(e,t){if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new F(`Workspace ID must contain only letters, digits, hyphens or underscores. / Workspace ID 只能包含字母、数字、连字符或下划线。`);return`https://${e}.cn-beijing.maas.aliyuncs.com${t}`}function Bn(){return`/compatible-mode/v1/chat/completions`}function Vn(){return`/compatible-mode/v1/responses`}function Hn(){return`/compatible-mode/v1/systemone`}function Un(){return`/api/v1/services/aigc/image-generation/generation`}function Wn(){return`/api/v1/services/aigc/multimodal-generation/generation`}function Gn(){return`/api/v1/services/aigc/text2image/image-synthesis`}function Kn(){return`/api/v1/services/aigc/image2image/image-synthesis`}function qn(){return`/api/v1/services/aigc/video-generation/video-synthesis`}function Jn(){return`/api/v1/services/aigc/image2video/video-synthesis`}function Yn(e){return`/api/v1/tasks/${encodeURIComponent(e)}`}function Xn(){return`/api/v1/models/limits`}function Zn(){return`/api/v1/models/permissions`}function Qn(e){return`/api/v1/apps/${encodeURIComponent(e)}/completion`}function $n(e,t){return zn(e,t)}function er(){return`/api/v2/apps/memory/add-async`}function tr(e){return`/api/v2/apps/memory/events/${encodeURIComponent(e)}`}function nr(){return`/api/v2/apps/memory/memory_nodes/search`}function rr(){return`/api/v2/apps/memory/memory_nodes`}function ir(e){return`/api/v2/apps/memory/memory_nodes/${encodeURIComponent(e)}`}function ar(e){return`/api/v2/apps/memory/skill/export/${encodeURIComponent(e)}`}function or(){return`/api/v1/services/audio/tts/SpeechSynthesizer`}function sr(){return`/api/v1/services/audio/asr/transcription`}function cr(){return`/api/v1/services/audio/asr/customization`}function lr(){return`/api/v2/apps/memory/profile_schemas`}function ur(e){return`/api/v2/apps/memory/profile_schemas/${encodeURIComponent(e)}`}function dr(e){return`${ur(e)}/user_profile`}function fr(e){return`${ur(e)}/profile_values`}function pr(e,t=`cn-beijing`){return`https://${e}.${t}.maas.aliyuncs.com`}function mr(e){return zn(e,`/api/v1/indices/knowledge/search`)}function hr(e){return zn(e,`/api/v2/apps/knowledge/chat`)}function gr(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}const _r=`/api/v1/agentstudio/security`;function vr(e){return`${e}${_r}/overview`}function yr(e){return`${e}${_r}/agent_logs`}function br(){return`/api/v1/mcps/WebSearch/mcp`}function xr(){return`/compatible-mode/v1/files`}function Sr(){return`/api/v1/files`}function Cr(e){return`/api/v1/files/${encodeURIComponent(e)}`}function wr(){return`/api/v1/fine-tunes`}function Tr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}`}function Er(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/cancel`}function Dr(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/logs`}function Or(e){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/checkpoints`}function kr(e,t){return`/api/v1/fine-tunes/${encodeURIComponent(e)}/export/${encodeURIComponent(t)}`}function Ar(){return`/api/v1/fine-tunes/compress/templates`}function jr(){return`/api/v1/fine-tunes/compress/jobs`}function Mr(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}`}function Nr(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/cancel`}function Pr(e){return`/api/v1/fine-tunes/compress/jobs/${encodeURIComponent(e)}/logs`}function Fr(){return`/api/v1/deployments`}function Ir(e){return`/api/v1/deployments/${encodeURIComponent(e)}`}function Lr(e){return`${Ir(e)}/capacity-instances`}function Rr(e,t){return`${Lr(e)}/${encodeURIComponent(t)}`}function zr(e,t){return`${Rr(e,t)}/scale`}function Br(e,t){return`${Rr(e,t)}/renew`}function Vr(e){return`${Ir(e)}/update-overflowstrategy`}function Hr(e,t){return`${Ir(e)}/capacity-operations/${encodeURIComponent(t)}`}function Ur(e){return`${Ir(e)}/scale`}function Wr(e){return`/api/v1/deployments/${encodeURIComponent(e)}/update`}function Gr(){return`/api/v1/deployments/models`}function Kr(e,t){return zn(e,t)}function qr(){return`/api/v1/agentstudio/files`}function Jr(e){return`https://${e}.cn-beijing.maas.aliyuncs.com`}function Yr(e){return`/api/v1/agentstudio/sandbox${e}`}function Xr(e,t){return Jr(e)+Yr(t)}const Zr={sandboxes:`/sandboxes`,sandboxList:`/v2/sandboxes`,templates:`/templates`,templateCreate:`/v3/templates`,templateList:`/v2/templates`};function Qr(e){return`${Zr.sandboxes}/${encodeURIComponent(e)}`}function $r(e,t){return`${Qr(e)}/${t}`}function ei(e){return`${Zr.templates}/${encodeURIComponent(e)}`}function ti(e,t){return`${ei(e)}/builds/${encodeURIComponent(t)}/status`}const ni={indexList:`/api/v1/indices/rag/index/list`,indexCreateV2:`/api/v1/indices/rag/index/create_v2`,indexUpdate:`/api/v1/indices/rag/index/update`,indexDelete:`/api/v1/indices/rag/index/delete`,indexMonitor:`/api/v1/indices/rag/index/monitor`,indexFileDetails:`/api/v1/indices/rag/list/index/file/details`,indexFiles:`/api/v1/indices/rag/index/files`,indexDeleteFile:`/api/v1/indices/rag/index/delete_file`,indexJobCreate:`/api/v1/indices/rag/index/job/create`,indexJobStatus:`/api/v1/indices/rag/index_job/status`,chunkList:`/api/v1/indices/rag/index/chunklist`,chunkCreate:`/api/v1/indices/rag/index/chunk/create`,chunkUpdate:`/api/v1/indices/rag/index/chunk/update`,chunkDelete:`/api/v1/indices/rag/index/chunk/delete`,agentList:`/api/v1/indices/rag/app/list`,agentGet:`/api/v1/indices/rag/app/get`,agentCreate:`/api/v1/indices/rag/app/create`,agentUpdate:`/api/v1/indices/rag/app/update`,agentDeploy:`/api/v1/indices/rag/app/deploy`,agentDelete:`/api/v1/indices/rag/app/delete`,agentCopy:`/api/v1/indices/rag/app/copy`,applyFileUploadLease:`/api/v1/connector/dash/applyFileUploadLease`,addFile:`/api/v1/connector/dash/addFile`,addFilesFromAuthorizedOss:`/api/v1/connector/dash/addFilesFromAuthorizedOss`,batchUpdateFileTag:`/api/v1/connector/dash/batchUpdateFileTag`,listFile:`/api/v1/connector/dash/listFile`,describeFile:`/api/v1/connector/dash/describeFile`,deleteFile:`/api/v1/connector/dash/deleteFile`,addConnector:`/api/v1/connector/dash/addConnector`,getConnector:`/api/v1/connector/dash/getConnector`,listCategory:`/api/v1/connector/dash/listCategory`,addCategory:`/api/v1/connector/dash/addCategory`,deleteCategory:`/api/v1/connector/dash/deleteCategory`},ri=[`qwen-image`,`wan2.7-image`,`z-image`],ii=[`qwen-image-3.0`,`qwen-image-2.0`,`qwen-image-edit`,`wan2.7-image`,`wan2.6-image`];function ai(e,t){return t.some(t=>e.startsWith(t))}function oi(e){return ai(e,ri)||e.startsWith(`wan2.6-image`)}function si(e){return ai(e,ri)}function ci(e){return ai(e,ii)}function li(e){return/^wanx-v1(?:-|$)/i.test(e)}function ui(e){return e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||si(e)?!1:!!(/^wan2\.[0-5][^-]*-t2i/i.test(e)||li(e)||/^wanx/i.test(e)&&/t2i|text2image/i.test(e))}function di(e){return/wan2\.5-i2i/i.test(e)}function fi(e){return/imageedit/i.test(e)}function pi(e){return e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-edit`)?`qwen-image-2.0`:e.startsWith(`qwen-image`)?`qwen-image-fixed`:e.startsWith(`wan2.7-image`)?`wan27`:e.startsWith(`z-image`)?`z-image`:e.startsWith(`wan2.6-t2i`)||e.startsWith(`wan2.6-image`)||e.startsWith(`wan2.5-t2i`)?`wan26`:li(e)?`wanx-v1`:/wan2\.5-i2i/i.test(e)?`wan25-i2i`:ui(e)?`wan-legacy`:`wan26`}function mi(e){if(e.startsWith(`qwen-image-3.0`)||e.startsWith(`qwen-image-2.0`)||e.startsWith(`qwen-image-max`))return!0;if(e.startsWith(`z-image`))return!1}function B(e,t){return{...e,sizeProfile:pi(t),promptExtendDefault:mi(t)}}function hi(e){return si(e)?B({kind:`sync-multimodal`,path:Wn(),useSync:!0,inputStyle:`messages`},e):ui(e)?B({kind:`async-text2image`,path:Gn(),useSync:!1,inputStyle:`prompt`},e):B({kind:`async-image-generation`,path:Un(),useSync:!1,inputStyle:`messages`},e)}function gi(e){return ci(e)?B({kind:`sync-multimodal`,path:Wn(),useSync:!0,inputStyle:`messages`},e):fi(e)?B({kind:`async-image2image`,path:Kn(),useSync:!1,inputStyle:`function-base-image`},e):di(e)?B({kind:`async-image2image`,path:Kn(),useSync:!1,inputStyle:`prompt-images`},e):B({kind:`async-image-generation`,path:Un(),useSync:!1,inputStyle:`messages`},e)}function _i(e){return/realtime|streaming/i.test(e)}function vi(e){return/filetrans/i.test(e)}function yi(e){return/^qwen3-asr-flash-filetrans(?:-|$)/i.test(e)}const bi=[`fun-asr-flash`,`qwen-audio`];function xi(e){return _i(e)||vi(e)?!1:!!(e.startsWith(bi[0])||e.startsWith(bi[1])&&/asr-flash/i.test(e))}function Si(e){return!(!/^qwen3-asr-flash(?:-|$)/i.test(e)||vi(e)||_i(e)||xi(e))}function Ci(e){if(_i(e))return{kind:`unsupported`,path:``,useSync:!1,unsupportedReason:`Model "${e}" is a realtime/streaming ASR model and requires a WebSocket API. Use an async filetrans model (e.g. fun-asr, qwen3-asr-flash-filetrans) or a sync flash model (e.g. qwen3-asr-flash, qwen-audio-3.0-asr-flash) with this command.`};if(vi(e)){let t=yi(e);return{kind:`async-filetrans`,path:sr(),useSync:!1,asyncInputStyle:t?`file_url`:`file_urls`,asyncLanguageStyle:t?`language`:`language_hints`}}return xi(e)?{kind:`sync-flash`,path:Wn(),useSync:!0,flashFamily:`input-audio`}:Si(e)?{kind:`sync-flash`,path:Wn(),useSync:!0,flashFamily:`qwen3`}:{kind:`async-filetrans`,path:sr(),useSync:!1,asyncInputStyle:`file_urls`,asyncLanguageStyle:`language_hints`}}function wi(e){let t=/^data:audio\/([^;,]+)/i.exec(e)?.[1]?.toLowerCase();if(t)return t===`mpeg`?`mp3`:t===`x-wav`||t===`wave`?`wav`:t;let n=(e.split(/[?#]/,1)[0]??e).match(/\.([a-zA-Z0-9]+)$/)?.[1]?.toLowerCase();return n?n===`mpeg`?`mp3`:n:`wav`}function Ti(e){return[{role:`user`,content:[{type:`input_text`,text:e}]}]}function Ei(e,t){return t?e===`language`?{language:t}:{language_hints:[t]}:{}}function Di(e){let{model:t,audioUrl:n,language:r,vocabularyId:i,vocabulary:a,context:o,flashFamily:s}=e;if(s===`input-audio`){let e={format:wi(n),sample_rate:`16000`};r&&(e.language_hints=[r]),i&&(e.vocabulary_id=i),a&&(e.vocabulary=a);let s=[];if(o)for(let e of Ti(o))s.push(e);return s.push({role:`user`,content:[{type:`input_audio`,input_audio:{data:n}}]}),{model:t,input:{messages:s},parameters:e}}let c={};r&&(c.language=r);let l={};Object.keys(c).length>0&&(l.asr_options=c);let u={model:t,input:{messages:[{role:`user`,content:[{audio:n}]}]}};return Object.keys(l).length>0&&(u.parameters=l),u}function Oi(e,t){let n=e.output;if(!n)return``;if(t===`input-audio`){if(typeof n.text==`string`&&n.text.length>0)return n.text;let e=n.sentence;if(typeof e?.text==`string`&&e.text.length>0)return e.text;let t=n.output?.sentence;return typeof t?.text==`string`?t.text:``}let r=n.choices;if(!r?.length)return``;let i=[];for(let e of r){let t=e.message;if(!t)continue;let n=t.content;if(typeof n==`string`){i.push(n);continue}if(Array.isArray(n))for(let e of n){if(typeof e==`string`){i.push(e);continue}if(e&&typeof e==`object`){let t=e;typeof t.text==`string`&&i.push(t.text)}}}return i.join(``)}function ki(e){if(e.results&&e.results.length>0)return e.results;let t=e.result?.transcription_url;return typeof t==`string`&&t.length>0?[{transcription_url:t,subtask_status:`SUCCEEDED`}]:[]}const Ai={12000090:`STS credentials unavailable — retry in a moment`,12000091:`Service-linked role creation failed — retry`,12000092:`Use the primary account to create the service-linked role`,12000093:`Cloud security service is unavailable — retry later`,12000094:`Alert query failed — treat as no data`},ji=new Set(Object.values(ze));function Mi(e){return ji.has(e.replace(/\/+$/,``))}function Ni(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:void 0}function Pi(...e){for(let t of e)if(typeof t==`string`&&t.length>0)return t}function Fi(e,t,n){let r=e??`unknown`,i=e===void 0&&t===void 0?`\nUnexpected response body (truncated): ${n.slice(0,800)}`:``;throw new P(`Security API failed: ${r} - ${t??`no message`}${i}`,N.GENERAL,Ai[r],{rawResponse:n.slice(0,500)})}function Ii(e,t){let n;try{n=JSON.parse(e)}catch{throw new P(`Security API returned non-JSON response (${t??`unknown type`}).`,N.GENERAL,void 0,{rawResponse:e.slice(0,500)})}let r=Ni(n),i=r?Ni(r.data):void 0,a=i?Ni(i.DataV2):void 0;if(a){let t=Ni(a.data),n=Array.isArray(a.ret)?a.ret.map(e=>String(e)):[],o=n.length===0||n.some(e=>e.startsWith(`SUCCESS`)),s=Pi(i?.errorCode,r?.errorCode),c=Pi(i?.errorMsg,r?.errorMsg)??(o?void 0:n.join(`; `));return(r?.successResponse===!1||i?.success===!1||t?.success===!1||t?.failed===!0||!o||s!==void 0)&&Fi(s,c,e),(t?t.data:void 0)??null}if(r&&`success`in r)return r.success||Fi(Pi(r.errorCode),Pi(r.errorMsg),e),r.data??null;if(r){let t=Pi(i?.errorCode,r.errorCode),n=Pi(i?.errorMsg,r.errorMsg);(r.successResponse===!1||i?.success===!1||t!==void 0)&&Fi(t,n,e)}if(r)return r;Fi(void 0,void 0,e)}async function Li(e,t){let n=await e.request({path:t,method:`GET`});return Ii(await n.text(),n.headers.get(`content-type`))}function Ri(e){try{let{hostname:t}=new URL(e);return t===`aliyuncs.com`||t.endsWith(`.aliyuncs.com`)}catch{return!1}}function zi(e){return typeof e==`string`?e:e instanceof URL?e.href:e.url}function Bi(e){return async(t,n={})=>{let r=zi(t),i=new Headers(n.headers??(t instanceof Request?t.headers:void 0));if(i.has(`user-agent`)||i.set(`User-Agent`,`${e.identity.clientName}/${e.identity.version}`),Ri(r))for(let[t,n]of Object.entries(z(e.identity)))i.set(t,n);if(e.settings.verbose){console.error(`> ${n.method??`GET`} ${r}`);let e=i.get(`authorization`);e&&console.error(`> Auth: ${Gt(e.replace(/^Bearer /,``))}`)}let a=await fetch(t,{...n,headers:i});if(e.settings.verbose){console.error(`< ${a.status} ${a.statusText}`);let e=a.headers.get(`x-request-id`);e&&console.error(`request_id: ${e}`)}return a}}const Vi=`2024-08-16`;function Hi(e){return`bailiancontrol.${e}.aliyuncs.com`}function Ui(e){return new Nn({identity:e.identity,settings:e.settings,baseUrl:e.baseUrl,openApiCred:{accessKeyId:e.accessKeyId,accessKeySecret:e.accessKeySecret,securityToken:e.securityToken,source:`flag`}})}async function Wi(e){return Ui(e).openApiJson({host:Hi(e.regionId),path:`/bailianControl/User/createUser`,action:`CreateUser`,version:Vi,method:`POST`,body:{data:JSON.stringify({reqDTO:e.reqDTO})}})}async function Gi(e){return Ui(e).openApiJson({host:Hi(e.regionId),path:`/bailianControl/workspaces`,action:`ListWorkspaces`,version:Vi,method:`GET`,queryParams:{data:JSON.stringify({reqDTO:{},cornerstoneParam:{}})}})}async function Ki(e){return Ui(e).openApiJson({host:Hi(e.regionId),path:`/bailianControl/serviserAuthorityPolicy/resetPolicies4Agent`,action:`ChangeUserPermissions`,version:Vi,method:`POST`,body:{data:JSON.stringify({cornerstoneParam:{},outerKey:e.outerKey,policyIndexList:e.policyIndexList??[1],agentId:e.agentId})}})}const qi=`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,Ji=`zeldaEasy.bmp.modelPredictRpcService.getPredictParamConfig`;function V(e){let t=e.data;if(!t)return e;let n=t.DataV2;if(n){let e=n.data;return e?.data??e??n}return t.data??t}async function Yi(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[]}=t,s=V(await e(qi,{input:{pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:[],group:!0,capabilities:o,contextWindows:[]}})),c=s.total??0,l=s.list??[],u=[];for(let e of l){let t=e.items;if(t?.length)for(let e of t)u.push(e);else u.push(e)}return{total:c,models:u}}async function Xi(e,t={}){let n=t.pageSize??50,r=await Yi(e,{...t,pageNo:1,pageSize:n}),i=[...r.models],a=Math.ceil(r.total/n);for(let r=2;r<=a;r++){let a=await Yi(e,{...t,pageNo:r,pageSize:n});if(a.models.length===0)break;i.push(...a.models)}return i}async function Zi(e,t){return(await Yi(e,{name:t,pageSize:50})).models.find(e=>e.model===t)??null}async function Qi(e,t={}){let{pageNo:n=1,pageSize:r=50,name:i=``,providers:a=[],capabilities:o=[],features:s=[],contextWindows:c=[],querySampleCode:l}=t,u={pageNo:n,pageSize:r,name:i,providers:a,inferenceProviders:[],features:s,group:!0,capabilities:o,contextWindows:c,queryPermissions:!0,queryApplyStatus:!0,queryActivationStatus:!0,queryPrice:!0,queryQpmInfo:!0,supports:{inference:!0}};l&&(u.querySampleCode=!0);let d=V(await e(qi,{input:u}));return{total:d.total??0,groups:d.list??[]}}function $i(e){return e.flatMap(e=>e.items??[])}async function ea(e,t={}){let n=t.pageSize??50,r=await Qi(e,{...t,pageNo:1,pageSize:n}),i=Math.max(1,Math.ceil(r.total/n)),a=[];for(let e=2;e<=i;e++)a.push(e);let o=await Promise.all(a.map(r=>Qi(e,{...t,pageNo:r,pageSize:n})));return $i([r.groups,...o.map(e=>e.groups)].flat())}async function ta(e,t){return(V(await e(`zeldaHttp.dashscopeModel./zelda/api/v1/modelCenter/listFoundationModels`,{input:{pageNo:1,pageSize:50,group:!0,model:t,querySampleCode:!0,queryGroupByModel:!0,queryWorkspaceLimit:!0,queryPrice:!0,queryQuota:!1,queryQpmInfo:!0,queryApplyStatus:!0,queryPermissions:!0,queryActivationStatus:!0}})).list??[])[0]??null}const na=[`name`,`key`,`default`,`tip`,`range`];function ra(e){return e.map(e=>{let t={};for(let n of na)e[n]!==void 0&&(t[n]=e[n]);return t})}async function ia(e,t){let n=V(await e(Ji,{modelId:t})).predictConfig;if(!n)return null;if(typeof n==`string`)try{let e=JSON.parse(n);return Array.isArray(e)?ra(e):null}catch{return null}return Array.isArray(n)?ra(n):null}function aa(e){return{read:()=>R(e),async write(t){let n=R(e);for(let[e,r]of Object.entries(t))r===void 0?delete n[e]:n[e]=e===`base_url`?Le(String(r)):r;await Ct(n,e)},async unset(t){let n=R(e);for(let e of t)delete n[e];await Ct(n,e)},profiles:()=>Tt(),activate:e=>Ot(e),validateActivation:e=>Dt(e),get path(){return st()}}}async function oa(e,t){let{filePath:r,purpose:i=`fine-tune`,signal:a}=t,o=l(r),s=m(r),c=ie.toWeb(n(r)),u=await new Response(c).blob(),d=new FormData;d.append(`file`,u,s),d.append(`purpose`,i);let f=await e.requestJson({path:xr(),method:`POST`,body:d,signal:a});if(f.id)return{file_id:f.id,name:f.filename??s,size:f.bytes??o.size,purpose:f.purpose??i,gmt_create:f.created_at?(/* @__PURE__ */ new Date(f.created_at*1e3)).toISOString():void 0,request_id:f.request_id};let p=f.data?.failed_uploads;if(Array.isArray(p)&&p.length>0){let e=p[0]??{};throw new P(`Dataset upload failed${e.code?` [${e.code}]`:``}: ${e.message??`no message returned`}`,N.GENERAL,`Server reported failure for ${s}. Re-run with --verbose to see the raw response.`)}throw new P(`Dataset upload of ${s} returned no file_id (HTTP 200 with empty payload).`,N.GENERAL,`The platform accepted the request but did not allocate a file_id. Retry the upload; if it recurs, contact platform support with the request id.`)}async function sa(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.purpose&&n.set(`purpose`,t.purpose);let r=Sr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function ca(e,t,n){return e.requestJson({path:Cr(t),method:`GET`,signal:n})}async function la(e,t,n){let r=await e.request({path:Cr(t),method:`DELETE`,signal:n});try{return await r.json()}catch{return{data:{deleted:!0,file_id:t}}}}const ua=209715200,da=314572800,fa=314572800,pa=2147483648;function ma(e,t=ua){if(!i(e))throw new P(`File not found: ${e}`,N.USAGE);let n=l(e);if(!n.isFile())throw new P(`Not a regular file: ${e}`,N.USAGE);if(n.size===0)throw new P(`File is empty: ${e}`,N.USAGE);if(n.size>t)throw new P(`File too large: ${(n.size/1048576).toFixed(1)}MB exceeds the ${(t/1048576).toFixed(0)}MB dataset upload cap.`,N.USAGE);return{bytes:n.size,ext:h(e).toLowerCase()}}function H(e,t,n,r={}){return{severity:e,code:t,message:n,...r}}function ha(e){if(e===void 0||e.trim()===``)return;let t=e.trim();if(t===`chatml`||t===`dpo`||t===`cpt`||t===`decision`||t===`tts`||t===`image`||t===`video`)return t;throw new P(`Unsupported --schema "${e}". Supported: chatml, dpo, cpt, decision, tts, image, video. / 不支持的 --schema;可选值:chatml、dpo、cpt、decision、tts、image、video。`,N.USAGE,`Omit --schema to auto-detect per record (state/questions → decision, chosen/rejected → DPO, text → CPT, wav_fn → TTS, img_path → image, first_frame_path/video_path → video, else ChatML). / 省略 --schema 可逐条自动识别。`)}function ga(e,t=50,n=100,r=10){if(e<=0)return[];if(e<=t+r)return Array.from({length:e},(e,t)=>t+1);let i=/* @__PURE__ */ new Set;for(let n=1;n<=Math.min(t,e);n++)i.add(n);for(let t=0;t<r;t++)i.add(e-t);let a=Math.max(1,Math.ceil(e/n));for(let n=t+1;n<=e-r;n+=a)i.add(n);return[...i].filter(t=>t>=1&&t<=e).sort((e,t)=>e-t)}const _a=/* @__PURE__ */ new Set([`system`,`user`,`assistant`,`tool`]),va=.1;function ya(e,t,n,r){let i=[],a=t=>{if(!(t in e))return;let a=e[t];(typeof a!=`number`||a<va||a>10)&&i.push(H(`error`,`INVALID_VIDEO_FPS`,`"${t}" must be a number between ${va} and 10 (got ${JSON.stringify(a)}).`,{line:n,path:`${r}.${t}`}))};a(`fps`),a(`sample_fps`);let o=t?[`fps`,`video_start`,`video_end`]:[`sample_fps`],s=t?`frame-list`:`file-path`;for(let t of o)t in e&&i.push(H(`warning`,`VIDEO_PARAM_MODE_MISMATCH`,`"${t}" does not apply to ${s} video mode and will be ignored by the platform.`,{line:n,path:`${r}.${t}`}));for(let a of[`video_start`,`video_end`])a in e&&!t&&typeof e[a]!=`number`&&i.push(H(`error`,`INVALID_VIDEO_CLIP_TIME`,`"${a}" must be a number (seconds).`,{line:n,path:`${r}.${a}`}));return i}function ba(e,t,n){let r=[];if(typeof e==`string`)return r;if(!Array.isArray(e))return r.push(H(`error`,`INVALID_CONTENT`,`"content" must be a string or an array of content items (got ${typeof e}).`,{line:t,path:n})),r;if(e.length===0)return r.push(H(`error`,`EMPTY_CONTENT_ARRAY`,`"content" array must not be empty.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(H(`error`,`INVALID_CONTENT_ITEM`,`Content item must be an object.`,{line:t,path:o}));continue}let s=a,c=`text`in s,l=`image`in s,u=`video`in s;if(!c&&!l&&!u){r.push(H(`error`,`CONTENT_ITEM_NO_KNOWN_FIELD`,`Content item must contain at least one of: "text", "image", "video".`,{line:t,path:o}));continue}if(c&&typeof s.text!=`string`&&r.push(H(`error`,`INVALID_CONTENT_TEXT`,`"text" in content item must be a string.`,{line:t,path:`${o}.text`})),l&&typeof s.image!=`string`&&r.push(H(`error`,`INVALID_CONTENT_IMAGE`,`"image" in content item must be a string.`,{line:t,path:`${o}.image`})),u){let e=s.video;if(typeof e!=`string`&&!Array.isArray(e))r.push(H(`error`,`INVALID_CONTENT_VIDEO`,`"video" in content item must be a string (file path) or an array of strings (frame list).`,{line:t,path:`${o}.video`}));else{if(Array.isArray(e))for(let n=0;n<e.length;n++)typeof e[n]!=`string`&&r.push(H(`error`,`INVALID_VIDEO_FRAME`,`Video frame list item at index ${n} must be a string.`,{line:t,path:`${o}.video[${n}]`}));r.push(...ya(s,Array.isArray(e),t,o))}}}return r}function xa(e,t,n){let r=[];if(!Array.isArray(e))return r.push(H(`error`,`INVALID_TOOL_CALLS`,`"tool_calls" must be an array.`,{line:t,path:n})),r;for(let i=0;i<e.length;i++){let a=e[i],o=`${n}[${i}]`;if(typeof a!=`object`||!a||Array.isArray(a)){r.push(H(`error`,`INVALID_TOOL_CALL`,`tool_calls item must be an object.`,{line:t,path:o}));continue}let s=a;(typeof s.id!=`string`||s.id.length===0)&&r.push(H(`error`,`TOOL_CALL_MISSING_ID`,`tool_calls item must have a non-empty "id".`,{line:t,path:`${o}.id`})),s.type!==`function`&&r.push(H(`warning`,`TOOL_CALL_TYPE_NOT_FUNCTION`,`tool_calls item "type" should be "function" (got "${String(s.type)}").`,{line:t,path:`${o}.type`}));let c=s.function;if(typeof c!=`object`||!c||Array.isArray(c))r.push(H(`error`,`TOOL_CALL_MISSING_FUNCTION`,`tool_calls item must have a "function" object.`,{line:t,path:`${o}.function`}));else{let e=c;(typeof e.name!=`string`||e.name.length===0)&&r.push(H(`error`,`TOOL_CALL_FN_NO_NAME`,`tool_calls function must have a "name".`,{line:t,path:`${o}.function.name`})),typeof e.arguments!=`string`&&r.push(H(`error`,`TOOL_CALL_FN_ARGS_NOT_STRING`,`tool_calls function "arguments" must be a JSON string.`,{line:t,path:`${o}.function.arguments`}))}}return r}function Sa(e,t,n){let r=[];if(typeof e!=`object`||!e||Array.isArray(e))return r.push(H(`error`,`MESSAGE_NOT_OBJECT`,`Message must be an object.`,{line:t,path:n})),r;let i=e,a=i.role;return(typeof a!=`string`||!_a.has(a))&&r.push(H(`error`,`INVALID_ROLE`,`Invalid role "${String(a)}". Expected one of: system, user, assistant, tool.`,{line:t,path:`${n}.role`})),a===`tool`&&(typeof i.tool_call_id!=`string`||i.tool_call_id.length===0)&&r.push(H(`error`,`TOOL_MISSING_CALL_ID`,`A "tool" role message must have a non-empty "tool_call_id".`,{line:t,path:`${n}.tool_call_id`})),`content`in i?r.push(...ba(i.content,t,`${n}.content`)):(a!==`assistant`||!(`tool_calls`in i))&&r.push(H(`error`,`MISSING_CONTENT`,`"content" field is missing.`,{line:t,path:`${n}.content`})),`tool_calls`in i&&r.push(...xa(i.tool_calls,t,`${n}.tool_calls`)),`name`in i&&r.push(H(`error`,`UNSUPPORTED_FIELD_NAME`,`Field "name" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`${n}.name`})),`weight`in i&&r.push(H(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure. All assistant outputs are trained; per-line importance uses "loss_weight" (invite-only).`,{line:t,path:`${n}.weight`})),r}function Ca(e,t){let n=[],r=e.messages;if(!Array.isArray(r))return n.push(H(`error`,`MISSING_MESSAGES`,`Required field "messages" is missing or not an array.`,{line:t,path:`messages`})),n;if(r.length===0)return n.push(H(`error`,`EMPTY_MESSAGES`,`"messages" must contain at least one entry.`,{line:t,path:`messages`})),n;let i=!1,a,o=-1,s=/* @__PURE__ */ new Set,c=/* @__PURE__ */ new Set;for(let e=0;e<r.length;e++){let l=r[e],u=`messages[${e}]`;n.push(...Sa(l,t,u));let d=l,f=d?.role;if(f===`system`&&(e!==0&&n.push(H(`warning`,`SYSTEM_NOT_FIRST`,`"system" message should appear at index 0; found at index ${e}.`,{line:t,path:`${u}.role`})),i=!0),f===`assistant`&&(o=e,d&&Array.isArray(d.tool_calls)))for(let e of d.tool_calls){let t=e;t&&typeof t.id==`string`&&s.add(t.id)}if(f===`tool`){let e=d?.tool_call_id;typeof e==`string`&&e.length>0&&c.add(e)}a===f&&(f===`user`||f===`assistant`)&&n.push(H(`warning`,`ROLE_NOT_ALTERNATING`,`Consecutive ${f} messages — user/assistant turns should typically alternate.`,{line:t,path:`${u}.role`})),typeof f==`string`&&(a=f)}r.some(e=>e.role===`user`)||n.push(H(`warning`,`NO_USER_ROLE`,`No "user" message found in this sample.`,{line:t,path:`messages`})),i&&r.length===1&&n.push(H(`warning`,`SYSTEM_ONLY`,`Sample only contains a "system" message.`,{line:t,path:`messages`}));for(let e of c)s.has(e)||n.push(H(`error`,`TOOL_CALL_ID_UNMATCHED`,`tool message references tool_call_id "${e}" which does not match any assistant tool_calls[].id.`,{line:t,path:`messages`}));for(let e of s)c.has(e)||n.push(H(`warning`,`TOOL_CALL_NO_RESPONSE`,`assistant tool_calls[].id "${e}" has no matching tool response message.`,{line:t,path:`messages`}));if(o>=0)for(let e=0;e<r.length;e++){if(e===o)continue;let i=r[e];if(i?.role!==`assistant`||i&&Array.isArray(i.tool_calls))continue;let a=i?.content;wa(a)&&n.push(H(`warning`,`THINK_TAG_NOT_LAST`,`Thinking tags (<think>…</think>) should only appear in the last assistant message (or an assistant message carrying tool_calls), found at messages[${e}].`,{line:t,path:`messages[${e}].content`}))}let l=(e,r)=>{(typeof e!=`number`||e<0||e>1)&&n.push(H(`error`,`INVALID_LOSS_WEIGHT`,`"loss_weight" must be a number between 0.0 and 1.0 (got ${JSON.stringify(e)}).`,{line:t,path:r}))};`loss_weight`in e&&l(e.loss_weight,`loss_weight`);for(let e=0;e<r.length;e++){let i=r[e];i&&`loss_weight`in i&&(l(i.loss_weight,`messages[${e}].loss_weight`),(i.role!==`assistant`||e!==o)&&n.push(H(`warning`,`LOSS_WEIGHT_PLACEMENT`,`"loss_weight" is only supported on the last assistant message; found at messages[${e}] (role "${String(i.role)}").`,{line:t,path:`messages[${e}].loss_weight`})))}return`weight`in e&&n.push(H(`error`,`UNSUPPORTED_FIELD_WEIGHT`,`Record-level field "weight" is not supported by Bailian and must be removed when migrating from OpenAI/Azure.`,{line:t,path:`weight`})),n}function wa(e){return typeof e==`string`?e.includes(`<think>`):Array.isArray(e)?e.some(e=>e&&typeof e==`object`&&`text`in e?typeof e.text==`string`&&e.text.includes(`<think>`):!1):!1}const Ta={name:`chatml`,detect:()=>!0,inspect:Ca};function Ea(e,t){let n=[];if(!(`text`in e))return n.push(H(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`})),n;let r=e.text;return typeof r==`string`?(r.trim().length===0&&n.push(H(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})),n):(n.push(H(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`})),n)}const Da={name:`cpt`,detect:e=>`text`in e&&!(`messages`in e),inspect:Ea};function Oa(e,t){let n=Ca(e,t),r=e.messages;if(!Array.isArray(r)||r.length===0)return n;let i=(e,n)=>{if(!Array.isArray(e))return[];let r=[];for(let i=0;i<e.length;i++){let a=e[i];if(a&&typeof a==`object`)for(let e of[`image`,`video`])e in a&&r.push(H(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support ${e} inputs; found at ${n}.content[${i}].`,{line:t,path:`${n}.content[${i}].${e}`}))}return r};`tools`in e&&n.push(H(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; remove the "tools" definition.`,{line:t,path:`tools`}));for(let e=0;e<r.length;e++){let a=r[e];if(!a)continue;let o=`messages[${e}]`;(a.role===`tool`||`tool_calls`in a)&&n.push(H(`error`,`DPO_UNSUPPORTED_ELEMENT`,`DPO training data does not support tool calling; found ${a.role===`tool`?`role "tool"`:`"tool_calls"`} at ${o}.`,{line:t,path:o})),n.push(...i(a.content,o))}let a=r[r.length-1];a&&a.role!==`user`&&n.push(H(`error`,`DPO_LAST_MSG_NOT_USER`,`DPO "messages" must end with a "user" message (the prompt for chosen/rejected). Got "${String(a.role)}" as the last message.`,{line:t,path:`messages[${r.length-1}].role`}));let o=`chosen`in e,s=`rejected`in e;if(o||n.push(H(`error`,`MISSING_CHOSEN`,`DPO record is missing the "chosen" preference.`,{line:t,path:`chosen`})),s||n.push(H(`error`,`MISSING_REJECTED`,`DPO record is missing the "rejected" preference.`,{line:t,path:`rejected`})),o){n.push(...Sa(e.chosen,t,`chosen`)),n.push(...i(e.chosen?.content,`chosen`));let r=e.chosen?.role;typeof r==`string`&&r!==`assistant`&&n.push(H(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"chosen" role should be "assistant" (got "${r}").`,{line:t,path:`chosen.role`}))}if(s){n.push(...Sa(e.rejected,t,`rejected`)),n.push(...i(e.rejected?.content,`rejected`));let r=e.rejected?.role;typeof r==`string`&&r!==`assistant`&&n.push(H(`warning`,`PREFERENCE_ROLE_NOT_ASSISTANT`,`"rejected" role should be "assistant" (got "${r}").`,{line:t,path:`rejected.role`}))}return n}const ka={name:`dpo`,detect:e=>`chosen`in e||`rejected`in e,inspect:Oa},Aa=[`choice`,`noul`,`score`],ja=255,Ma=2,Na=255,Pa=/* @__PURE__ */ new Set([`true`,`false`]);function U(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fa(e){return typeof e==`string`&&e.trim().length>0}function W(e,t,n,r){return{code:e,path:t,message:{"en-US":n,"zh-CN":r}}}function Ia(e,t=`state`){return Fa(e)||Array.isArray(e)&&e.length>0||U(e)&&Object.keys(e).length>0?[]:[W(`DECISION_INVALID_STATE`,t,`"${t}" must be a non-empty string, object, or array.`,`"${t}" 必须是非空字符串、对象或数组。`)]}function La(e,t){let n=`${t}.criteria`;if(!U(e))return[W(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must be an option-to-description object.`,`"${n}" 必须是“选项名到描述”的对象。`)];let r=Object.keys(e).length;if(r<1||r>255)return[W(`DECISION_INVALID_CHOICE_CRITERIA`,n,`"${n}" must contain 1-255 options (got ${r}).`,`"${n}" 必须包含 1-255 个选项(当前 ${r} 个)。`)];for(let[t,r]of Object.entries(e))if(!Fa(t)||!Fa(r))return[W(`DECISION_INVALID_CHOICE_CRITERIA`,`${n}.${t}`,`Choice option names and descriptions in "${n}" must be non-empty strings.`,`"${n}" 中的选项名和描述必须是非空字符串。`)];return[]}function Ra(e,t){let n=`${t}.criteria`;return!Array.isArray(e)||e.some(e=>!Fa(e))?[W(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must be an array of non-empty level descriptions, from low to high.`,`"${n}" 必须是从低到高排列、由非空等级描述组成的数组。`)]:e.length<2||e.length>255?[W(`DECISION_INVALID_SCORE_CRITERIA`,n,`"${n}" must contain 2-255 levels (got ${e.length}).`,`"${n}" 必须包含 2-255 个等级(当前 ${e.length} 个)。`)]:[]}function za(e,t){if(e===void 0)return[];let n=`${t}.criteria`;return U(e)&&Object.entries(e).every(([e,t])=>Pa.has(e)&&typeof t==`string`)?[]:[W(`DECISION_INVALID_NOUL_CRITERIA`,n,`"${n}" is optional; when provided it must be an object with only "true" / "false" string descriptions.`,`"${n}" 为可选项;填写时必须是只包含 "true" / "false" 字符串描述的对象。`)]}function Ba(e,t){if(!U(e))return[W(`DECISION_QUESTION_NOT_OBJECT`,t,`"${t}" must be an object.`,`"${t}" 必须是对象。`)];let n=[];return e.instructions!==void 0&&typeof e.instructions!=`string`&&n.push(W(`DECISION_INVALID_INSTRUCTIONS`,`${t}.instructions`,`"${t}.instructions" must be a string when provided.`,`"${t}.instructions" 填写时必须是字符串。`)),e.type===`choice`?n.push(...La(e.criteria,t)):e.type===`noul`?n.push(...za(e.criteria,t)):e.type===`score`?n.push(...Ra(e.criteria,t)):n.push(W(`DECISION_INVALID_QUESTION_TYPE`,`${t}.type`,`"${t}.type" must be choice, noul, or score.`,`"${t}.type" 必须是 choice、noul 或 score。`)),n}function Va(e,t=`questions`){return U(e)&&Object.keys(e).length>0?[]:[W(`DECISION_INVALID_QUESTIONS`,t,`"${t}" must be a non-empty object keyed by question ID.`,`"${t}" 必须是以问题 ID 为键的非空对象。`)]}function Ha(e,t=`questions`){return Fa(e)?[]:[W(`DECISION_INVALID_QUESTION_ID`,t,`Question IDs must be non-empty strings.`,`问题 ID 必须是非空字符串。`)]}function Ua(e,t=`questions`){let n=Va(e,t);if(n.length>0)return n;let r=[];for(let[n,i]of Object.entries(e)){let e=Ha(n,t);if(e.length>0){r.push(...e);continue}r.push(...Ba(i,`${t}.${n}`))}return r}function G(e,t,n,r){return H(`error`,e,t,{line:n,path:r})}function Wa(e,t){return G(e.code,`${e.message[`en-US`]} / ${e.message[`zh-CN`]}`,t,e.path)}function Ga(e,t,n,r){if(!U(e))return[G(`DECISION_INVALID_TARGET`,`"${r}" must be an object containing a complete probability distribution. / "${r}" 必须是包含完整概率分布的对象。`,n,r)];let i=Object.keys(e).sort(),a=[...t].sort();if(i.length!==a.length||i.some((e,t)=>e!==a[t]))return[G(`DECISION_INVALID_TARGET_KEYS`,`"${r}" must contain exactly these keys: ${a.join(`, `)}. / "${r}" 必须且只能包含这些键:${a.join(`, `)}。`,n,r)];let o=0;for(let t of a){let i=e[t];if(typeof i!=`number`||!Number.isFinite(i)||i<0||i>1)return[G(`DECISION_INVALID_TARGET_PROBABILITY`,`"${r}.${t}" must be a finite number in [0, 1]. / "${r}.${t}" 必须是 [0, 1] 范围内的有限数字。`,n,`${r}.${t}`)];o+=i}return Math.abs(o-1)>1e-6?[G(`DECISION_TARGET_SUM_NOT_ONE`,`Probabilities in "${r}" must sum to 1 (got ${o}). / "${r}" 中的概率之和必须为 1(当前为 ${o})。`,n,r)]:[]}function Ka(e,t,n){let r=Object.keys(e.criteria);return typeof e.label!=`string`||!r.includes(e.label)?[G(`DECISION_INVALID_CHOICE_LABEL`,`"${n}.label" must be one of: ${r.join(`, `)}. / "${n}.label" 必须是以下选项之一:${r.join(`, `)}。`,t,`${n}.label`)]:e.target===void 0?[]:Ga(e.target,r,t,`${n}.target`)}function qa(e,t,n){return typeof e.label==`boolean`?e.target===void 0?[]:Ga(e.target,[`true`,`false`],t,`${n}.target`):[G(`DECISION_INVALID_NOUL_LABEL`,`"${n}.label" must be true or false. / "${n}.label" 必须是 true 或 false。`,t,`${n}.label`)]}function Ja(e,t,n){let r=e.criteria.length;if(typeof e.label!=`number`||!Number.isInteger(e.label)||e.label<0||e.label>=r)return[G(`DECISION_INVALID_SCORE_LABEL`,`"${n}.label" must be an integer from 0 to ${r-1}. / "${n}.label" 必须是 0 到 ${r-1} 之间的整数。`,t,`${n}.label`)];let i=Array.from({length:r},(e,t)=>String(t));return e.target===void 0?[]:Ga(e.target,i,t,`${n}.target`)}function Ya(e,t){let n=Ia(e.state).map(e=>Wa(e,t)),r=e.questions,i=Va(r);if(i.length>0)return n.push(...i.map(e=>Wa(e,t))),n;for(let[e,i]of Object.entries(r)){let r=Ha(e);if(r.length>0){n.push(...r.map(e=>Wa(e,t)));continue}let a=`questions.${e}`,o=Ba(i,a);if(o.length>0){n.push(...o.map(e=>Wa(e,t)));continue}let s=i;s.type===`choice`?n.push(...Ka(s,t,a)):s.type===`noul`?n.push(...qa(s,t,a)):n.push(...Ja(s,t,a))}return n}const Xa={name:`decision`,detect:e=>!(`messages`in e)&&(`questions`in e||`state`in e),inspect:Ya};function Za(e,t){let n=[];if(!(`wav_fn`in e))n.push(H(`error`,`MISSING_WAV_FN`,`Required field "wav_fn" is missing.`,{line:t,path:`wav_fn`}));else{let r=e.wav_fn;if(typeof r!=`string`)n.push(H(`error`,`INVALID_WAV_FN`,`"wav_fn" must be a string (got ${typeof r}).`,{line:t,path:`wav_fn`}));else if(r.trim().length===0)n.push(H(`error`,`EMPTY_WAV_FN`,`"wav_fn" must not be empty.`,{line:t,path:`wav_fn`}));else{r.startsWith(`train/`)||n.push(H(`error`,`WAV_FN_PREFIX`,`"wav_fn" must start with "train/" (got "${r}").`,{line:t,path:`wav_fn`}));let e=r.lastIndexOf(`.`),i=e>=0?r.slice(e).toLowerCase():``;i!==`.wav`&&n.push(H(`error`,`INVALID_AUDIO_EXT`,`"wav_fn" must reference a .wav file (got "${i||`(none)`}"). CosyVoice training audio must be WAV.`,{line:t,path:`wav_fn`}))}}if(!(`text`in e))n.push(H(`error`,`MISSING_TEXT`,`Required field "text" is missing.`,{line:t,path:`text`}));else{let r=e.text;typeof r==`string`?r.trim().length===0&&n.push(H(`error`,`EMPTY_TEXT`,`"text" must not be empty / whitespace-only.`,{line:t,path:`text`})):n.push(H(`error`,`INVALID_TEXT`,`"text" must be a string (got ${typeof r}).`,{line:t,path:`text`}))}return n}const Qa={name:`tts`,detect:e=>`wav_fn`in e,inspect:Za},$a=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.tif`,`.tiff`,`.webp`]);function eo(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function to(e){return/^[\x20-\x7E]+$/.test(e)}function no(e,t){let n=[];if(!(`prompt`in e))n.push(H(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(H(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(H(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}if(!(`img_path`in e))n.push(H(`error`,`MISSING_IMG_PATH`,`Required field "img_path" is missing.`,{line:t,path:`img_path`}));else{let r=e.img_path;if(typeof r!=`string`)n.push(H(`error`,`INVALID_IMG_PATH`,`"img_path" must be a string (got ${typeof r}).`,{line:t,path:`img_path`}));else if(r.trim().length===0)n.push(H(`error`,`EMPTY_IMG_PATH`,`"img_path" must not be empty.`,{line:t,path:`img_path`}));else{let e=eo(r);$a.has(e)||n.push(H(`warning`,`UNUSUAL_IMAGE_EXT`,`"img_path" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...$a].join(`, `)}.`,{line:t,path:`img_path`})),to(r)||n.push(H(`error`,`NON_ASCII_IMG_PATH`,`"img_path" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`img_path`}))}}if(`input_img`in e){let r=e.input_img;if(typeof r!=`string`)n.push(H(`error`,`INVALID_INPUT_IMG`,`"input_img" must be a string (got ${typeof r}).`,{line:t,path:`input_img`}));else if(r.trim().length===0)n.push(H(`error`,`EMPTY_INPUT_IMG`,`"input_img" must not be empty.`,{line:t,path:`input_img`}));else{let e=eo(r);$a.has(e)||n.push(H(`warning`,`UNUSUAL_INPUT_IMG_EXT`,`"input_img" points to a non-standard image extension "${e||`(none)`}". Expected one of: ${[...$a].join(`, `)}.`,{line:t,path:`input_img`})),to(r)||n.push(H(`error`,`NON_ASCII_INPUT_IMG`,`"input_img" must contain only ASCII characters (English filenames required). Got: "${r}".`,{line:t,path:`input_img`}))}}return n}const ro={name:`image`,detect:e=>`img_path`in e,inspect:no},io=/* @__PURE__ */ new Set([`.png`,`.jpg`,`.jpeg`,`.bmp`,`.webp`]),ao=/* @__PURE__ */ new Set([`.mp4`,`.mov`]);function oo(e){let t=e.lastIndexOf(`.`);return t>=0?e.slice(t).toLowerCase():``}function so(e){return/^[\x20-\x7E]+$/.test(e)}function co(e,t,n,r,i,a){if(!(n in t)){r&&e.push(H(`error`,`MISSING_FIELD`,`Required field "${n}" is missing.`,{line:a,path:n}));return}let o=t[n];if(typeof o!=`string`){e.push(H(`error`,`INVALID_FIELD`,`"${n}" must be a string (got ${typeof o}).`,{line:a,path:n}));return}if(o.trim().length===0){e.push(H(`error`,`EMPTY_FIELD`,`"${n}" must not be empty.`,{line:a,path:n}));return}let s=oo(o);i.has(s)||e.push(H(`warning`,`UNUSUAL_MEDIA_EXT`,`"${n}" points to a non-standard extension "${s||`(none)`}". Expected one of: ${[...i].join(`, `)}.`,{line:a,path:n})),so(o)||e.push(H(`error`,`NON_ASCII_PATH`,`"${n}" must contain only ASCII characters (English filenames required). Got: "${o}".`,{line:a,path:n}))}function lo(e,t){let n=[];if(!(`prompt`in e))n.push(H(`error`,`MISSING_PROMPT`,`Required field "prompt" is missing.`,{line:t,path:`prompt`}));else{let r=e.prompt;typeof r==`string`?r.trim().length===0&&n.push(H(`error`,`EMPTY_PROMPT`,`"prompt" must not be empty / whitespace-only.`,{line:t,path:`prompt`})):n.push(H(`error`,`INVALID_PROMPT`,`"prompt" must be a string (got ${typeof r}).`,{line:t,path:`prompt`}))}return co(n,e,`first_frame_path`,!0,io,t),co(n,e,`last_frame_path`,!1,io,t),co(n,e,`video_path`,!1,ao,t),n}const uo=[Qa,ro,{name:`video`,detect:e=>`first_frame_path`in e||`video_path`in e,inspect:lo},Xa,ka,Da,Ta];function fo(e,t){return t===void 0?uo.find(t=>t.detect(e))??Ta:uo.find(e=>e.name===t)||Ta}async function po(e,t){let r=n(e,{encoding:`utf8`}),i=x({input:r,crlfDelay:1/0}),a=[],o=0,s=0;for await(let e of i){if(t?.aborted)break;o++;let n=e.trim();if(n.length===0){s++;continue}a.length>=20||(n[0]!==`{`||n[n.length-1]!==`}`)&&a.push(H(`error`,`MALFORMED_LINE`,`Line does not start with '{' and end with '}'. JSONL requires one minified JSON object per line — pretty-printed JSON or arrays are not accepted here.`,{line:o}))}return{totalLines:o,blankLines:s,issues:a}}async function mo(e,t,r,i,a){let o=r?null:new Set(ga(t)),s=[],c=0,l=n(e,{encoding:`utf8`}),u=x({input:l,crlfDelay:1/0}),d=0;for await(let e of u){if(a?.aborted)break;if(d++,o&&!o.has(d))continue;let t=e.trim();if(t.length===0||(c++,s.length>=30))continue;let n;try{n=JSON.parse(t)}catch(e){s.push(H(`error`,`MALFORMED_JSON`,`JSON.parse failed: ${e.message}`,{line:d}));continue}s.push(...ho(n,d,i))}return{sampled:c,issues:s}}function ho(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return[H(`error`,`RECORD_NOT_OBJECT`,`Each line must be a JSON object, got ${Array.isArray(e)?`array`:typeof e}.`,{line:t})];let r=e;return fo(r,n).inspect(r,t)}const go={format:`jsonl`,extensions:[`.jsonl`],async validate(e,t){let n=Date.now(),r=await po(e,t.signal);if(r.totalLines===0||r.totalLines===r.blankLines)return{valid:!1,format:`jsonl`,filePath:e,errors:[H(`error`,`EMPTY_FILE`,`File contains no non-blank lines.`)],warnings:[],stats:{totalRecords:0,sampledRecords:0,durationMs:Date.now()-n}};if(r.issues.length>0)return{valid:!1,format:`jsonl`,filePath:e,errors:r.issues,warnings:[],stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:0,durationMs:Date.now()-n}};let i=await mo(e,r.totalLines,!!t.fullValidate,t.schema,t.signal),a=i.issues.filter(e=>e.severity===`error`),o=i.issues.filter(e=>e.severity===`warning`);return{valid:a.length===0,format:`jsonl`,filePath:e,errors:a,warnings:o,stats:{totalRecords:r.totalLines-r.blankLines,sampledRecords:i.sampled,durationMs:Date.now()-n}}}};function _o(e,t){return new Promise((n,r)=>{oe.open(e,{lazyEntries:!0},(e,i)=>{if(e||!i){r(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}i.readEntry(),i.on(`entry`,e=>{let r=e.fileName.replace(/\\/g,`/`);r===t||r.endsWith(`/${t}`)?n({entry:e,zipfile:i}):i.readEntry()}),i.on(`end`,()=>{i.close(),r(/* @__PURE__ */ Error(`Entry "${t}" not found in ZIP`))}),i.on(`error`,r)})})}function vo(e){return new Promise((t,n)=>{oe.open(e,{lazyEntries:!0},(e,r)=>{if(e||!r){n(/* @__PURE__ */ Error(`Failed to open ZIP: ${e?.message??`unknown error`}`));return}let i=[];r.readEntry(),r.on(`entry`,e=>{i.push(e.fileName.replace(/\\/g,`/`)),r.readEntry()}),r.on(`end`,()=>{r.close(),t(i)}),r.on(`error`,n)})})}const yo=/^[a-zA-Z0-9_-]+$/;function bo(e){let t=e.lastIndexOf(`.`);return t>0?e.slice(0,t):e}function xo(e){if(e===`__MACOSX`||e.startsWith(`__MACOSX/`))return!0;let t=e.split(`/`).filter(e=>e.length>0).pop()??``;return t===`.DS_Store`||t.startsWith(`._`)}function So(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){if(r.endsWith(`/`)||xo(r))continue;let e=r.split(`/`).filter(e=>e.length>0);for(let n of e){let e=bo(n),i=n.slice(e.length);e.length>0&&!yo.test(e)&&t.length<10&&t.push(H(`error`,`INVALID_FILENAME_CHARSET`,`File/folder name "${n}" contains invalid characters. Only a-z, A-Z, 0-9, underscore (_), and hyphen (-) are allowed.`,{path:r})),i.length>0&&!/^\.[a-zA-Z0-9]+$/.test(i)&&t.length<10&&t.push(H(`error`,`INVALID_FILENAME_CHARSET`,`File extension "${i}" in "${n}" contains invalid characters.`,{path:r}))}let i=e[e.length-1]??``,a=bo(i);if(a.length>120&&t.length<10&&t.push(H(`error`,`FILENAME_TOO_LONG`,`Filename "${i}" (without extension) exceeds 120 characters (got ${a.length}). Shorten the name and re-upload.`,{path:r})),a.length>0){let e=n.get(a);e===void 0?n.set(a,r):t.length<10&&t.push(H(`error`,`DUPLICATE_FILENAME`,`Filename "${i}" conflicts with "${e}" — names must be globally unique (ignoring extension) even across different folders.`,{path:r}))}}return t.length>=10&&t.push(H(`warning`,`FILENAME_ISSUES_TRUNCATED`,`More filename issues exist but reporting is capped at 10.`)),t}async function Co(e,t,n){let{entry:i,zipfile:a}=await _o(e,t);return new Promise((e,t)=>{a.openReadStream(i,(i,o)=>{if(i||!o){a.close(),t(i??/* @__PURE__ */ Error(`Failed to open entry stream`));return}let s=r(n);ae(o,s).then(()=>{a.close(),e()}).catch(e=>{a.close(),t(e)})})})}async function wo(e,t=100){let r=n(e,{encoding:`utf8`}),i=x({input:r,crlfDelay:1/0}),a=[],o=0;for await(let e of i){if(o++,a.length>=t)continue;let n=e.trim();if(n.length!==0)try{let e=JSON.parse(n);typeof e.wav_fn==`string`&&a.push(e.wav_fn),typeof e.img_path==`string`&&a.push(e.img_path),typeof e.input_img==`string`&&a.push(e.input_img),typeof e.first_frame_path==`string`&&a.push(e.first_frame_path),typeof e.last_frame_path==`string`&&a.push(e.last_frame_path),typeof e.video_path==`string`&&a.push(e.video_path),typeof e.image_fn==`string`&&a.push(e.image_fn),typeof e.video_fn==`string`&&a.push(e.video_fn)}catch{}}return{refs:a,totalLines:o}}const To={format:`zip`,extensions:[`.zip`],async validate(e,t){let n=Date.now(),r=[],i=[],o;try{o=await vo(e)}catch(t){return{valid:!1,format:`zip`,filePath:e,errors:[H(`error`,`ZIP_OPEN_FAILED`,`Could not open ZIP archive: ${t.message}`)],warnings:[],stats:{durationMs:Date.now()-n}}}if(o.length===0)return{valid:!1,format:`zip`,filePath:e,errors:[H(`error`,`ZIP_EMPTY`,`ZIP archive contains no entries.`)],warnings:[],stats:{durationMs:Date.now()-n}};let s=o.some(e=>e===`data.jsonl`),l=!s&&o.find(e=>e.endsWith(`/data.jsonl`));s||(l?r.push(H(`error`,`DATA_JSONL_NOT_AT_ROOT`,`"data.jsonl" must be at the ZIP root (found "${l}"). Re-package so that opening the ZIP shows data.jsonl directly, without a wrapping folder.`)):r.push(H(`error`,`MISSING_DATA_JSONL`,`ZIP archive must contain "data.jsonl" at the root. This file maps media files (e.g. .wav, .jpg) to their labels.`)));let u=So(o);for(let e of u)e.severity===`error`?r.push(e):i.push(e);let d=t.schema===`image`,f=t.schema===`video`,m=o.some(e=>e===`train/`||e.startsWith(`train/`)),h=o.some(e=>e.toLowerCase().endsWith(`.wav`));if(!m&&!d&&!f&&h&&i.push(H(`warning`,`NO_TRAIN_DIR`,`No "train/" directory found in the ZIP. Media files are typically placed under "train/" and referenced as "train/xxx.wav" in data.jsonl.`)),d){let e=o.filter(e=>{if(e===`data.jsonl`||e.endsWith(`/data.jsonl`)||e.endsWith(`/`)||xo(e))return!1;let t=e.lastIndexOf(`.`),n=t>=0?e.slice(t).toLowerCase():``;return $a.has(n)});e.length<25&&r.push(H(`error`,`INSUFFICIENT_IMAGES`,`Found ${e.length} image(s) in ZIP, but image generation fine-tuning requires at least 25 images (50+ recommended).`))}if(!s&&!l)return{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:o.length,durationMs:Date.now()-n}};let _=s?`data.jsonl`:o.find(e=>e.endsWith(`/data.jsonl`)),v=g(p(),`bl-zip-${ne(6).toString(`hex`)}`);a(v,{recursive:!0});let y=g(v,`data.jsonl`);try{await Co(e,_,y)}catch(t){return r.push(H(`error`,`EXTRACT_FAILED`,`Failed to extract "data.jsonl" from ZIP: ${t.message}`)),c(v,{recursive:!0,force:!0}),{valid:!1,format:`zip`,filePath:e,errors:r,warnings:i,stats:{durationMs:Date.now()-n}}}let b=await go.validate(y,t);if(r.push(...b.errors),i.push(...b.warnings),b.valid){let{refs:e}=await wo(y),t=new Set(o),n=_.lastIndexOf(`/`),i=n>=0?_.slice(0,n+1):``,a=[];for(let n of e){let e=n.replace(/^\.\//,``);t.has(e)||t.has(i+e)||a.push(n)}if(a.length>0){let e=a.slice(0,5).join(`, `),t=a.length>5?` (and ${a.length-5} more)`:``;r.push(H(`error`,`DANGLING_MEDIA_REFS`,`${a.length} media file(s) referenced in data.jsonl not found in ZIP: ${e}${t}`))}}return c(v,{recursive:!0,force:!0}),{valid:r.length===0,format:`zip`,filePath:e,errors:r,warnings:i,stats:{totalRecords:b.stats.totalRecords??o.length,sampledRecords:b.stats.sampledRecords,durationMs:Date.now()-n}}}};async function Eo(e){let t=h(e).toLowerCase();if(t===`.jsonl`)return Do(e);if(t===`.zip`)return Oo(e);throw new P(`Cannot inspect file with extension "${t}". Expected .jsonl or .zip.`,N.USAGE)}async function Do(e){let t=await Ao(e);if(!t)throw new P(`JSONL file is empty or contains only blank lines: ${e}`,N.USAGE);let n=ko(t);return n===`unknown`?`text`:n}async function Oo(e){let t=await jo(e,`data.jsonl`);if(!t)throw new P(`ZIP archive does not contain "data.jsonl" or it is empty: ${e}`,N.USAGE,`Audio training data must be a ZIP with data.jsonl at the root and a train/ subfolder.`);let n=ko(t);if(n===`unknown`)throw new P(`ZIP data.jsonl does not match any supported media format (expected wav_fn / img_path / first_frame_path / video_path): ${e}`,N.USAGE,`ZIP archives are for audio/image/video training data. For text data, use a .jsonl file instead.`);return n}function ko(e){let t;try{t=JSON.parse(e)}catch{throw new P(`Failed to parse first JSON record for modality detection: ${e.slice(0,120)}`,N.USAGE)}if(typeof t!=`object`||!t||Array.isArray(t))throw new P(`Expected a JSON object as the first record, got ${Array.isArray(t)?`array`:typeof t}.`,N.USAGE);return`wav_fn`in t?`audio`:`img_path`in t?`input_img`in t?`image-i2i`:`image`:`first_frame_path`in t||`video_path`in t?`last_frame_path`in t?`video-kf2v`:`video`:`unknown`}function Ao(e){return new Promise((t,r)=>{let i=n(e,{encoding:`utf8`}),a=x({input:i,crlfDelay:1/0}),o=!1;a.on(`line`,e=>{if(o)return;let n=e.trim();n.length!==0&&(o=!0,a.close(),i.destroy(),t(n))}),a.on(`close`,()=>{o||t(null)}),a.on(`error`,r),i.on(`error`,r)})}function jo(e,t){return _o(e,t).then(({entry:e,zipfile:n})=>new Promise((r,i)=>{n.openReadStream(e,(e,a)=>{if(e||!a){n.close(),i(new P(`Failed to read "${t}" from ZIP: ${e?.message}`,N.USAGE));return}let o=x({input:a,crlfDelay:1/0}),s=!1;o.on(`line`,e=>{if(s)return;let t=e.trim();t.length!==0&&(s=!0,o.close(),a.destroy(),n.close(),r(t))}),o.on(`close`,()=>{s||(n.close(),r(null))}),o.on(`error`,e=>{n.close(),i(e)})})})).catch(e=>{if(e instanceof Error&&e.message.includes(`not found in ZIP`))return null;throw e})}const Mo=[go,To];function No(e){let t=h(e).toLowerCase(),n=Mo.find(e=>e.extensions.includes(t));if(!n){let e=Mo.flatMap(e=>e.extensions).join(`, `);throw new P(`Unsupported dataset format "${t||`(none)`}". Supported: ${e}`,N.USAGE,`Convert your data to one of the supported formats and re-run.`)}return n}function Po(e){Mo.some(t=>t.format===e.format)||Mo.push(e)}async function K(e,t={}){let{bytes:n}=ma(e,t.maxBytes??209715200),r=await No(e).validate(e,t);return r.stats.bytes===void 0&&(r.stats.bytes=n),r}function Fo(){return Mo.map(e=>({format:e.format,extensions:[...e.extensions]}))}function Io(e){let t=[];e.line!==void 0&&t.push(`line ${e.line}`),e.path&&t.push(e.path);let n=t.length?` [${t.join(` · `)}]`:``;return` ${e.severity.toUpperCase()} ${e.code}${n}: ${e.message}`}const Lo=`decision-model-preview`,Ro=[`cn-beijing`,`ap-southeast-1`],zo=`cn-beijing`,Bo=[`label`,`target`];function Vo(e){if(!U(e))return e;let t=e.questions;return U(t)&&typeof t.type!=`string`?t:e}function Ho(e){if(!U(e))return e;let t={};for(let[n,r]of Object.entries(e)){if(!U(r)){t[n]=r;continue}let e={...r};for(let t of Bo)delete e[t];t[n]=e}return t}async function Uo(e,t,n){return e.requestJson({path:wr(),method:`POST`,body:t,signal:n})}async function Wo(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.status&&n.set(`status`,t.status),t.model&&n.set(`model`,t.model);let r=wr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Go(e,t,n){return e.requestJson({path:Tr(t),method:`GET`,signal:n})}async function Ko(e,t,n){return e.requestJson({path:Er(t),method:`POST`,signal:n})}async function qo(e,t,n){return e.requestJson({path:Tr(t),method:`DELETE`,signal:n})}async function Jo(e,t,n={}){let r=new URLSearchParams;n.pageNo!==void 0&&r.set(`page_no`,String(n.pageNo)),n.pageSize!==void 0&&r.set(`page_size`,String(n.pageSize));let i=Dr(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Yo(e,t,n){return e.requestJson({path:Or(t),method:`GET`,signal:n})}async function Xo(e,t,n,r,i){let a=new URLSearchParams;return a.set(`model_name`,r),e.requestJson({path:`${kr(t,n)}?${a.toString()}`,method:`GET`,signal:i})}function Zo(e,t){let n=new URLSearchParams;for(let[e,r]of Object.entries(t))r!==void 0&&r!==``&&n.set(e,String(r));return n.toString()?`${e}?${n.toString()}`:e}async function Qo(e,t={}){return e.requestJson({path:Zo(Ar(),{model:t.model,lang:t.lang}),method:`GET`,signal:t.signal})}async function $o(e,t,n){return e.requestJson({path:jr(),method:`POST`,body:t,signal:n})}async function es(e,t={}){let n=Zo(jr(),{status:t.status,model:t.model,template_id:t.templateId,quant_spec:t.quantSpec,quant_method:t.quantMethod,start_time:t.startTime,end_time:t.endTime,search_key:t.searchKey,select_key:t.selectKey,sort_order:t.sortOrder,page_no:t.pageNo,page_size:t.pageSize});return e.requestJson({path:n,method:`GET`,signal:t.signal})}async function ts(e,t,n){return e.requestJson({path:Mr(t),method:`GET`,signal:n})}async function ns(e,t,n={}){return e.requestJson({path:Zo(Pr(t),{offset:n.offset,line:n.line}),method:`GET`,signal:n.signal})}async function rs(e,t,n){return e.requestJson({path:Nr(t),method:`POST`,signal:n})}async function is(e,t,n){return e.requestJson({path:Mr(t),method:`DELETE`,signal:n})}const as={sft:{server:`sft`,method:`sft`,variant:`full`},"sft-lora":{server:`efficient_sft`,method:`sft`,variant:`lora`},dpo:{server:`dpo_full`,method:`dpo`,variant:`full`},"dpo-lora":{server:`dpo_lora`,method:`dpo`,variant:`lora`},cpt:{server:`cpt`,method:`cpt`,variant:`full`}},os=Object.keys(as),ss=`sft-lora`;function cs(e){return e in as}function ls(e){let{method:t,variant:n}=as[e];return{method:t,variant:n}}function us(e,t){if(!e)return!1;let{method:n,variant:r}=as[t];if(e.supports?.[n]!==!0)return!1;let i=e.trainingTypes?.[n];return Array.isArray(i)&&i.includes(r)}function ds(e){return e?os.filter(t=>us(e,t)):[]}async function fs(e,t){return await Zi(Ht(e),t)}const ps=`INSUFFICIENT_SAMPLES`;function ms(e){let{recordCount:t,batchSize:n}=e;return t>n?{ok:!0}:{ok:!1,issue:{severity:`error`,code:ps,message:`Training dataset has ${t} sample(s), which is not greater than batch_size (${n}).`},hint:[`The platform requires the number of training samples to exceed batch_size.`,`Options:`,` • add more data (recommended: comfortably more than batch_size, since the`,` platform also holds back a default 0.9 train split),`,` • lower --batch-size (server clamps to a minimum of 8).`].join(`
|
|
13
13
|
`)}}function hs(e){let t={};if(t.n_epochs=e.nEpochs===void 0?3:e.nEpochs,e.learningRate!==void 0&&(t.learning_rate=e.learningRate),e.maxLength!==void 0&&(t.max_length=e.maxLength),e.batchSize!==void 0){let n=e.batchSize;n<8&&(n=8),n>1024&&(n=1024),t.batch_size=n}return t}function gs(e,t,n){return{clientTrainingType:e,serverTrainingType:t,acceptedExtensions:[`.jsonl`],async validate(e,t,r){return K(e,{...r,schema:n})},resolveHyperParameters(e,t){return hs(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}}const _s=gs(`sft`,`sft`,`chatml`),vs={lm_max_epoch:60,lm_step:5,lm_num:3,lm_batch_size:1e3,fm_max_epoch:100,fm_step:10,fm_num:3,fm_batch_size:2e3},ys={learning_rate:`3e-5`,max_steps:800,eval_steps:200,max_token_length:`1k`,gradient_clip:.5,weight_decay:.02,max_pixels:`2k`,val_img_size:`2k`,generation_type:`t2i`,lora_rank:32,save_total_limit:10,split:.9},bs={...ys,max_pixels:`1k`,val_img_size:`1k`,generation_type:`i2i`},xs={n_epochs:50,learning_rate:`2e-5`,split:.5,max_split_val_dataset_sample:5,eval_epochs:20,save_total_limit:10,lora_rank:32,lora_alpha:32};function Ss(e){return e===`image`||e===`image-i2i`}function Cs(e){return e===`video`||e===`video-kf2v`}function ws(e){return typeof e==`string`&&/wan2\.5/i.test(e)}function Ts(e){return typeof e==`string`&&/wan2\.7/i.test(e)}const Es=[_s,{clientTrainingType:`sft-lora`,serverTrainingType:`efficient_sft`,acceptedExtensions:[`.jsonl`,`.zip`],async validate(e,t,n){if(t===`audio`)return K(e,{...n,schema:`tts`});if(Ss(t))return K(e,{...n,schema:`image`,maxBytes:pa});if(Cs(t)){let r=await K(e,{...n,schema:`video`,maxBytes:pa});if(typeof n.model==`string`&&n.model.length>0){let e=/kf2v/i.test(n.model),i=t===`video-kf2v`;e&&!i?r.errors.push(H(`error`,`KF2V_DATA_MISMATCH`,`Model "${n.model}" is a first+last-frame (kf2v) model but the data has no "last_frame_path". kf2v training data must include a last frame per record.`)):!e&&i&&r.warnings.push(H(`warning`,`I2V_LAST_FRAME_IGNORED`,`Model "${n.model}" is a first-frame (i2v) model but the data includes "last_frame_path"; the last frame will be ignored during training.`))}return r.valid=r.errors.length===0,r}return K(e,{...n,schema:`chatml`})},resolveHyperParameters(e,t){if(e===`audio`)return{...vs};if(Ss(e)){let n={...e===`image-i2i`?bs:ys};return t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}if(Cs(e)){let e=t.model??t.baseModel,n={...xs,batch_size:Ts(e)?1:4,max_pixels:Ts(e)?102400:ws(e)?36864:262144};return t.nEpochs!==void 0&&(n.n_epochs=t.nEpochs),t.batchSize!==void 0&&(n.batch_size=t.batchSize),t.learningRate!==void 0&&(n.learning_rate=t.learningRate),n}return hs(t)},shouldSkipGate(e,t){return!(t!==`audio`&&!Ss(t)&&!Cs(t)||e!==`batch_size`)},shouldSkipCapabilityCheck(e){return e===`audio`||Ss(e)||Cs(e)}},gs(`dpo`,`dpo_full`,`dpo`),gs(`dpo-lora`,`dpo_lora`,`dpo`),{clientTrainingType:`cpt`,serverTrainingType:`cpt`,acceptedExtensions:[`.jsonl`],async validate(e,t,n){return K(e,{...n,schema:`cpt`,maxBytes:da})},resolveHyperParameters(e,t){return hs(t)},shouldSkipGate(e,t){return!1},shouldSkipCapabilityCheck(e){return!1}}];function Ds(e){let t=Es.find(t=>t.clientTrainingType===e);if(!t){let t=Es.map(e=>e.clientTrainingType).join(`, `);throw new P(`Unknown training type "${e}".`,N.USAGE,`Supported training types: ${t}.`)}return t}function Os(){return Es.map(e=>e.clientTrainingType)}const ks=`zeldaEasy.broadscope-platform.modelCenter.getModelPrice`,As=`zeldaEasy.broadscope-platform.modelInstance.calculateDatasetsTotalTokens`,js=`zeldaEasy.broadscope-platform.modelInstance.estimateFinetuneTokens`;async function Ms(e,t){return V(await e.console(ks,{query:{type:0,modelId:t}}))}async function Ns(e,t,n){return V(await e.console(As,{input:{trainDatasetIds:t,hyperParams:n}}))}async function Ps(e,t,n,r){let i=JSON.stringify({useDefault:!1,userDefinedObj:{batch_size:16,eval_steps:50,learning_rate:`7e-6`,lr_scheduler_type:`linear`,max_length:8192,n_epochs:r,split:.9,save_total_limit:`3`,resume_from_checkpoint:!1,save_strategy:`epoch`},useQwenMixedStrategy:!1});return V(await e.console(js,{input:{trainingType:`cpt`,instanceName:`${t}_cli_estimate`,algorithmType:100,bizType:100,trainDatasetIds:n,hyperParams:i,bailianTrainModel:t,validationDatasetIds:``,jobName:`${t}_cli_estimate`,priority:`L0`}}))}function Fs(e){return e?{"x-acs-req-uuid":e,"X-DashScope-RequestId":e}:void 0}async function Is(e,t,n){return e.requestJson({path:Fr(),method:`POST`,body:t,signal:n})}async function Ls(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.plan!==void 0&&n.set(`plan`,t.plan);let r=Fr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Rs(e,t,n){return e.requestJson({path:Ir(t),method:`GET`,signal:n})}async function zs(e,t,n={}){let r=new URLSearchParams;n.pageNo!==void 0&&r.set(`page_no`,String(n.pageNo)),n.pageSize!==void 0&&r.set(`page_size`,String(n.pageSize)),n.includeDeleted!==void 0&&r.set(`include_deleted`,String(n.includeDeleted)),n.statuses!==void 0&&r.set(`statuses`,n.statuses.join(`,`)),n.chargeTypes!==void 0&&r.set(`charge_types`,n.chargeTypes.join(`,`));let i=Lr(t),a=r.toString()?`${i}?${r.toString()}`:i;return e.requestJson({path:a,method:`GET`,signal:n.signal})}async function Bs(e,t,n,r){return e.requestJson({path:Rr(t,n),method:`GET`,signal:r})}async function Vs(e,t,n,r){return e.requestJson({path:Hr(t,n),method:`GET`,signal:r})}async function Hs(e,t,n,r={}){return e.requestJson({path:Lr(t),method:`POST`,body:n,headers:Fs(r.requestId),signal:r.signal})}async function Us(e,t,n,r,i={}){return e.requestJson({path:zr(t,n),method:`PUT`,body:r,headers:Fs(i.requestId),signal:i.signal})}async function Ws(e,t,n,r,i={}){return e.requestJson({path:Br(t,n),method:`PUT`,body:r,headers:Fs(i.requestId),signal:i.signal})}async function Gs(e,t,n,r={}){let i=Rr(t,n),a=new URLSearchParams;return r.reason!==void 0&&a.set(`reason`,r.reason),e.requestJson({path:a.toString()?`${i}?${a.toString()}`:i,method:`DELETE`,headers:Fs(r.requestId),signal:r.signal})}async function Ks(e,t,n,r){return e.requestJson({path:Vr(t),method:`PUT`,body:{overflow_strategy:n},signal:r})}async function qs(e,t,n){return e.requestJson({path:Ir(t),method:`DELETE`,signal:n})}async function Js(e,t={}){let n=new URLSearchParams;t.pageNo!==void 0&&n.set(`page_no`,String(t.pageNo)),t.pageSize!==void 0&&n.set(`page_size`,String(t.pageSize)),t.version&&n.set(`version`,t.version),t.modelSource&&n.set(`model_source`,t.modelSource);let r=Gr(),i=n.toString()?`${r}?${n.toString()}`:r;return e.requestJson({path:i,method:`GET`,signal:t.signal})}async function Ys(e,t,n,r,i){return e.requestJson({path:Ur(t),method:`PUT`,body:n,headers:Fs(i),signal:r})}async function Xs(e,t,n,r){return e.requestJson({path:Wr(t),method:`PUT`,body:n,signal:r})}const q={LORA:`lora`,PTU:`ptu`,MU:`mu`},Zs=q.LORA;function Qs(e){return e===`audio`?q.MU:Zs}const $s={POST_PAY:`POST_PAY`,PRE_PAY:`PRE_PAY`},ec=$s.POST_PAY,J={POST_PAID:`post_paid`,PRE_PAID:`pre_paid`};function tc(e,t){if(t||e.inputTpm!==void 0||e.outputTpm!==void 0){if(e.inputTpm===void 0||e.outputTpm===void 0)return`--input-tpm and --output-tpm must be provided together.
|
|
14
14
|
必须同时提供 --input-tpm 和 --output-tpm。`;if(!Number.isSafeInteger(e.inputTpm)||e.inputTpm<0)return`--input-tpm must be a non-negative safe integer in kTPM.
|
|
15
15
|
--input-tpm 必须是非负安全整数,单位为 kTPM。`;if(!Number.isSafeInteger(e.outputTpm)||e.outputTpm<0)return`--output-tpm must be a non-negative safe integer in kTPM.
|
|
@@ -23,7 +23,7 @@ plan=ptu 必须提供 --charge-type,且只能为 pre_paid 或 post_paid。`:e.
|
|
|
23
23
|
--service-tier 只能为 ptu_fast 或 ptu_default。`:e.serviceTier===`ptu_default`&&e.chargeType===J.POST_PAID?`ptu_default only supports pre_paid.
|
|
24
24
|
ptu_default 仅支持 pre_paid。`:e.chargeType===J.POST_PAID&&rc(e)?`Prepaid flags are not allowed with --charge-type post_paid.
|
|
25
25
|
--charge-type post_paid 不允许提供预付费参数。`:tc(e,!0)??ic(e,e.chargeType===J.PRE_PAID):`--thinking-output-tpm is not supported by current reservation models.
|
|
26
|
-
当前吞吐预留模型不支持 --thinking-output-tpm。`},async resolve(e){let t={charge_type:e.flags.chargeType,ptu_capacity:nc(e.flags)};e.flags.serviceTier!==void 0&&(t.service_tier=e.flags.serviceTier),e.flags.suffix!==void 0&&(t.suffix=e.flags.suffix);let n=ac(e.flags);return n!==void 0&&(t.pre_paid_info=n),{body:t}}},cc={name:q.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||ec,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new P(`No mu-plan template found for model "${e.model}". Run \`${e.binName} deploy models --source base\` to inspect available models, or pass --deploy-spec explicitly.`,N.USAGE);try{let a=await Js(e.client,{modelSource:`base`,pageSize:100,version:`v1.0`}),o=((a.output??a.data)?.models??[]).find(t=>t.model_name===e.model)?.plans?.find(({plan:e})=>e===q.MU)?.templates??[];if(o.length===0)throw i();let s=t===$s.POST_PAY?J.POST_PAID:J.PRE_PAID,c=o.find(e=>e.charge_type===s)??o[0];if(!c?.deploy_spec&&!c?.template_id)throw i();n=c.deploy_spec??c.template_id,r===void 0&&(r=c.roles?.unified?.capacity_unit_per_instance??1)}catch(e){throw e instanceof P?e:new P(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,N.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},lc={[q.LORA]:oc,[q.PTU]:sc,[q.MU]:cc};function uc(e){let t=lc[e];if(!t)throw new P(`Unsupported plan "${e}". Supported plans: ${Object.keys(lc).join(`, `)}.`,N.USAGE);return t}const dc=`zeldaEasy.broadscope-platform.modelInstance.startModelService`,fc=`zeldaEasy.broadscope-platform.modelInstance.stopModelService`,pc=`zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel`;async function mc(e,t){return V(await e.console(dc,{input:{modelServiceId:t}}))}async function hc(e,t){return V(await e.console(fc,{input:{modelServiceId:t}}))}async function gc(e){let t=[],n=1;for(;;){let r=V(await e.console(pc,{input:{pageNo:n,pageSize:50}})),i=r.records??[];t.push(...i);let a=r.pageCount??1;if(n>=a||i.length===0)break;n++}return t}function _c(e,t){return e.find(e=>e.modelServiceId===t||e.deployedModel===t||e.deployed_model===t)}const vc=`speech-biasing`;function yc(e,t){return{model:vc,input:{action:e,...t}}}async function bc(e,t,n,r){return e.requestJson({path:cr(),method:`POST`,body:yc(t,n),signal:r})}function xc(e,t,n){return bc(e,`create_vocabulary`,{target_model:t.targetModel,prefix:t.prefix,vocabulary:t.vocabulary},n)}function Sc(e,t={},n){let r={};return t.prefix!==void 0&&(r.prefix=t.prefix),t.pageIndex!==void 0&&(r.page_index=t.pageIndex),t.pageSize!==void 0&&(r.page_size=t.pageSize),bc(e,`list_vocabulary`,r,n)}function Cc(e,t,n){return bc(e,`query_vocabulary`,{vocabulary_id:t},n)}function wc(e,t,n,r){return bc(e,`update_vocabulary`,{vocabulary_id:t,vocabulary:n},r)}function Tc(e,t,n){return bc(e,`delete_vocabulary`,{vocabulary_id:t},n)}function Ec(e,t){try{return JSON.parse(e)}catch(e){throw new F(`${t} is not valid JSON — ${e.message}`)}}function Dc(e){let t=Ec(e,`--vocabulary`);if(!t||typeof t!=`object`||Array.isArray(t))throw new F(`--vocabulary must decode to a JSON object of word→weight.`);for(let[e,n]of Object.entries(t))if(typeof n!=`number`||!Number.isFinite(n))throw new F(`--vocabulary weight for "${e}" must be a number.`);return t}function Oc(e,t){let n=`--words`,r=Ec(e,n),i;if(Array.isArray(r))i=r.map((e,t)=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new F(`${n} entry #${t} must be an object with string "text" and number "weight".`);let r=e;if(typeof r.text!=`string`||typeof r.weight!=`number`)throw new F(`${n} entry #${t} must have a string "text" and a number "weight".`);if(!Number.isFinite(r.weight))throw new F(`${n} entry #${t} weight must be a finite number.`);return{text:r.text,weight:r.weight,...typeof r.lang==`string`?{lang:r.lang}:{}}});else if(!r||typeof r!=`object`)throw new F(`${n} must decode to a JSON object or array.`);else{i=[];for(let[e,a]of Object.entries(r)){if(typeof a!=`number`||!Number.isFinite(a))throw new F(`${n} weight for "${e}" must be a number.`);i.push({text:e,weight:a,...t?{lang:t}:{}})}}if(i.length===0)throw new F(`${n} must contain at least one hot word.`);return i}const kc={output:{type:`string`,valueHint:`<format>`,description:{"en-US":`Output format: text, json`,"zh-CN":`输出格式:text、json`}},timeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Request timeout`,"zh-CN":`请求超时时间`}},quiet:{type:`switch`,description:{"en-US":`Suppress non-essential output`,"zh-CN":`隐藏非必要输出`}},verbose:{type:`switch`,description:{"en-US":`Print HTTP request/response details`,"zh-CN":`打印 HTTP 请求和响应详情`}},dryRun:{type:`switch`,description:{"en-US":`Dry run mode`,"zh-CN":`仅预览,不实际执行`}},config:{type:`string`,valueHint:`<name>`,description:{"en-US":`Use a config profile for this command`,"zh-CN":`为当前命令使用指定配置 Profile`}},help:{type:`switch`,description:{"en-US":`Show help`,"zh-CN":`显示帮助信息`}},version:{type:`switch`,description:{"en-US":`Print version`,"zh-CN":`显示版本信息`}}},Ac={concurrent:{type:`number`,valueHint:`<n>`,description:{"en-US":`Run N parallel requests (default: 1)`,"zh-CN":`并行发送 N 个请求(默认:1)`}}},jc={async:{type:`switch`,description:{"en-US":`Return async task id without waiting`,"zh-CN":`直接返回异步任务 ID,不等待任务完成`}}},Mc={apiKey:{type:`string`,valueHint:`<key>`,description:{"en-US":`API key`,"zh-CN":`API Key`}},baseUrl:{type:`string`,valueHint:`<url>`,description:{"en-US":`API base URL`,"zh-CN":`API Base URL`}}},Nc={consoleRegion:{type:`string`,valueHint:`<region>`,description:{"en-US":`Console gateway region (e.g. cn-beijing, ap-southeast-1)`,"zh-CN":`控制台网关地域(例如 cn-beijing、ap-southeast-1)`}},consoleSite:{type:`string`,valueHint:`<site>`,description:{"en-US":`Console site: domestic, international`,"zh-CN":`控制台站点:domestic、international`}},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:{"en-US":`Switch agent UID for delegated access`,"zh-CN":`切换代理访问的 UID`}},workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID (env: BAILIAN_WORKSPACE_ID)`,"zh-CN":`Workspace ID(环境变量:BAILIAN_WORKSPACE_ID)`}}},Pc={accessKeyId:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`,"zh-CN":`阿里云 Access Key ID(环境变量:ALIBABA_CLOUD_ACCESS_KEY_ID)`}},accessKeySecret:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`,"zh-CN":`阿里云 Access Key Secret(环境变量:ALIBABA_CLOUD_ACCESS_KEY_SECRET)`}},securityToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN)`,"zh-CN":`阿里云 STS Security Token(环境变量:ALIBABA_CLOUD_SECURITY_TOKEN)`}}};function Fc(e){return e.auth===`apiKey`?Mc:e.auth===`console`?Nc:e.auth===`openapi`?Pc:{}}function Ic(e){return e}const Lc=1;function Rc(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function zc(e,t){return`${Rc(e||`image`,`image`)}_${Rc((t||``).substring(0,20),`untitled`)}_${Date.now()}`}function Bc(e=f()){let t=process.env.HERMES_HOME?.trim();if(t)return Vc(t);if(process.platform===`win32`){let t=process.env.LOCALAPPDATA?.trim();return t?g(t,`hermes`):g(e,`AppData`,`Local`,`hermes`)}return g(e,`.hermes`)}function Vc(e){return e===`~`?f():e.startsWith(`~/`)||e.startsWith(`~\\`)?g(f(),e.slice(2)):e}const Hc=()=>g(f(),`bailian-output`);function Uc(e,t){let n=t?.flagDir||e.outputDir||Hc(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function Wc(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function Gc(e){return o(e===`-`?0:e,`utf-8`)}async function Kc(e,t){let n=[],r=0;async function i(){for(;r<e.length;){let t=r++;n[t]=await e[t]()}}let a=Array.from({length:Math.min(t,e.length)},()=>i());return await Promise.all(a),n}function qc(e,t=`boolean`){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}throw new P(`Invalid ${t} value "${String(e)}". Use true or false.`,N.USAGE)}function Jc(e,t=`boolean`){if(e!=null)return qc(e,t)}function Yc(e,t,n=`boolean`){let r=Jc(e,n);return r===void 0?t:r}function Xc(e,t){return Jc(e,`watermark`)??t??!0}const Zc=/^[a-z0-9][a-z0-9.-]{0,63}$/,Qc=/^bailian-[a-z0-9-]{1,64}$/,$c=/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]{1,20})?$/;function el(e,t){let n=e[t];if(typeof n!=`string`)return;let r=n.trim();return r.length>0?r:void 0}function tl(e){if(!e)return`unknown`;let t=e.toLowerCase().replace(/[\s_]+/g,`-`);return Zc.test(t)?t:`unknown`}function nl(e){let t=el(e,`BAILIAN_CALLER_TYPE`)?.toLowerCase();if(t!==`agent`&&t!==`ai_agent`)return{callerType:`unknown`};let n=el(e,`BAILIAN_SKILL_NAME`)?.toLowerCase(),r=n!==void 0&&Qc.test(n)?n:void 0,i=el(e,`BAILIAN_SKILL_VERSION`),a=r!==void 0&&i!==void 0&&$c.test(i)?i:void 0;return{callerType:`agent`,callerName:tl(el(e,`BAILIAN_CALLER_NAME`)),...r===void 0?{}:{skillName:r},...a===void 0?{}:{skillVersion:a}}}function rl(e){let t={command:e.command,timestamp:(/* @__PURE__ */ new Date()).toISOString(),durationMs:e.durationMs,success:e.success,cliVersion:e.cliVersion,nodeVersion:process.version,os:process.platform,callerType:e.caller.callerType};return e.caller.callerType===`agent`&&(t.callerName=e.caller.callerName,e.caller.skillName!==void 0&&(t.skillName=e.caller.skillName),e.caller.skillVersion!==void 0&&(t.skillVersion=e.caller.skillVersion)),e.authMethod&&(t.authMethod=e.authMethod),!e.success&&e.error&&(e.error.message&&(t.errorMessage=e.error.message),e.error.exitCode!==void 0&&(t.exitCode=e.error.exitCode),e.error.httpStatus!==void 0&&(t.httpStatus=e.error.httpStatus),e.error.requestId&&(t.requestId=e.error.requestId)),e.params&&Object.keys(e.params).length>0&&(t.params=e.params),t}function il(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function al(e){let{command:t,params:n,...r}=e,i={et:`EXP`,ext:r,c1:n,c2:e.success?`success`:`failure`};return e.httpStatus!==void 0&&(i.c3=String(e.httpStatus)),e.errorMessage&&(i.c4=il(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let Y;function ol(){return Y||(process.env.NODE_ENV===`development`?(Y=`dev`,Y):process.env.BAILIAN_COMPILED===`1`?(Y=`prod`,Y):(Y=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,Y))}var sl=/* @__PURE__ */ je(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=8)})([function(e,t){e.exports=Pe(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=Pe(`dns`)},function(e,t){e.exports=Pe(`util`)},function(e,t){e.exports=Pe(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},ee=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},ne=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},x=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},se=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},S=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},C=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},w=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},de=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},D=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},O=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},fe=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},k=/* @__PURE__ */ new Map,A=/* @__PURE__ */ new Map;k.set(`Baiduspider-render`,i),k.set(`Baiduspider+`,i),k.set(`Baiduspider-image+`,i),k.set(`360Spider`,a),k.set(`360Spider-Image`,a),k.set(`bingbot`,o),k.set(`Googlebot`,s),k.set(`YandexRenderResourcesBot`,c),k.set(`spider`,l),k.set(`Dataprovider.com`,u),k.set(`AhrefsBot`,d),k.set(`BitSightBot`,f),k.set(`oBot`,p),k.set(`Cincraw`,m),k.set(`DingTalkBot-LinkService`,h),k.set(`YisouSpider`,g),k.set(`Bytespider`,_),k.set(`ev-crawler`,v),k.set(`bitdiscovery`,y),k.set(`Spider`,b),k.set(`Ai2Bot-Dolma`,ee),k.set(`dianjing_ad_spider`,te),A.set(`Baiduspider-render`,ne),A.set(`Baiduspider+`,ne),A.set(`Baiduspider-image+`,ne),A.set(`360Spider`,re),A.set(`360Spider-Image`,re),A.set(`bingbot`,ie),A.set(`Googlebot`,x),A.set(`YandexRenderResourcesBot`,ae),A.set(`spider`,oe),A.set(`Dataprovider.com`,se),A.set(`AhrefsBot`,ce),A.set(`BitSightBot`,le),A.set(`oBot`,S),A.set(`Cincraw`,C),A.set(`DingTalkBot-LinkService`,w),A.set(`YisouSpider`,T),A.set(`Bytespider`,E),A.set(`ev-crawler`,ue),A.set(`bitdiscovery`,de),A.set(`Spider`,D),A.set(`Ai2Bot-Dolma`,O),A.set(`dianjing_ad_spider`,fe);let pe={productHandlerMap:k,commentHandlerMap:A,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,pe),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=/* @__PURE__ */ new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,"DEFAULT_MODEL_HANDLER_KEY",{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,"createUAInfo",{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,"runTask",{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function y(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:(/* @__PURE__ */ new Date()).getTimezoneOffset()},e&&(this._config=c(this._config,e))}y.prototype={constructor:y,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||(/* @__PURE__ */ new Date()).getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var b=y,ee=n(3),te=n.n(ee),ne=n(4),re=n(5),ie=n.n(re);function x(e){return(x=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e})(e)}function ae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function oe(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ae(Object(n),!0).forEach(function(t){se(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ae(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function se(e,t,n){return(t=(function(e){var t=(function(e,t){if(x(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(x(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return x(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ce(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=S(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
26
|
+
当前吞吐预留模型不支持 --thinking-output-tpm。`},async resolve(e){let t={charge_type:e.flags.chargeType,ptu_capacity:nc(e.flags)};e.flags.serviceTier!==void 0&&(t.service_tier=e.flags.serviceTier),e.flags.suffix!==void 0&&(t.suffix=e.flags.suffix);let n=ac(e.flags);return n!==void 0&&(t.pre_paid_info=n),{body:t}}},cc={name:q.MU,validateFlags(){},async resolve(e){let t=e.flags.billingMethod||ec,n=e.flags.deploySpec,r=e.flags.capacity;if(!e.dryRun&&!n){let i=()=>new P(`No mu-plan template found for model "${e.model}". Run \`${e.binName} deploy models --source base\` to inspect available models, or pass --deploy-spec explicitly.`,N.USAGE);try{let a=await Js(e.client,{modelSource:`base`,pageSize:100,version:`v1.0`}),o=((a.output??a.data)?.models??[]).find(t=>t.model_name===e.model)?.plans?.find(({plan:e})=>e===q.MU)?.templates??[];if(o.length===0)throw i();let s=t===$s.POST_PAY?J.POST_PAID:J.PRE_PAID,c=o.find(e=>e.charge_type===s)??o[0];if(!c?.deploy_spec&&!c?.template_id)throw i();n=c.deploy_spec??c.template_id,r===void 0&&(r=c.roles?.unified?.capacity_unit_per_instance??1)}catch(e){throw e instanceof P?e:new P(`Failed to auto-pick template for plan=mu: ${e.message}. Pass --deploy-spec explicitly.`,N.USAGE)}}let i={capacity:r??1,billing_method:t};return n&&(i.deploy_spec=n),{body:i}}},lc={[q.LORA]:oc,[q.PTU]:sc,[q.MU]:cc};function uc(e){let t=lc[e];if(!t)throw new P(`Unsupported plan "${e}". Supported plans: ${Object.keys(lc).join(`, `)}.`,N.USAGE);return t}const dc=`zeldaEasy.broadscope-platform.modelInstance.startModelService`,fc=`zeldaEasy.broadscope-platform.modelInstance.stopModelService`,pc=`zeldaEasy.broadscope-platform.modelInstance.listIndependentDeployedModel`;async function mc(e,t){return V(await e.console(dc,{input:{modelServiceId:t}}))}async function hc(e,t){return V(await e.console(fc,{input:{modelServiceId:t}}))}async function gc(e){let t=[],n=1;for(;;){let r=V(await e.console(pc,{input:{pageNo:n,pageSize:50}})),i=r.records??[];t.push(...i);let a=r.pageCount??1;if(n>=a||i.length===0)break;n++}return t}function _c(e,t){return e.find(e=>e.modelServiceId===t||e.deployedModel===t||e.deployed_model===t)}const vc=`speech-biasing`;function yc(e,t){return{model:vc,input:{action:e,...t}}}async function bc(e,t,n,r){return e.requestJson({path:cr(),method:`POST`,body:yc(t,n),signal:r})}function xc(e,t,n){return bc(e,`create_vocabulary`,{target_model:t.targetModel,prefix:t.prefix,vocabulary:t.vocabulary},n)}function Sc(e,t={},n){let r={};return t.prefix!==void 0&&(r.prefix=t.prefix),t.pageIndex!==void 0&&(r.page_index=t.pageIndex),t.pageSize!==void 0&&(r.page_size=t.pageSize),bc(e,`list_vocabulary`,r,n)}function Cc(e,t,n){return bc(e,`query_vocabulary`,{vocabulary_id:t},n)}function wc(e,t,n,r){return bc(e,`update_vocabulary`,{vocabulary_id:t,vocabulary:n},r)}function Tc(e,t,n){return bc(e,`delete_vocabulary`,{vocabulary_id:t},n)}function Ec(e,t){try{return JSON.parse(e)}catch(e){throw new F(`${t} is not valid JSON — ${e.message}`)}}function Dc(e){let t=Ec(e,`--vocabulary`);if(!t||typeof t!=`object`||Array.isArray(t))throw new F(`--vocabulary must decode to a JSON object of word→weight.`);for(let[e,n]of Object.entries(t))if(typeof n!=`number`||!Number.isFinite(n))throw new F(`--vocabulary weight for "${e}" must be a number.`);return t}function Oc(e,t){let n=`--words`,r=Ec(e,n),i;if(Array.isArray(r))i=r.map((e,t)=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new F(`${n} entry #${t} must be an object with string "text" and number "weight".`);let r=e;if(typeof r.text!=`string`||typeof r.weight!=`number`)throw new F(`${n} entry #${t} must have a string "text" and a number "weight".`);if(!Number.isFinite(r.weight))throw new F(`${n} entry #${t} weight must be a finite number.`);return{text:r.text,weight:r.weight,...typeof r.lang==`string`?{lang:r.lang}:{}}});else if(!r||typeof r!=`object`)throw new F(`${n} must decode to a JSON object or array.`);else{i=[];for(let[e,a]of Object.entries(r)){if(typeof a!=`number`||!Number.isFinite(a))throw new F(`${n} weight for "${e}" must be a number.`);i.push({text:e,weight:a,...t?{lang:t}:{}})}}if(i.length===0)throw new F(`${n} must contain at least one hot word.`);return i}const kc={introspect:{type:`switch`,description:{"en-US":`Print the machine-readable command schema (JSON) and exit`,"zh-CN":`输出机器可读的命令说明(JSON)并退出`}},output:{type:`string`,valueHint:`<format>`,description:{"en-US":`Output format: text, json`,"zh-CN":`输出格式:text、json`}},timeout:{type:`number`,valueHint:`<seconds>`,description:{"en-US":`Request timeout`,"zh-CN":`请求超时时间`}},quiet:{type:`switch`,description:{"en-US":`Suppress non-essential output`,"zh-CN":`隐藏非必要输出`}},verbose:{type:`switch`,description:{"en-US":`Print HTTP request/response details`,"zh-CN":`打印 HTTP 请求和响应详情`}},dryRun:{type:`switch`,description:{"en-US":`Dry run mode`,"zh-CN":`仅预览,不实际执行`}},config:{type:`string`,valueHint:`<name>`,description:{"en-US":`Use a config profile for this command`,"zh-CN":`为当前命令使用指定配置 Profile`}},help:{type:`switch`,description:{"en-US":`Show help`,"zh-CN":`显示帮助信息`}},version:{type:`switch`,description:{"en-US":`Print version`,"zh-CN":`显示版本信息`}}},Ac={concurrent:{type:`number`,valueHint:`<n>`,description:{"en-US":`Run N parallel requests (default: 1)`,"zh-CN":`并行发送 N 个请求(默认:1)`}}},jc={async:{type:`switch`,description:{"en-US":`Return async task id without waiting`,"zh-CN":`直接返回异步任务 ID,不等待任务完成`}}},Mc={apiKey:{type:`string`,valueHint:`<key>`,description:{"en-US":`API key`,"zh-CN":`API Key`}},baseUrl:{type:`string`,valueHint:`<url>`,description:{"en-US":`API base URL`,"zh-CN":`API Base URL`}}},Nc={consoleRegion:{type:`string`,valueHint:`<region>`,description:{"en-US":`Console gateway region (e.g. cn-beijing, ap-southeast-1)`,"zh-CN":`控制台网关地域(例如 cn-beijing、ap-southeast-1)`}},consoleSite:{type:`string`,valueHint:`<site>`,description:{"en-US":`Console site: domestic, international`,"zh-CN":`控制台站点:domestic、international`}},consoleSwitchAgent:{type:`number`,valueHint:`<uid>`,description:{"en-US":`Switch agent UID for delegated access`,"zh-CN":`切换代理访问的 UID`}},workspaceId:{type:`string`,valueHint:`<id>`,description:{"en-US":`Workspace ID (env: BAILIAN_WORKSPACE_ID)`,"zh-CN":`Workspace ID(环境变量:BAILIAN_WORKSPACE_ID)`}}},Pc={accessKeyId:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key ID (env: ALIBABA_CLOUD_ACCESS_KEY_ID)`,"zh-CN":`阿里云 Access Key ID(环境变量:ALIBABA_CLOUD_ACCESS_KEY_ID)`}},accessKeySecret:{type:`string`,valueHint:`<key>`,description:{"en-US":`Alibaba Cloud Access Key Secret (env: ALIBABA_CLOUD_ACCESS_KEY_SECRET)`,"zh-CN":`阿里云 Access Key Secret(环境变量:ALIBABA_CLOUD_ACCESS_KEY_SECRET)`}},securityToken:{type:`string`,valueHint:`<token>`,description:{"en-US":`Alibaba Cloud STS Security Token (env: ALIBABA_CLOUD_SECURITY_TOKEN)`,"zh-CN":`阿里云 STS Security Token(环境变量:ALIBABA_CLOUD_SECURITY_TOKEN)`}}};function Fc(e){return e.auth===`apiKey`?Mc:e.auth===`console`?Nc:e.auth===`openapi`?Pc:{}}function Ic(e){return e}const Lc=1;function Rc(e,t){return e.normalize(`NFKC`).replace(/[\\/:*?"<>|]/g,`_`).replace(/\s+/g,`_`).replace(/_+/g,`_`).replace(/^_+|_+$/g,``)||t}function zc(e,t){return`${Rc(e||`image`,`image`)}_${Rc((t||``).substring(0,20),`untitled`)}_${Date.now()}`}function Bc(e=f()){let t=process.env.HERMES_HOME?.trim();if(t)return Vc(t);if(process.platform===`win32`){let t=process.env.LOCALAPPDATA?.trim();return t?g(t,`hermes`):g(e,`AppData`,`Local`,`hermes`)}return g(e,`.hermes`)}function Vc(e){return e===`~`?f():e.startsWith(`~/`)||e.startsWith(`~\\`)?g(f(),e.slice(2)):e}const Hc=()=>g(f(),`bailian-output`);function Uc(e,t){let n=t?.flagDir||e.outputDir||Hc(),r=t?.subDir?g(n,t.subDir):n;return i(r)||a(r,{recursive:!0}),r}function Wc(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function Gc(e){return o(e===`-`?0:e,`utf-8`)}async function Kc(e,t){let n=[],r=0;async function i(){for(;r<e.length;){let t=r++;n[t]=await e[t]()}}let a=Array.from({length:Math.min(t,e.length)},()=>i());return await Promise.all(a),n}function qc(e,t=`boolean`){if(typeof e==`boolean`)return e;if(typeof e==`string`){let t=e.trim().toLowerCase();if(t===`true`)return!0;if(t===`false`)return!1}throw new P(`Invalid ${t} value "${String(e)}". Use true or false.`,N.USAGE)}function Jc(e,t=`boolean`){if(e!=null)return qc(e,t)}function Yc(e,t,n=`boolean`){let r=Jc(e,n);return r===void 0?t:r}function Xc(e,t){return Jc(e,`watermark`)??t??!0}const Zc=/^[a-z0-9][a-z0-9.-]{0,63}$/,Qc=/^bailian-[a-z0-9-]{1,64}$/,$c=/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][0-9A-Za-z.-]{1,20})?$/;function el(e,t){let n=e[t];if(typeof n!=`string`)return;let r=n.trim();return r.length>0?r:void 0}function tl(e){if(!e)return`unknown`;let t=e.toLowerCase().replace(/[\s_]+/g,`-`);return Zc.test(t)?t:`unknown`}function nl(e){let t=el(e,`BAILIAN_CALLER_TYPE`)?.toLowerCase();if(t!==`agent`&&t!==`ai_agent`)return{callerType:`unknown`};let n=el(e,`BAILIAN_SKILL_NAME`)?.toLowerCase(),r=n!==void 0&&Qc.test(n)?n:void 0,i=el(e,`BAILIAN_SKILL_VERSION`),a=r!==void 0&&i!==void 0&&$c.test(i)?i:void 0;return{callerType:`agent`,callerName:tl(el(e,`BAILIAN_CALLER_NAME`)),...r===void 0?{}:{skillName:r},...a===void 0?{}:{skillVersion:a}}}function rl(e){let t={command:e.command,timestamp:(/* @__PURE__ */ new Date()).toISOString(),durationMs:e.durationMs,success:e.success,cliVersion:e.cliVersion,nodeVersion:process.version,os:process.platform,callerType:e.caller.callerType};return e.caller.callerType===`agent`&&(t.callerName=e.caller.callerName,e.caller.skillName!==void 0&&(t.skillName=e.caller.skillName),e.caller.skillVersion!==void 0&&(t.skillVersion=e.caller.skillVersion)),e.authMethod&&(t.authMethod=e.authMethod),!e.success&&e.error&&(e.error.message&&(t.errorMessage=e.error.message),e.error.exitCode!==void 0&&(t.exitCode=e.error.exitCode),e.error.httpStatus!==void 0&&(t.httpStatus=e.error.httpStatus),e.error.requestId&&(t.requestId=e.error.requestId)),e.params&&Object.keys(e.params).length>0&&(t.params=e.params),t}function il(e){if(e==null)return;let t=typeof e==`string`?e:JSON.stringify(e);return t.length<=500?t:t.slice(0,500)}function al(e){let{command:t,params:n,...r}=e,i={et:`EXP`,ext:r,c1:n,c2:e.success?`success`:`failure`};return e.httpStatus!==void 0&&(i.c3=String(e.httpStatus)),e.errorMessage&&(i.c4=il(e.errorMessage)),e.requestId&&(i.c5=e.requestId),i}let Y;function ol(){return Y||(process.env.NODE_ENV===`development`?(Y=`dev`,Y):process.env.BAILIAN_COMPILED===`1`?(Y=`prod`,Y):(Y=import.meta.url.includes(`/node_modules/`)?`prod`:`dev`,Y))}var sl=/* @__PURE__ */ je(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=8)})([function(e,t){e.exports=Pe(`os`)},function(e,t){e.exports=globalThis.fetch},function(e,t,n){e.exports=n(6)},function(e,t){e.exports=Pe(`dns`)},function(e,t){e.exports=Pe(`util`)},function(e,t){e.exports=Pe(`crypto`)},function(e,t,n){Object.defineProperty(t,Symbol.toStringTag,{value:`Module`});let r=n(7),i=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},a=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},o=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},s=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},c=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},l=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},u=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},d=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},f=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},p=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},m=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},h=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},g=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},_=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},v=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},y=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},b=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},ee=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},te=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},ne=(e,t)=>{t.appName=`BaiduSpider`,t.appVersion=e.value,t.deviceBrand=`Baidu`,t.deviceType=`bot`,t.platform=`other`},re=(e,t)=>{t.appName=`360 Spider`,t.appVersion=e.value,t.deviceBrand=`360`,t.deviceType=`bot`,t.platform=`other`},ie=(e,t)=>{t.appName=`BingBot`,t.appVersion=e.value,t.deviceBrand=`Microsoft`,t.deviceType=`bot`,t.platform=`other`},x=(e,t)=>{t.appName=`Googlebot`,t.appVersion=e.value,t.deviceBrand=`Google`,t.deviceType=`bot`,t.platform=`other`},ae=(e,t)=>{t.appName=`YandexBot`,t.appVersion=e.value,t.deviceBrand=`Yandex`,t.deviceType=`bot`,t.platform=`other`},oe=(e,t)=>{e.getPreviousNTokens(3)===`Sogou web spider`&&(t.deviceBrand=`Sogou.com`,t.appName=`SogouSpider`),t.appVersion=e.value,t.deviceType=`bot`},se=(e,t)=>{t.appName=`DataproviderBot`,t.appVersion=e.value,t.deviceBrand=`Dataprovider.com`,t.deviceType=`bot`,t.platform=`other`},ce=(e,t)=>{t.appName=`AhrefsBot`,t.appVersion=e.value,t.deviceBrand=`Ahrefs`,t.deviceType=`bot`,t.platform=`other`},le=(e,t)=>{t.appName=`BitSightBot`,t.appVersion=e.value,t.deviceBrand=`Bitsight`,t.deviceType=`bot`,t.platform=`other`},S=(e,t)=>{t.appName=`oBot`,t.appVersion=e.value,t.deviceBrand=`IBM`,t.deviceType=`bot`,t.platform=`other`},C=(e,t)=>{t.appName=`Cincraw`,t.appVersion=e.value,t.deviceBrand=`CINC`,t.deviceType=`bot`,t.platform=`other`},w=(e,t)=>{t.appName=`DingTalkBot`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},T=(e,t)=>{t.appName=`YisouSpider`,t.appVersion=e.value,t.deviceBrand=`Alibaba`,t.deviceType=`bot`,t.platform=`other`},E=(e,t)=>{t.appName=`ByteSpider`,t.appVersion=e.value,t.deviceBrand=`ByteDance`,t.deviceType=`bot`,t.platform=`other`},ue=(e,t)=>{t.appName=`HeadlineCrawler`,t.appVersion=e.value,t.deviceBrand=`Headline.com`,t.deviceType=`bot`,t.platform=`other`},de=(e,t)=>{t.appName=`BitDiscoveryBot`,t.appVersion=e.value,t.deviceBrand=`Tenable`,t.deviceType=`bot`,t.platform=`other`},D=(e,t)=>{e.getPreviousNTokens(4)===`Screaming Frog SEO Spider`&&(t.deviceBrand=`Screaming Frog`,t.appName=`Screaming Frog`),t.appVersion=e.value,t.deviceType=`bot`},O=(e,t)=>{t.appName=`Ai2Bot`,t.appVersion=e.value,t.deviceBrand=`Ai2`,t.deviceType=`bot`,t.platform=`other`},fe=(e,t)=>{t.appName=`DianjingAdSpider`,t.appVersion=e.value,t.deviceBrand=`Dianjing`,t.deviceType=`bot`,t.platform=`other`},k=/* @__PURE__ */ new Map,A=/* @__PURE__ */ new Map;k.set(`Baiduspider-render`,i),k.set(`Baiduspider+`,i),k.set(`Baiduspider-image+`,i),k.set(`360Spider`,a),k.set(`360Spider-Image`,a),k.set(`bingbot`,o),k.set(`Googlebot`,s),k.set(`YandexRenderResourcesBot`,c),k.set(`spider`,l),k.set(`Dataprovider.com`,u),k.set(`AhrefsBot`,d),k.set(`BitSightBot`,f),k.set(`oBot`,p),k.set(`Cincraw`,m),k.set(`DingTalkBot-LinkService`,h),k.set(`YisouSpider`,g),k.set(`Bytespider`,_),k.set(`ev-crawler`,v),k.set(`bitdiscovery`,y),k.set(`Spider`,b),k.set(`Ai2Bot-Dolma`,ee),k.set(`dianjing_ad_spider`,te),A.set(`Baiduspider-render`,ne),A.set(`Baiduspider+`,ne),A.set(`Baiduspider-image+`,ne),A.set(`360Spider`,re),A.set(`360Spider-Image`,re),A.set(`bingbot`,ie),A.set(`Googlebot`,x),A.set(`YandexRenderResourcesBot`,ae),A.set(`spider`,oe),A.set(`Dataprovider.com`,se),A.set(`AhrefsBot`,ce),A.set(`BitSightBot`,le),A.set(`oBot`,S),A.set(`Cincraw`,C),A.set(`DingTalkBot-LinkService`,w),A.set(`YisouSpider`,T),A.set(`Bytespider`,E),A.set(`ev-crawler`,ue),A.set(`bitdiscovery`,de),A.set(`Spider`,D),A.set(`Ai2Bot-Dolma`,O),A.set(`dianjing_ad_spider`,fe);let pe={productHandlerMap:k,commentHandlerMap:A,getSpecialProductHandler:()=>null,getSpecialCommentHandler:()=>null,getDefaultModelHandler:()=>null};t.isBot=function(e){let t=r.createUAInfo();return r.runTask(e,t,pe),t.deviceType===`bot`}},function(e,t){function n(e){let t=[],n={parent:e,tokens:t,get firstToken(){return t.length===0?null:t[0]},getNewToken(r){let i=(function(){let e=[],t=[],n=[],r=null,i=null,a=null,o=!0,s=!0,c=!0,l=null,u={get key(){return o&&=(r=e.join(``),!1),r},get value(){return s&&=(i=t.join(``),!1),i},get originValue(){return c&&=(a=n.join(``),!1),a},previousToken:null,properties:null,appendKey(t){e.push(t),o=!0},appendValue(e){t.push(e===`_`?`.`:e),n.push(e),s=!0,c=!0,l=null},getSplitValue(e){if(l===null){let e=u.value;l=e===``?[]:e.split(`/`)}return e>=0&&e<l.length?l[e]:null},getPreviousNTokens(e){let t=[],n=u;for(let r=0;r<e;r++){if(n==null)return null;t.unshift(n.key),n=n.previousToken}return t.join(` `)}};return u})();return t.push(i),i.previousToken=r===void 0?t.length>1?t[t.length-2]:null:r,e&&(e.properties=n),i},getLastToken:()=>t.length===0?null:t[t.length-1],getFirstToken:()=>t.length===0?null:t[0],isEmpty:()=>t.length===0};return n}function r(){return{appName:null,appVersion:null,browserName:null,browserVersion:null,engineName:null,engineVersion:null,deviceBrand:null,deviceModel:null,deviceType:`mobile`,osName:null,osVersion:null,platform:`web`,tokenGroup:n(null)}}let i=new Set(` ;,"'`.split(``)),a=new Set(`/=:`.split(``)),o=/* @__PURE__ */ new Set([`Mozilla`,`AppleWebKit`,`Safari`,`Opera`,`Dalvik`,`com.ss.android.ugc.aweme`]);function s(e){return e.length===1&&i.has(e)}function c(e){return e.length===1&&a.has(e)}function l(e,t,n,r){if(e==null)return;let i=t.parent,a=e.key,s=null;if(i!=null){let e=i.key;o.has(e)?(s=r.commentHandlerMap.get(a)??null,s??=r.getSpecialCommentHandler(a),s==null&&a.endsWith(` Build`)&&(s=r.getDefaultModelHandler())):s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a)}else s=r.productHandlerMap.get(a)??r.getSpecialProductHandler(a);if(s!=null)try{s(e,n)}catch{}}function u(e,t,r){if(e==null)throw Error(`input can not be null`);return(function e(t,r,i,a,o){let u,d=null,f=null,p=!1,m=t.length,h=r>0?t[r-1]:`\0`;for(u=r;u<m;u++){let g=t[u];if(s(g)){let e=h!==`\0`&&s(h);if(!p&&r>0&&g===` `&&!e){let e=u+1;if(e<m){let n=t[e];/\d/.test(n)||n===`-`?p=!0:f?.appendKey(g)}else f?.appendKey(g)}else f!=null&&(d=f,f=null);h=g}else if(g===`(`){if(h===`(`){h=g;continue}let r=u;u=e(t,u+1,n(i.getLastToken()),a,o),f!=null&&(d=f,f=null),h=t[r]}else{if(g===`)`){if(r===0){h=g;continue}break}f??(l(i.getLastToken(),i,a,o),f=i.getNewToken(d),p=!1),c(g)?(p&&f.appendValue(g),p=!0):p?f.appendValue(g):f.appendKey(g),h=g}}return l(i.getLastToken(),i,a,o),u})(e,0,t.tokenGroup,t,r),t}Object.defineProperty(t,"DEFAULT_MODEL_HANDLER_KEY",{enumerable:!0,get:function(){return`DEFAULT_MODEL_HANDLER`}}),Object.defineProperty(t,"createUAInfo",{enumerable:!0,get:function(){return r}}),Object.defineProperty(t,"runTask",{enumerable:!0,get:function(){return u}})},function(e,t,n){n.r(t);var r=n(0),i=n.n(r),a=n(1),o=n.n(a);n(2);function s(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:20,t=arguments.length>1?arguments[1]:void 0;return t||=``,e?s(--e,`0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz`.charAt(Math.floor(60*Math.random()))+t):t}function c(e,t){for(var n in t)e[n]=t[n];return e}function l(e){return Object.prototype.toString.call(e)===`[object Object]`}function u(e){return typeof Promise<`u`&&e instanceof Promise}var d=Object.freeze({__aesBeforeSkip:1}),f=function(e){var t=Object.prototype.toString.call(e);if(t===`[object String]`&&e||t===`[object Number]`||t===`[object Boolean]`)return e;if(t===`[object Object]`||t===`[object Array]`)try{return JSON.stringify(e)}catch{}},p=function(e){var t={};for(var n in e){var r=e[n];r!==void 0&&(t[n]=f(r))}return t},m=function(e){var t=[];for(var n in e){var r=f(e[n]);r!==void 0&&t.push(`${n}=${encodeURIComponent(r)}`)}return t.join(`&`)};function h(e){return(e.requiredFields||[]).concat([`pid`]).some(function(t){return e[t]===void 0})}function g(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:``,t=arguments.length>1?arguments[1]:void 0;typeof console<`u`&&console.warn(`日志解析报错,埋点将被丢弃 => ${e}`,t)}var _=`AEM_TRACKER_UNIQUE_PVID`,v=typeof globalThis<`u`&&globalThis?globalThis:typeof window<`u`&&window?window:typeof global<`u`&&global?global:typeof self<`u`&&self?self:(console.error(`Unable to locate global object in current environment`),{});function y(e){this._queue=[],this._reqQueue=[],this._plugins={},this._subscribers={onConfigUpdated:[]},this._timeout=0,this._config={sdk_version:`3.3.18`,set pv_id(e){v[_]=e},get pv_id(){return v[_]||(v[_]=s()),v[_]},timezone_offset:(/* @__PURE__ */ new Date()).getTimezoneOffset()},e&&(this._config=c(this._config,e))}y.prototype={constructor:y,_sendAll:function(){if(this._timeout&&=(clearTimeout(this._timeout),0),this._queue.length){var e,t=this._config.maxUrlLength||3e4,n=this._getSendConfig();try{e=this._processData(this._queue,n)}catch{}if(e&&e.length<t)return this._queue=[],void this.send(e);for(var r,i=[];this._queue.length;){i.push(this._queue.shift());try{r=this._processData(i,n)}catch(e){var a=i.pop();g(e.message,a);continue}if(r.length>t){i.length>1&&(this._queue.unshift(i.pop()),r=this._processData(i,n));break}}r&&this.send(r),this._queue.length&&this._sendAll()}},_send:function(e,t){var n=this;if(!1===t){var r;try{r=this._processData([e])}catch(t){g(t.message,e)}r&&this.send(r)}else{this._queue.push(e);var i=this._config.mergeRequestInterval||500;this._timeout||=setTimeout(function(){n._sendAll()},i)}},_getSendConfig:function(){var e={},t=this._config;for(var n in t)n!==`requiredFields`&&n!==`maxUrlLength`&&n!==`queueGlobalName`&&n!==`debug`&&n!==`excludeCrawlers`&&n!==`collectClientHints`&&n.indexOf(`plugin`)!==0&&t[n]!==``&&t[n]!==null&&t[n]!==void 0&&(e[n]=f(t[n]));return e},_processData:function(e,t){t||=this._getSendConfig();var n=m(t);return n+=`&msg=`+encodeURIComponent(e.map(function(e){return m(e)}).join(`|`))},setConfig:function(e,t){var n=this,r={};t===void 0?r=e:r[e]=t;var i=!(function e(t,n){if(t===void 0||n===void 0||!l(t)||!l(n))return!1;for(var r in t)if(l(t[r])){if(!e(t[r],n[r]))return!1}else if(t[r]!==n[r])return!1;return!0})(r,this._config),a=function(){if(i){for(var e in r)l(r[e])?n._config[e]=c(n._config[e]||{},r[e]):n._config[e]=r[e];n._execSubscribe(`onConfigUpdated`,[r,n._config])}};this._reqQueue.length?(a(),h(this._config)||(this._reqQueue.forEach(function(e){n._send.apply(n,e)}),this._reqQueue=[])):(i&&this._sendAll(),a())},getConfig:function(e){return e?this._config[e]:this._config},updatePVID:(function(e,t){if(typeof e!=`function`)throw TypeError(`Expected a function`);t=typeof t==`number`&&t>=0?t:100;var n=null;return function(){if(n===null){var r=this,i=Array.prototype.slice.call(arguments);n=setTimeout(function(){n=null},t),e.apply(r,i)}}})(function(){v[_]=s()},200),log:function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};e&&(t.ts=t.ts||(/* @__PURE__ */ new Date()).getTime(),t.type=e,this._print(`log`,e,t),t=p(t),h(this._config)?this._reqQueue.length<1e3&&this._reqQueue.push([t,n.combo]):this._send(t,n.combo))},before:function(e,t){var n=this;return function(){var r=arguments,i=t.apply(n,r);i!==d&&(u(i)?i.then(function(t){t!==d&&e.apply(n,t||r)}):e.apply(n,i||r))}},after:function(e,t){var n=this;return function(){var r=arguments;e.apply(n,r),t.apply(n,r)}},use:function(e,t){var n=this;return Object.prototype.toString.call(e)===`[object Array]`?e.map(function(e){if(Object.prototype.toString.call(e)===`[object Array]`){var t=e[0],r=e[1];return n._plugins[t]||(n._plugins[t]=new t(n,r))}return n._plugins[e]||(n._plugins[e]=new e(n))}):this._plugins[e]||(this._plugins[e]=new e(this,t))},_print:function(){this._config.debug&&typeof console<`u`&&console.log.apply(console,arguments)},onConfigUpdated:function(e){this._subscribers.onConfigUpdated&&this._subscribers.onConfigUpdated.push(e)},_execSubscribe:function(e,t){this._subscribers[e]&&this._subscribers[e].forEach(function(e){e.apply(this,t)})}};var b=y,ee=n(3),te=n.n(ee),ne=n(4),re=n(5),ie=n.n(re);function x(e){return(x=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e})(e)}function ae(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function oe(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ae(Object(n),!0).forEach(function(t){se(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ae(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function se(e,t,n){return(t=(function(e){var t=(function(e,t){if(x(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(x(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)})(e,`string`);return x(t)==`symbol`?t:t+``})(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ce(e,t){var n=typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(!n){if(Array.isArray(e)||(n=S(e))||t&&e&&typeof e.length==`number`){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw TypeError(`Invalid attempt to iterate non-iterable instance.
|
|
27
27
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a,o=!0,s=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){s=!0,a=e},f:function(){try{o||n.return==null||n.return()}finally{if(s)throw a}}}}function le(e,t){return(function(e){if(Array.isArray(e))return e})(e)||(function(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}})(e,t)||S(e,t)||(function(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
28
28
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function S(e,t){if(e){if(typeof e==`string`)return C(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?C(e,t):void 0}}function C(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function w(){for(var e=/(?:[0]{1,2}[:-]){5}[0]{1,2}/,t=i.a.networkInterfaces(),n=0,r=Object.entries(t);n<r.length;n++){var a=le(r[n],2),o=(a[0],a[1]);if(o){var s,c=ce(o);try{for(c.s();!(s=c.n()).done;){var l=s.value;if(!1===e.test(l.mac))return l.mac}}catch(e){c.e(e)}finally{c.f()}}}return`00:00:00:00:00:00`}var T,E,ue=(T=process.version,{os:i.a.type(),os_version:i.a.release(),app_name:`node`,app_version:T,device_id:ie.a.createHash(`md5`).update(w()).digest(`hex`),platform:`node`}),de=(0,ne.promisify)(te.a.resolve);function D(e){this._offlineQueue=[],e.endpoint=e.endpoint||`gm.mmstat.com`,b.call(this,oe(oe({},ue),e)),this._config.endpoint_url=`https://${this._config.endpoint}/aes.1.1`}D.prototype=((E=function(){}).prototype=b.prototype,new E),D.prototype.constructor=D,D.prototype.send=function(e){var t,n=this;return(t=this._config.endpoint,de(t)).then(function(t){return n._offlineQueue.forEach(function(e){n.send(e)}),n._offlineQueue=[],n._print(`send`,e),o()(n._config.endpoint_url,{method:`POST`,keepalive:!0,body:JSON.stringify({gokey:encodeURIComponent(e),gmkey:`EXP`})}).catch(function(){})}).catch(function(t){n._offlineQueue.length>500&&n._offlineQueue.shift(),n._offlineQueue.push(e)})},t.default=D}]).default})),cl=/* @__PURE__ */ je(((e,t)=>{t.exports=(function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){typeof Symbol<`u`&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:`Module`}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t||4&t&&typeof e==`object`&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&typeof e!=`string`)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,`a`,t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p=``,n(n.s=0)})([function(e,t,n){n.r(t);var r=[`ec`,`ea`,`el`,`et`],i=function(e,t){var n=function(e){var n=e.ec,r=e.ea,i=e.el,a=e.et,o=a===void 0?`CLK`:a,s=e.xpath;delete e.ec,delete e.ea,delete e.el,delete e.et,delete e.xpath,e.p1=n,e.p2=r,e.p3=i,e.p4=o,e.p5=s;try{t.log(`event`,e)}catch{}};return function(){var t=arguments,i={};if(t.length!==0){for(var a=0;a<t.length;a++){var o,s,c=t[a];if(a!==0&&typeof c==`object`&&a!==t.length-1)return void(e==null||(o=e.console)==null||(s=o.warn)==null||s.call(o,`Only the last argument can be object type`));if(typeof c==`string`||typeof c==`number`)i[r[a]]=c;else if(typeof c==`object`&&a===t.length-1)for(var l in c)c.hasOwnProperty(l)&&(i[l]=c[l])}n(i)}else{var u,d;(u=e.console)==null||(d=u.warn)==null||d.call(u,`At lease one augument`)}}};t.default=function(e,t){return i(global,e)}}]).default})),ll=/* @__PURE__ */ Ne(sl(),1),ul=/* @__PURE__ */ Ne(cl(),1);const dl=()=>g(I(),`telemetry.jsonl`);let fl;const pl=/* @__PURE__ */ new Set;let ml;try{let e=new ll.default({pid:`bailian-cli-node`,env:ol()}),t=e.send.bind(e);e.send=function(e){let n=t(e);if(n&&typeof n.then==`function`){let e=n;pl.add(e),e.finally(()=>pl.delete(e))}return n},ml=e,fl=e.use(ul.default)}catch{}async function hl(e=1e3){try{if(ml)try{typeof ml._sendAll==`function`&&ml._sendAll()}catch{}if(pl.size===0)return;let t=[...pl].map(e=>e.catch(()=>void 0));await Promise.race([Promise.allSettled(t),new Promise(t=>setTimeout(t,e).unref?.())])}catch{}}async function gl(e){try{await lt();let n=dl();try{l(n).size>5242880&&u(n)}catch{}t(n,JSON.stringify(e)+`
|
|
29
29
|
`,{mode:384})}catch{}}async function _l(e){try{if(!fl)return;fl(e.command,al(e))}catch{}}const vl=/* @__PURE__ */ new Set([`apiKey`,`baseUrl`,`output`,`quiet`,`verbose`,`timeout`,`dryRun`,`help`,`console`]),yl=/* @__PURE__ */ new Set(/* @__PURE__ */ `page.pageSize.n.count.model.voice.language.provider.capability.temperature.topP.topK.maxTokens.seed.stream.size.resolution.ratio.duration.format.audioFormat.sampleRate.pitch.rate.volume.api.mode.download.textOnly.promptExtend.enableSsml.watermark.hasThoughts.listTools.rerank.rerankTopN.diarization`.split(`.`));function bl(e){let t={};for(let[n,r]of Object.entries(e))n.startsWith(`_`)||vl.has(n)||yl.has(n)&&r!==void 0&&r!==!1&&(n!==`page`||typeof r==`number`&&Number.isFinite(r))&&(t[n]=r);return t}async function xl(e,t,n,r){if(!e.settings.telemetry){await r();return}let i=performance.now(),a=!0,o,s,c,l;try{await r()}catch(e){throw a=!1,e instanceof P?(o=e.message,s=e.exitCode,c=e.api?.httpStatus,l=e.api?.requestId):e instanceof Error&&(o=e.message),e}finally{let r=Math.round(performance.now()-i),u=rl({command:t.join(` `),durationMs:r,success:a,error:a?void 0:{message:o,exitCode:s,httpStatus:c,requestId:l},cliVersion:e.identity.version,authMethod:e.authMethod,params:bl(n),caller:e.caller});gl(u).catch(()=>{}),_l(u).catch(()=>{})}}function Sl(e){if(!e.model)return null;let t=e.inferenceMetadata;return{model:e.model,name:e.name??e.model,description:e.description??e.shortDescription??``,shortDescription:e.shortDescription,provider:e.provider??``,capabilities:e.capabilities??[],features:e.features??[],category:e.category,contextWindow:e.contextWindow??void 0,maxOutputTokens:e.maxOutputTokens??void 0,maxInputTokens:e.maxInputTokens??void 0,docUrl:e.docUrl,collectionTag:e.collectionTag,inferenceMetadata:t,prices:e.prices,qpmInfo:e.qpmInfo,versionTag:e.versionTag,openSource:e.openSource}}var Cl=class{settings;name=`api`;constructor(e){this.settings=e}available(){return!0}async load(){return(await Xi(Ht(this.settings))).map(Sl).filter(e=>e!==null)}};function wl(){return M(I(),`skills/bailian-docs-llm-wiki`)}function Tl(){return M(wl(),`models`,`models.jsonl`)}function El(e){return!e.model||typeof e.model!=`string`?null:{model:e.model,name:e.name??e.model,description:e.description??``,provider:e.provider??``,capabilities:e.capabilities??[],features:e.features??[],contextWindow:e.contextWindow,maxOutputTokens:e.maxOutputTokens,docUrl:e.docUrl,inferenceMetadata:e.inferenceMetadata,shortDescription:e.shortDescription,category:e.category,collectionTag:e.collectionTag,maxInputTokens:e.maxInputTokens,prices:e.prices,qpmInfo:e.qpmInfo,versionTag:e.versionTag,openSource:e.openSource,family:e.family,familyName:e.familyName}}function Dl(e){let t=T(e,`utf-8`).split(`
|
package/package.json
CHANGED