@lingjingai/lj-awb-cli 0.3.15 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +46 -27
  2. package/build/_shared.mjs +130 -0
  3. package/build/build.mjs +3 -0
  4. package/build/pre-publish.mjs +57 -0
  5. package/build/pre.mjs +8 -107
  6. package/build/prod.mjs +9 -78
  7. package/install.mjs +1 -0
  8. package/package.json +8 -3
  9. package/packages/awb-cli/README.md +0 -3
  10. package/packages/awb-cli/package.json +2 -2
  11. package/packages/awb-core/package.json +6 -2
  12. package/packages/awb-core/src/api.js +33 -64
  13. package/packages/awb-core/src/artifact.js +75 -6
  14. package/packages/awb-core/src/auth.js +1 -1
  15. package/packages/awb-core/src/commands.js +316 -120
  16. package/packages/awb-core/src/common.js +3 -2
  17. package/packages/awb-core/src/output.js +2353 -105
  18. package/packages/awb-core/src/services.js +1311 -135
  19. package/packages/awb-core/src/standalone.js +908 -247
  20. package/packages/awb-core/src/update.js +327 -0
  21. package/skills/lj-awb/SKILL.md +105 -76
  22. package/skills/lj-awb/VERSION +1 -1
  23. package/skills/lj-awb/compat.json +3 -3
  24. package/skills/lj-awb/modules/account.md +20 -7
  25. package/skills/lj-awb/modules/artifact/asset.md +64 -0
  26. package/skills/lj-awb/modules/artifact/clip.md +65 -0
  27. package/skills/lj-awb/modules/artifact/script.md +37 -0
  28. package/skills/lj-awb/modules/artifact/video.md +65 -0
  29. package/skills/lj-awb/modules/artifact.md +31 -52
  30. package/skills/lj-awb/modules/asset.md +50 -11
  31. package/skills/lj-awb/modules/auth.md +10 -4
  32. package/skills/lj-awb/modules/create-contract.md +25 -13
  33. package/skills/lj-awb/modules/create.md +37 -0
  34. package/skills/lj-awb/modules/credits.md +6 -0
  35. package/skills/lj-awb/modules/driver.md +126 -0
  36. package/skills/lj-awb/modules/evals.md +84 -36
  37. package/skills/lj-awb/modules/image.md +22 -13
  38. package/skills/lj-awb/modules/model.md +34 -33
  39. package/skills/lj-awb/modules/project.md +7 -0
  40. package/skills/lj-awb/modules/subject.md +28 -7
  41. package/skills/lj-awb/modules/task-manual.md +32 -28
  42. package/skills/lj-awb/modules/task.md +70 -8
  43. package/skills/lj-awb/modules/upload.md +16 -2
  44. package/skills/lj-awb/modules/video.md +33 -29
  45. package/skills/lj-awb/modules/workflows.md +232 -169
  46. package/skills/lj-awb/references/error-codes.md +109 -0
  47. package/skills/lj-awb/references/model-options-read.md +25 -17
  48. package/skills/lj-awb/references/output-fields.md +119 -0
  49. package/skills/lj-awb/scripts/resolve-lj-awb-cmd.sh +106 -4
@@ -46,6 +46,62 @@ const REQUEST_SOURCE_CLI = 'LINGJING_AWB_CLI';
46
46
  const DEFAULT_TASK_RECORD_FILE_ENV = process.env.LINGJING_AWB_TASK_RECORD_FILE || process.env.AWB_TASK_RECORD_FILE;
47
47
  const execFileAsync = promisify(execFile);
48
48
  const COMMON_IMAGE_FORMATS = new Set(['jpg', 'jpeg', 'jfif', 'png', 'webp']);
49
+ const REMOTE_IMAGE_DOWNLOAD_TIMEOUT_MS = 30_000;
50
+ const REMOTE_IMAGE_DOWNLOAD_MAX_BYTES = 100 * 1024 * 1024;
51
+ const REMOTE_IMAGE_MIME_TYPES = new Set([
52
+ 'image/bmp',
53
+ 'image/gif',
54
+ 'image/jpeg',
55
+ 'image/jpg',
56
+ 'image/png',
57
+ 'image/webp',
58
+ ]);
59
+ const REMOTE_IMAGE_EXTENSIONS = new Set(['.bmp', '.gif', '.jfif', '.jpg', '.jpeg', '.png', '.webp']);
60
+ const REMOTE_VOICE_DOWNLOAD_TIMEOUT_MS = 30_000;
61
+ const REMOTE_VOICE_DOWNLOAD_MAX_BYTES = 100 * 1024 * 1024;
62
+ const REMOTE_VOICE_MIME_TYPES = new Set([
63
+ 'audio/mpeg',
64
+ 'audio/wav',
65
+ 'audio/x-wav',
66
+ 'audio/mp4',
67
+ 'audio/aac',
68
+ 'audio/ogg',
69
+ 'video/mp4',
70
+ ]);
71
+ const REMOTE_VOICE_EXTENSIONS = new Set(['.mp3', '.wav', '.m4a', '.aac', '.ogg', '.mp4']);
72
+ const ASSET_PLATFORM_CODES = ['JIMENG', 'BYTEPLUS'];
73
+ const ASSET_PLATFORM_CODE_SET = new Set(ASSET_PLATFORM_CODES);
74
+ const ASSET_PLATFORM_HINT = ASSET_PLATFORM_CODES.join('|');
75
+ const CREATE_STANDARD_KWARG_KEYS = new Set([
76
+ 'modelGroupCode',
77
+ 'projectGroupNo',
78
+ 'customBizId',
79
+ 'prompt',
80
+ 'ratio',
81
+ 'quality',
82
+ 'generateNum',
83
+ 'generate_num',
84
+ 'duration',
85
+ 'needAudio',
86
+ 'need_audio',
87
+ 'resource',
88
+ 'resources',
89
+ 'resourcesJson',
90
+ 'resources_json',
91
+ 'modelParam',
92
+ 'model_param',
93
+ 'modelParams',
94
+ 'model_params',
95
+ 'modelParamsJson',
96
+ 'model_params_json',
97
+ 'taskRecordFile',
98
+ 'waitSeconds',
99
+ 'pollIntervalMs',
100
+ 'inputFile',
101
+ 'concurrency',
102
+ 'dryRun',
103
+ 'yes',
104
+ ]);
49
105
 
50
106
  export function normalizeUserInfo(payload) {
51
107
  const data = payload && typeof payload === 'object' ? payload : {};
@@ -371,7 +427,6 @@ export async function doctor(kwargs = {}) {
371
427
  },
372
428
  origins: {
373
429
  apiOrigin: API_ORIGIN,
374
- assetEditOrigin: awbApi.ASSET_EDIT_ORIGIN,
375
430
  },
376
431
  auth: summarizeAuth(auth, authContext.accessKeyInfo),
377
432
  paths: {
@@ -666,6 +721,31 @@ function modelListMetadata(kind, paramKeys = [], rulesByKey = new Map()) {
666
721
  };
667
722
  }
668
723
 
724
+ function normalizeRateValue(value) {
725
+ if (value === undefined || value === null || value === '') return null;
726
+ const text = String(value).trim();
727
+ const isPercent = text.endsWith('%');
728
+ const parsed = Number(isPercent ? text.slice(0, -1) : text);
729
+ if (!Number.isFinite(parsed)) return null;
730
+ const rate = isPercent || parsed > 1 ? parsed / 100 : parsed;
731
+ if (rate < 0 || rate > 1) return null;
732
+ return rate;
733
+ }
734
+
735
+ function modelSuccessRate(item = {}) {
736
+ const ext = item?.modelExtInfo || {};
737
+ return normalizeRateValue(
738
+ item?.successRate
739
+ ?? item?.success_rate
740
+ ?? item?.successRatio
741
+ ?? item?.success_ratio
742
+ ?? ext?.successRate
743
+ ?? ext?.success_rate
744
+ ?? ext?.successRatio
745
+ ?? ext?.success_ratio,
746
+ );
747
+ }
748
+
669
749
  function normalizeModelRows(payload, kind, options = {}) {
670
750
  const includeRaw = Boolean(options.includeRaw);
671
751
  const includeInternal = Boolean(options.includeInternal);
@@ -683,10 +763,12 @@ function normalizeModelRows(payload, kind, options = {}) {
683
763
  const row = compactRecord({
684
764
  modelGroupCode,
685
765
  displayName: item?.modelName ?? item?.name ?? item?.label ?? null,
766
+ modelDesc: item?.modelDesc ?? null,
686
767
  provider: item?.provider ?? item?.vendor ?? item?.supplier ?? item?.componyName ?? null,
687
768
  enabled: item?.enabled ?? item?.available ?? item?.status ?? null,
688
769
  modelStatus: item?.modelStatus ?? null,
689
770
  taskQueueNum: item?.taskQueueNum ?? null,
771
+ successRate: modelSuccessRate(item),
690
772
  feeCalcType: item?.feeCalcType ?? item?.feeType ?? null,
691
773
  inputModes: metadata.inputModes,
692
774
  params: metadata.controls,
@@ -720,6 +802,44 @@ export async function listModels(kind, kwargs = {}) {
720
802
  return { usage, models };
721
803
  }
722
804
 
805
+ function requireAssetPlatform(value, options = {}) {
806
+ const flag = options.flag || '--platform';
807
+ const platform = trimToNull(value);
808
+ if (!platform) {
809
+ throw argumentError(`缺少参数:${flag}`, `素材加白平台必须显式传入 ${ASSET_PLATFORM_HINT},不要依赖默认平台。`);
810
+ }
811
+ if (!ASSET_PLATFORM_CODE_SET.has(platform)) {
812
+ throw argumentError(`不支持的平台:${platform}`, `只接受 ${ASSET_PLATFORM_HINT};请使用 model asset-review-models 查看模型支持的平台。`);
813
+ }
814
+ return platform;
815
+ }
816
+
817
+ function optionalAssetPlatform(value) {
818
+ if (value == null || value === '') return null;
819
+ return requireAssetPlatform(value);
820
+ }
821
+
822
+ function normalizeAssetReviewModelRecord(item = {}) {
823
+ return compactRecord({
824
+ modelGroupCode: item?.modelGroupCode ?? item?.groupCode ?? null,
825
+ platform: item?.platform ?? null,
826
+ });
827
+ }
828
+
829
+ export async function assetReviewModels(kwargs = {}) {
830
+ const modelGroupCode = trimToNull(kwargs.modelGroupCode);
831
+ const platform = optionalAssetPlatform(kwargs.platform);
832
+ const payload = await awbApi.fetchAssetReviewModels();
833
+ const models = normalizeRows(payload)
834
+ .map((item) => normalizeAssetReviewModelRecord(item))
835
+ .filter((item) => !modelGroupCode || item.modelGroupCode === modelGroupCode)
836
+ .filter((item) => !platform || item.platform === platform);
837
+ return {
838
+ models,
839
+ ...(toBool(kwargs.includeRaw) ? { raw: payload } : {}),
840
+ };
841
+ }
842
+
723
843
  async function findModelGroup(modelGroupCode, options = {}) {
724
844
  const includeRaw = Boolean(options.includeRaw);
725
845
  const [imageResult, videoResult] = await Promise.allSettled([
@@ -864,6 +984,68 @@ function normalizeModelConstraints(constraintSchema = [], taskKind = 'image') {
864
984
  }).filter((constraint) => constraint.target || constraint.targetConfigCode);
865
985
  }
866
986
 
987
+ function resourceConstraintTarget(mediaType, usage = 'reference') {
988
+ const media = String(mediaType || '').toLowerCase();
989
+ const normalizedUsage = String(usage || 'reference');
990
+ return media ? `resource.${media}.${normalizedUsage}` : '';
991
+ }
992
+
993
+ function countRangeValue(minCount, maxCount) {
994
+ if (minCount != null && maxCount != null && minCount === maxCount) return String(minCount);
995
+ if (minCount != null && maxCount != null) return `${minCount}..${maxCount}`;
996
+ if (minCount != null) return `>=${minCount}`;
997
+ if (maxCount != null) return `<=${maxCount}`;
998
+ return undefined;
999
+ }
1000
+
1001
+ function normalizeLimitProfileCondition(condition = {}) {
1002
+ const mediaType = String(condition?.mediaType || '').toUpperCase();
1003
+ const usage = condition?.usage || 'reference';
1004
+ const minCount = ruleNumber(condition?.minCount);
1005
+ const maxCount = ruleNumber(condition?.maxCount);
1006
+ const target = resourceConstraintTarget(mediaType, usage);
1007
+ return compactRecord({
1008
+ key: target ? `${target}.count` : undefined,
1009
+ mediaType,
1010
+ usage,
1011
+ minCount,
1012
+ maxCount,
1013
+ value: countRangeValue(minCount, maxCount),
1014
+ meaning: 'count',
1015
+ });
1016
+ }
1017
+
1018
+ function normalizeResourceLimitProfileConstraints(options = []) {
1019
+ const constraints = [];
1020
+ for (const option of Array.isArray(options) ? options : []) {
1021
+ const profiles = Array.isArray(option?.rules?.limitProfiles) ? option.rules.limitProfiles : [];
1022
+ for (const [profileIndex, profile] of profiles.entries()) {
1023
+ const condition = normalizeLimitProfileCondition(profile?.condition);
1024
+ const overrides = Array.isArray(profile?.overrides) ? profile.overrides : [];
1025
+ for (const [overrideIndex, override] of overrides.entries()) {
1026
+ const mediaType = String(override?.mediaType || '').toUpperCase();
1027
+ if (!mediaType) continue;
1028
+ const usage = override?.usage || condition.usage || 'reference';
1029
+ const limits = compactRecord({
1030
+ usage,
1031
+ ...normalizeMediaRule({ ...override, mediaType }),
1032
+ });
1033
+ constraints.push(compactRecord({
1034
+ id: `${option.paramKey || 'resource'}.limitProfiles[${profileIndex}].overrides[${overrideIndex}]`,
1035
+ name: '素材联动限制',
1036
+ target: resourceConstraintTarget(mediaType, usage),
1037
+ targetConfigCode: option.paramKey,
1038
+ effect: 'resource_limit_overrides',
1039
+ priority: option.rank,
1040
+ conditions: condition.key ? [condition] : [],
1041
+ limits,
1042
+ }));
1043
+ }
1044
+ }
1045
+ }
1046
+ return constraints;
1047
+ }
1048
+
867
1049
  function resourceUsageList(usage) {
868
1050
  return (Array.isArray(usage) ? usage : [usage])
869
1051
  .map((item) => trimToNull(item))
@@ -898,14 +1080,16 @@ function resourceSourceKindForValidation(detail = {}) {
898
1080
  }
899
1081
 
900
1082
  function sourceAllowedByRule(rule = {}, sourceKind) {
901
- const sources = Array.isArray(rule.sources) ? rule.sources : [];
902
- if (!sources.length) return true;
903
- return sources.includes(sourceKind);
1083
+ const shapes = Array.isArray(rule.valueShapes) ? rule.valueShapes : [];
1084
+ if (!shapes.length) return true;
1085
+ return shapes.includes(sourceKind);
904
1086
  }
905
1087
 
906
1088
  function resourceFormatForValidation(detail = {}) {
907
1089
  if (detail.localFile?.format) return String(detail.localFile.format).toLowerCase();
908
1090
  const value = detail.resource?.source?.value;
1091
+ const transformedFormat = imageTransformFormat(value);
1092
+ if (transformedFormat) return transformedFormat;
909
1093
  const pathname = (() => {
910
1094
  try {
911
1095
  return new URL(String(value)).pathname;
@@ -917,6 +1101,34 @@ function resourceFormatForValidation(detail = {}) {
917
1101
  return ext || null;
918
1102
  }
919
1103
 
1104
+ function imageTransformFormat(value) {
1105
+ const text = String(value || '');
1106
+ if (!text.includes('?') && !text.includes('%2F') && !text.includes('/format/')) return null;
1107
+ const queryText = (() => {
1108
+ try {
1109
+ const url = new URL(text);
1110
+ return url.search || text;
1111
+ } catch {
1112
+ const queryIndex = text.indexOf('?');
1113
+ return queryIndex >= 0 ? text.slice(queryIndex) : text;
1114
+ }
1115
+ })();
1116
+ let decoded = queryText;
1117
+ try {
1118
+ decoded = decodeURIComponent(queryText);
1119
+ } catch {}
1120
+ for (const pattern of [
1121
+ /image(?:mogr2|view2)[^&#?]*?\/format\/([A-Za-z0-9]+)/i,
1122
+ /x-oss-process=image[^&#?]*?format,([A-Za-z0-9]+)/i,
1123
+ /(?:^|[?&#])format=([A-Za-z0-9]+)/i,
1124
+ ]) {
1125
+ const match = decoded.match(pattern);
1126
+ const format = normalizeFileFormat(match?.[1]);
1127
+ if (format) return format;
1128
+ }
1129
+ return null;
1130
+ }
1131
+
920
1132
  function normalizeFileFormat(value) {
921
1133
  const format = trimToNull(value)?.toLowerCase();
922
1134
  if (!format) return null;
@@ -981,6 +1193,15 @@ function isConvertibleLocalImage(detail = {}) {
981
1193
  return Boolean(detail.localFile?.exists && String(detail.localFile?.mimeType || '').startsWith('image/'));
982
1194
  }
983
1195
 
1196
+ function isDownloadableImageSource(detail = {}) {
1197
+ const sourceKind = resourceSourceKindForValidation(detail);
1198
+ return detail.resource?.source?.kind === 'url' && ['http_url', 'backendPath'].includes(sourceKind);
1199
+ }
1200
+
1201
+ function isConvertibleImageResource(detail = {}) {
1202
+ return isConvertibleLocalImage(detail) || isDownloadableImageSource(detail);
1203
+ }
1204
+
984
1205
  function resourceFormatConversion(rule = {}, detail = {}) {
985
1206
  if (!isImageRule(rule)) return null;
986
1207
  const format = normalizeFileFormat(resourceFormatForValidation(detail));
@@ -992,7 +1213,7 @@ function resourceFormatConversion(rule = {}, detail = {}) {
992
1213
  fromFormat: format,
993
1214
  toFormat: policy.autoConvertTo,
994
1215
  reason: 'image_webp_not_supported',
995
- possible: isConvertibleLocalImage(detail),
1216
+ possible: isConvertibleImageResource(detail),
996
1217
  };
997
1218
  }
998
1219
  if (policy.kind === 'normal_plus_webp') return null;
@@ -1001,7 +1222,7 @@ function resourceFormatConversion(rule = {}, detail = {}) {
1001
1222
  fromFormat: format,
1002
1223
  toFormat: policy.autoConvertTo,
1003
1224
  reason: 'image_strict_format_mismatch',
1004
- possible: isConvertibleLocalImage(detail),
1225
+ possible: isConvertibleImageResource(detail),
1005
1226
  allowed: policy.allowed,
1006
1227
  };
1007
1228
  }
@@ -1033,7 +1254,7 @@ function assertResourceShapeAgainstModel(resourceDetails = [], resourceRules = [
1033
1254
  if (!sourceAllowedByRule(rule, sourceKind)) {
1034
1255
  throw argumentError(
1035
1256
  `模型不支持 ${resourceText(resource)} 的来源:${sourceKind}`,
1036
- `该资源允许来源:${(rule.sources || []).join(', ') || '未限制'}。`,
1257
+ `该资源允许的 value 形状:${(rule.valueShapes || []).join(', ') || '未限制'}。`,
1037
1258
  );
1038
1259
  }
1039
1260
  const format = resourceFormatForValidation(detail);
@@ -1041,7 +1262,7 @@ function assertResourceShapeAgainstModel(resourceDetails = [], resourceRules = [
1041
1262
  if (conversion && !conversion.possible) {
1042
1263
  throw argumentError(
1043
1264
  `素材格式需要转换但无法自动处理:${resourceText(resource)}`,
1044
- `当前格式 ${conversion.fromFormat},目标格式 ${conversion.toFormat};请使用本地文件,或先转换后再传远程 URL / asset。`,
1265
+ `当前格式 ${conversion.fromFormat},目标格式 ${conversion.toFormat};请使用本地文件、http(s) URL 或 material backendPath,asset 资源需先转换后再传。`,
1045
1266
  );
1046
1267
  }
1047
1268
  if (!conversion && !fileTypeAllowedByRule(rule, format)) {
@@ -1108,6 +1329,58 @@ function assertResourceCountsAgainstModel(resourceDetails = [], resourceRules =
1108
1329
  }
1109
1330
  }
1110
1331
 
1332
+ function resourceCountForCondition(resourceDetails = [], condition = {}) {
1333
+ return resourceDetails.filter((detail) => {
1334
+ const resource = detail.resource || {};
1335
+ if (condition.mediaType && resourceMediaType(resource) !== String(condition.mediaType).toUpperCase()) return false;
1336
+ if (condition.usage && resource.usage !== condition.usage) return false;
1337
+ return true;
1338
+ }).length;
1339
+ }
1340
+
1341
+ function resourceLimitConditionMatches(resourceDetails = [], condition = {}) {
1342
+ if (condition.meaning !== 'count') return false;
1343
+ const count = resourceCountForCondition(resourceDetails, condition);
1344
+ if (condition.minCount != null && count < condition.minCount) return false;
1345
+ if (condition.maxCount != null && count > condition.maxCount) return false;
1346
+ return true;
1347
+ }
1348
+
1349
+ function validationResourceLimitOverrides(limits = {}) {
1350
+ const validatesResourceDuration = resourceUsageList(limits.usage).includes('keyframe');
1351
+ return compactRecord({
1352
+ mediaType: limits.mediaType,
1353
+ usage: limits.usage,
1354
+ fileTypes: limits.fileTypes,
1355
+ minFiles: limits.minFiles,
1356
+ maxFiles: limits.maxFiles,
1357
+ maxSizeKB: limits.maxSizeKB,
1358
+ minItems: limits.minItems,
1359
+ maxItems: limits.maxItems,
1360
+ supportLastFrameOnly: limits.supportLastFrameOnly,
1361
+ minDurationMs: validatesResourceDuration ? limits.minDurationMs : undefined,
1362
+ maxDurationMs: validatesResourceDuration ? limits.maxDurationMs : undefined,
1363
+ maxPromptLength: validatesResourceDuration ? limits.maxPromptLength : undefined,
1364
+ });
1365
+ }
1366
+
1367
+ function applyResourceLimitProfileConstraints(resourceRules = [], constraints = [], resourceDetails = []) {
1368
+ const effective = resourceRules.map((rule) => ({ ...rule }));
1369
+ const profiles = constraints.filter((constraint) => constraint.effect === 'resource_limit_overrides' && constraint.limits);
1370
+ for (const profile of profiles) {
1371
+ const conditions = Array.isArray(profile.conditions) ? profile.conditions : [];
1372
+ if (conditions.length && !conditions.every((condition) => resourceLimitConditionMatches(resourceDetails, condition))) continue;
1373
+ const validationLimits = validationResourceLimitOverrides(profile.limits);
1374
+ if (!Object.keys(validationLimits).some((key) => !['mediaType', 'usage'].includes(key))) continue;
1375
+ const index = effective.findIndex((rule) => (
1376
+ String(rule.mediaType || '').toUpperCase() === String(validationLimits.mediaType || '').toUpperCase()
1377
+ && resourceUsageList(rule.usage).includes(validationLimits.usage || 'reference')
1378
+ ));
1379
+ if (index >= 0) effective[index] = compactRecord({ ...effective[index], ...validationLimits });
1380
+ }
1381
+ return effective;
1382
+ }
1383
+
1111
1384
  function promptParamValue(promptParams = {}, key) {
1112
1385
  if (key === 'duration') return promptParams.duration;
1113
1386
  if (key === 'generateNum') return promptParams.generate_num;
@@ -1116,12 +1389,16 @@ function promptParamValue(promptParams = {}, key) {
1116
1389
  }
1117
1390
 
1118
1391
  function providedPromptParamKeys(promptParams = {}) {
1119
- const keys = [];
1392
+ const keys = new Set();
1120
1393
  for (const key of ['prompt', 'ratio', 'quality', 'duration', 'generateNum', 'needAudio']) {
1121
1394
  const value = promptParamValue(promptParams, key);
1122
- if (value !== undefined && value !== null && value !== '') keys.push(key);
1395
+ if (value !== undefined && value !== null && value !== '') keys.add(key);
1123
1396
  }
1124
- return keys;
1397
+ for (const [key, value] of Object.entries(promptParams || {})) {
1398
+ if (key === 'resources' || key === 'generate_num' || key === 'need_audio') continue;
1399
+ if (value !== undefined && value !== null && value !== '') keys.add(key);
1400
+ }
1401
+ return [...keys];
1125
1402
  }
1126
1403
 
1127
1404
  function inferGeneratedMode(resources = []) {
@@ -1186,9 +1463,10 @@ async function validateCreateRequestAgainstModel(kind, modelGroupCode, promptPar
1186
1463
  }
1187
1464
  const params = modelOptionParams(context.options, context.taskKind);
1188
1465
  const resources = modelOptionsResources(context.inputModes);
1466
+ const effectiveResources = applyResourceLimitProfileConstraints(resources, context.constraints, resourceDetails);
1189
1467
  assertParamsAgainstModel(promptParams, params, context.constraints);
1190
- assertResourceShapeAgainstModel(resourceDetails, resources);
1191
- assertResourceCountsAgainstModel(resourceDetails, resources);
1468
+ assertResourceShapeAgainstModel(resourceDetails, effectiveResources);
1469
+ assertResourceCountsAgainstModel(resourceDetails, effectiveResources);
1192
1470
  if (kind === 'video') {
1193
1471
  const supportedIntents = createSpecSupportedIntents(context.inputModes, context.taskKind);
1194
1472
  const inputRequirement = createSpecInputRequirement(context.taskKind, context.inputModes, supportedIntents);
@@ -1221,12 +1499,16 @@ async function loadModelOptionContext(modelGroupCode, options = {}) {
1221
1499
  const constraintSchema = options.includeConstraintSchema
1222
1500
  ? await fetchModelConstraintSchema(rawModel, modelGroupCode)
1223
1501
  : [];
1502
+ const constraints = [
1503
+ ...normalizeModelConstraints(constraintSchema, taskKind),
1504
+ ...normalizeResourceLimitProfileConstraints(mergedOptions),
1505
+ ];
1224
1506
  return {
1225
1507
  rawModel,
1226
1508
  model: modelSummaryFromRaw(rawModel, modelGroupCode, taskKind),
1227
1509
  options: mergedOptions,
1228
1510
  constraintSchema,
1229
- constraints: normalizeModelConstraints(constraintSchema, taskKind),
1511
+ constraints,
1230
1512
  optionKeys,
1231
1513
  rulesByKey,
1232
1514
  taskKind,
@@ -1314,7 +1596,7 @@ function mergeResourceLimits(base = {}, overrides = {}) {
1314
1596
  function mergeModelParamRules(options = [], rawModel = null) {
1315
1597
  const rawParams = Array.isArray(rawModel?.modelParams) ? rawModel.modelParams : [];
1316
1598
  const rawByKey = new Map(rawParams.map((item) => [item?.paramKey, item]).filter(([key]) => key));
1317
- return options.map((option) => {
1599
+ const merged = options.map((option) => {
1318
1600
  const raw = rawByKey.get(option.paramKey);
1319
1601
  return {
1320
1602
  ...option,
@@ -1322,6 +1604,52 @@ function mergeModelParamRules(options = [], rawModel = null) {
1322
1604
  rules: option.rules ?? raw?.rules ?? null,
1323
1605
  };
1324
1606
  });
1607
+ const mergedKeys = new Set(merged.map((item) => item.paramKey).filter(Boolean));
1608
+ for (const raw of rawParams) {
1609
+ if (!raw?.paramKey || mergedKeys.has(raw.paramKey)) continue;
1610
+ merged.push(raw);
1611
+ }
1612
+ return merged;
1613
+ }
1614
+
1615
+ function modelParamDefaultValue(option = {}) {
1616
+ return option.rules?.defaultValue
1617
+ ?? option.defaultValue
1618
+ ?? option.rules?.defaultName
1619
+ ?? option.defaultName
1620
+ ?? null;
1621
+ }
1622
+
1623
+ function modelParamValueSource(option = {}) {
1624
+ const allowedValues = optionAllowedValues(option);
1625
+ if (allowedValues.length) return '只能从 allowedValues 选择。';
1626
+ if (modelParamDefaultValue(option) != null) return '模型配置提供 defaultValue;这是候选默认值,不代表可以静默代选。';
1627
+ return '来自实时 model options 的通用模型配置参数;用户明确选择后通过 --model-param key=value 或 --model-params-json 传入。';
1628
+ }
1629
+
1630
+ function isGenericModelConfigParam(option = {}) {
1631
+ const key = trimToNull(option.paramKey);
1632
+ if (!key) return false;
1633
+ if ([
1634
+ 'generated_mode',
1635
+ 'resources',
1636
+ 'iref',
1637
+ 'cref',
1638
+ 'sref',
1639
+ 'frames',
1640
+ 'multi_param',
1641
+ 'multi_prompt',
1642
+ ].includes(key)) return false;
1643
+ if (/resource|frame|image|video|audio|subject/i.test(key) && ![
1644
+ 'need_audio',
1645
+ 'audio',
1646
+ ].includes(key)) return false;
1647
+ const paramType = String(option.paramType || '');
1648
+ return Boolean(
1649
+ optionAllowedValues(option).length
1650
+ || modelParamDefaultValue(option) != null
1651
+ || /Enum|Boolean|Bool|Number|Integer|Float|Double|String|Text|Prompt/i.test(paramType),
1652
+ );
1325
1653
  }
1326
1654
 
1327
1655
  function createParamForModelOption(option = {}, taskKind = 'image') {
@@ -1457,15 +1785,26 @@ function createParamForModelOption(option = {}, taskKind = 'image') {
1457
1785
  },
1458
1786
  };
1459
1787
  return {
1460
- ...(definitions[key] ?? {
1461
- key,
1462
- cliArg: null,
1463
- requestPath: null,
1464
- materialLegacyKey: key,
1465
- meaning: '模型配置存在该参数,但当前 CLI 没有暴露为稳定创建参数;不要为了调用而硬塞旧字段。',
1466
- valueSource: '如确实需要,先扩展 CLI 显式参数和 Material adapter。',
1467
- notExposedByCli: true,
1468
- }),
1788
+ ...(definitions[key]
1789
+ ?? (isGenericModelConfigParam(option)
1790
+ ? {
1791
+ key,
1792
+ cliArg: '--model-param / --model-params-json',
1793
+ requestPath: `promptParams.${key}`,
1794
+ materialLegacyKey: key,
1795
+ meaning: option.paramName ? `模型配置参数:${option.paramName}` : '模型配置参数。',
1796
+ valueSource: modelParamValueSource(option),
1797
+ genericModelParam: true,
1798
+ }
1799
+ : {
1800
+ key,
1801
+ cliArg: null,
1802
+ requestPath: null,
1803
+ materialLegacyKey: key,
1804
+ meaning: '模型配置存在该参数,但当前 CLI 未将其识别为可安全透传的创建参数。',
1805
+ valueSource: '如确实需要,先确认该字段不是资源或旧 handler 内部字段,再扩展通用参数判定。',
1806
+ notExposedByCli: true,
1807
+ })),
1469
1808
  ...common,
1470
1809
  };
1471
1810
  }
@@ -1759,7 +2098,7 @@ function createSpecResourceRequirements(inputModes) {
1759
2098
  intent: item.intent,
1760
2099
  resource: item.requiredResources,
1761
2100
  syntax: item.resourceSyntax,
1762
- sources: item.sourceKinds,
2101
+ valueShapes: item.sourceKinds,
1763
2102
  ...item.resourceLimits,
1764
2103
  promptBinding: item.promptBinding,
1765
2104
  constraints: item.resourceConstraints,
@@ -1834,6 +2173,7 @@ function createSpecParameterControls(createParams, inputModes = []) {
1834
2173
  valueSource: item.valueSource,
1835
2174
  controlKind: item.controlKind,
1836
2175
  allowedValues: item.allowedValues,
2176
+ genericModelParam: item.genericModelParam,
1837
2177
  }));
1838
2178
  const resourceParams = createParams
1839
2179
  .filter((item) => item.key === 'resources')
@@ -1898,7 +2238,7 @@ function createSpecValidationRules(taskKind) {
1898
2238
  ];
1899
2239
  if (taskKind === 'video') {
1900
2240
  rules.splice(4, 0, 'reference_key 仅用于视频 reference 资源的可选 prompt 占位符绑定;prompt 中出现 <<<key>>> 时,必须有同名 reference 资源。');
1901
- rules.push('subject reference 必须使用 asset:<externalId>,externalId 应来自 subject publish + subject wait。');
2241
+ rules.push('subject reference 必须使用 asset:<externalId>,externalId 应来自 create subject + create subject-wait。');
1902
2242
  } else {
1903
2243
  rules.push('图片任务 resources 只接受 image reference,且不接受 reference_key 或 <<<key>>>;请用自然 prompt 描述图一、图二、参考图、主体等映射。');
1904
2244
  }
@@ -1907,8 +2247,8 @@ function createSpecValidationRules(taskKind) {
1907
2247
 
1908
2248
  function createSpecPreflight(taskKind) {
1909
2249
  const modelListCommand = taskKind === 'image' ? 'model image-models' : 'model video-models';
1910
- const feeCommand = taskKind === 'image' ? 'image fee' : 'video fee';
1911
- const createCommand = taskKind === 'image' ? 'image create' : 'video create';
2250
+ const feeCommand = taskKind === 'image' ? 'create image-fee' : 'create video-fee';
2251
+ const createCommand = taskKind === 'image' ? 'create image' : 'create video';
1912
2252
  return [
1913
2253
  'doctor --verify',
1914
2254
  `${modelListCommand} --model <keyword>`,
@@ -1927,26 +2267,26 @@ function createSpecExamples(taskKind, supportedIntents) {
1927
2267
  const examples = [];
1928
2268
  const hasIntent = (mode) => supportedIntents.some((item) => item.mode === mode);
1929
2269
  if (taskKind === 'image') {
1930
- if (hasIntent('prompt_only')) examples.push('lj-awb image create --model-group-code <code> --prompt "品牌吉祥物表情包四宫格" --ratio 1:1 --quality 1K --dry-run');
1931
- if (hasIntent('reference')) examples.push('lj-awb image create --model-group-code <code> --prompt "保持参考图主体,生成海报" --resource image:reference=./ref.png --dry-run');
2270
+ if (hasIntent('prompt_only')) examples.push('lj-awb create image --model-group-code <code> --prompt "品牌吉祥物表情包四宫格" --ratio 1:1 --quality 1K --dry-run');
2271
+ if (hasIntent('reference')) examples.push('lj-awb create image --model-group-code <code> --prompt "保持参考图主体,生成海报" --resource image:reference=./ref.png --dry-run');
1932
2272
  } else {
1933
- if (hasIntent('prompt_only')) examples.push('lj-awb video create --model-group-code <code> --prompt "机器人站在白色展台中央,缓慢转身" --duration 6 --dry-run');
2273
+ if (hasIntent('prompt_only')) examples.push('lj-awb create video --model-group-code <code> --prompt "机器人站在白色展台中央,缓慢转身" --duration 6 --dry-run');
1934
2274
  if (hasIntent('reference')) {
1935
2275
  const referenceIntent = supportedIntents.find((item) => item.mode === 'reference');
1936
- examples.push('lj-awb video create --model-group-code <code> --prompt "人物转身看向镜头" --resource image:reference=./hero.png --duration 5 --dry-run');
2276
+ examples.push('lj-awb create video --model-group-code <code> --prompt "人物转身看向镜头" --resource image:reference=./hero.png --duration 5 --dry-run');
1937
2277
  if (referenceIntent?.resourceSyntax?.some((item) => String(item).startsWith('audio:reference'))) {
1938
- examples.push('lj-awb video create --model-group-code <code> --prompt "让 <<<hero>>> 跟随音乐节奏转身" --resource image:reference:hero=./hero.png --resource audio:reference=./music.mp3 --duration 5 --dry-run');
2278
+ examples.push('lj-awb create video --model-group-code <code> --prompt "让 <<<hero>>> 跟随音乐节奏转身" --resource image:reference:hero=./hero.png --resource audio:reference=./music.mp3 --duration 5 --dry-run');
1939
2279
  }
1940
2280
  }
1941
2281
  if (hasIntent('frames')) {
1942
2282
  const framesIntent = supportedIntents.find((item) => item.mode === 'frames');
1943
- examples.push('lj-awb video create --model-group-code <code> --prompt "镜头缓慢推进" --resource image:first_frame=./first.png --duration 5 --dry-run');
1944
- examples.push('lj-awb video create --model-group-code <code> --prompt "镜头缓慢推进" --resource image:first_frame=asset:<assetId> --duration 5 --dry-run');
2283
+ examples.push('lj-awb create video --model-group-code <code> --prompt "镜头缓慢推进" --resource image:first_frame=./first.png --duration 5 --dry-run');
2284
+ examples.push('lj-awb create video --model-group-code <code> --prompt "镜头缓慢推进" --resource image:first_frame=asset:<assetId> --duration 5 --dry-run');
1945
2285
  if (framesIntent?.resourceUsages?.includes('last_frame')) {
1946
- examples.push('lj-awb video create --model-group-code <code> --prompt "从第一张过渡到第二张" --resource image:first_frame=./first.png --resource image:last_frame=./last.png --duration 5 --dry-run');
2286
+ examples.push('lj-awb create video --model-group-code <code> --prompt "从第一张过渡到第二张" --resource image:first_frame=./first.png --resource image:last_frame=./last.png --duration 5 --dry-run');
1947
2287
  }
1948
2288
  }
1949
- if (hasIntent('storyboard')) examples.push('lj-awb video create --model-group-code <code> --resources-json ./storyboard.json --duration 5 --dry-run');
2289
+ if (hasIntent('storyboard')) examples.push('lj-awb create video --model-group-code <code> --resources-json ./storyboard.json --duration 5 --dry-run');
1950
2290
  }
1951
2291
  return examples;
1952
2292
  }
@@ -1955,7 +2295,8 @@ function cliValueType(option = {}, allowedValues = []) {
1955
2295
  if (allowedValues.length) return 'enum';
1956
2296
  if (option.paramType === 'Prompt') return 'text';
1957
2297
  if (option.paramType === 'BooleanType') return 'boolean';
1958
- if (/Number|Integer|Float/i.test(String(option.paramType || ''))) return 'number';
2298
+ if (/Enum/i.test(String(option.paramType || ''))) return 'enum';
2299
+ if (/Number|Integer|Float|Double/i.test(String(option.paramType || ''))) return 'number';
1959
2300
  return option.paramType || undefined;
1960
2301
  }
1961
2302
 
@@ -1965,6 +2306,7 @@ function modelOptionParams(options = [], taskKind = 'image') {
1965
2306
  .filter(({ createParam }) => createParam.cliArg && createParam.key !== 'resources' && !createParam.internalOnly)
1966
2307
  .map(({ option, createParam }) => {
1967
2308
  const rules = option.rules || {};
2309
+ const defaultValue = modelParamDefaultValue(option);
1968
2310
  const allowedValues = optionAllowedValues(option);
1969
2311
  const required = option.required === true || rules.required === true ? true : undefined;
1970
2312
  const maxLength = option.paramType === 'Prompt'
@@ -1975,10 +2317,15 @@ function modelOptionParams(options = [], taskKind = 'image') {
1975
2317
  label: option.paramName,
1976
2318
  valueType: cliValueType(option, allowedValues),
1977
2319
  values: allowedValues.length ? allowedValues : undefined,
1978
- defaultValue: rules.defaultValue,
1979
- defaultName: rules.defaultName,
2320
+ defaultValue,
2321
+ defaultName: rules.defaultName ?? option.defaultName,
1980
2322
  maxLength,
1981
2323
  required,
2324
+ cliArg: createParam.cliArg,
2325
+ genericModelParam: createParam.genericModelParam || undefined,
2326
+ modelParamKey: createParam.modelParamKey,
2327
+ modelParamName: createParam.modelParamName,
2328
+ modelParamType: createParam.modelParamType,
1982
2329
  });
1983
2330
  });
1984
2331
  }
@@ -2019,6 +2366,7 @@ function modelOptionsResources(inputModes = []) {
2019
2366
  mode: 'frames',
2020
2367
  mediaType: 'IMAGE',
2021
2368
  usage: supportedFrameMode.optionResourceUsages,
2369
+ valueShapes: supportedFrameMode.sourceKinds,
2022
2370
  sources: supportedFrameMode.sourceKinds,
2023
2371
  ...supportedFrameMode.optionResourceLimits,
2024
2372
  formatPolicy: framePolicy.summary,
@@ -2036,7 +2384,8 @@ function modelOptionsResources(inputModes = []) {
2036
2384
  mode: optionResourceMode(sourceMode),
2037
2385
  mediaType,
2038
2386
  usage: optionResourceUsage(sourceMode),
2039
- sources: item.sources,
2387
+ valueShapes: item.valueShapes,
2388
+ sources: item.valueShapes,
2040
2389
  fileTypes: sourceMode === 'subject_reference' ? undefined : item.fileTypes,
2041
2390
  formatPolicy: imagePolicy?.summary,
2042
2391
  webpSupported: imagePolicy?.webpSupported,
@@ -2074,7 +2423,7 @@ export function modelInputGuide() {
2074
2423
  { field: 'resources[].type', values: ['image', 'video', 'audio', 'subject'], description: '资源本体类型;subject 表示已创建的主体对象。' },
2075
2424
  { field: 'resources[].usage', values: ['first_frame', 'last_frame', 'reference', 'keyframe'], description: '素材用途。' },
2076
2425
  { field: 'resources[].reference_key', values: ['custom string'], description: '仅视频 reference 资源需要占位绑定时使用;图片生图 image:reference 不使用 reference_key。subject reference 必须传。' },
2077
- { field: 'resources[].source.kind', values: ['url', 'asset_id'], description: '默认建议使用 url;asset_id 表示平台资产或主体对象 ID。' },
2426
+ { field: 'resources[].source.kind', values: ['url', 'asset_id'], description: '只接受 url、asset_id 两个枚举值。本地文件、http(s) URL、material backendPath 一律传 kind=url,CLI 按 value 自动识别;asset_id 表示平台资产或主体对象 ID。注意:模型 resources[].valueShapes 列出的 local_file / http_url / backendPath 是 value 形状分类,不是 kind 枚举。' },
2078
2427
  { field: 'resources[].source.value', description: '资源值,必填。url 传素材地址;asset_id 传资源 ID。' },
2079
2428
  { field: 'resources[].order', description: '仅 usage=keyframe 时需要,且同一请求内不能重复。' },
2080
2429
  { field: 'resources[].duration', description: '仅 keyframe 场景下用于表达该帧持续时长,可传小数秒。' },
@@ -2133,14 +2482,15 @@ export async function modelCreateSpec(kwargs = {}) {
2133
2482
  schemaVersion: 1,
2134
2483
  modelGroupCode,
2135
2484
  taskKind: context.taskKind,
2136
- createCommand: context.taskKind === 'image' ? 'image create' : 'video create',
2137
- feeCommand: context.taskKind === 'image' ? 'image fee' : 'video fee',
2485
+ createCommand: context.taskKind === 'image' ? 'create image' : 'create video',
2486
+ feeCommand: context.taskKind === 'image' ? 'create image-fee' : 'create video-fee',
2138
2487
  statusCommandTaskType: context.taskKind === 'image' ? 'IMAGE_CREATE' : 'VIDEO_GROUP',
2139
2488
  optionsCommand: `model options --model-group-code ${modelGroupCode}`,
2140
2489
  model: context.model,
2141
2490
  inputRequirement,
2142
2491
  supportedIntents,
2143
2492
  validationRules: createSpecValidationRules(context.taskKind),
2493
+ parameterControls: createSpecParameterControls(context.createParams, context.inputModes),
2144
2494
  agentGuidance: createSpecAgentGuidance(context.taskKind, inputRequirement),
2145
2495
  preflight: createSpecPreflight(context.taskKind),
2146
2496
  examples: createSpecExamples(context.taskKind, supportedIntents),
@@ -2156,7 +2506,35 @@ async function readJsonMaybeFile(value, fallback) {
2156
2506
  return JSON.parse(fileText);
2157
2507
  }
2158
2508
 
2159
- async function collectFileSpecs(kwargs = {}, defaultSceneType = TASK_UPLOAD_SCENE.DEFAULT) {
2509
+ const AUDIO_VIDEO_EXTENSIONS = new Set([
2510
+ '.aac',
2511
+ '.aiff',
2512
+ '.avi',
2513
+ '.flac',
2514
+ '.m4a',
2515
+ '.m4v',
2516
+ '.mkv',
2517
+ '.mov',
2518
+ '.mp3',
2519
+ '.mp4',
2520
+ '.mpeg',
2521
+ '.mpg',
2522
+ '.oga',
2523
+ '.ogg',
2524
+ '.ogv',
2525
+ '.wav',
2526
+ '.webm',
2527
+ ]);
2528
+
2529
+ function defaultUploadSceneForFile(filePath, mimeType = '') {
2530
+ const normalizedMime = String(mimeType || '').toLowerCase();
2531
+ if (normalizedMime.startsWith('audio/') || normalizedMime.startsWith('video/')) return TASK_UPLOAD_SCENE.VIDEO_CREATE;
2532
+ const ext = path.extname(String(filePath || '')).toLowerCase();
2533
+ if (AUDIO_VIDEO_EXTENSIONS.has(ext)) return TASK_UPLOAD_SCENE.VIDEO_CREATE;
2534
+ return TASK_UPLOAD_SCENE.DEFAULT;
2535
+ }
2536
+
2537
+ async function collectFileSpecs(kwargs = {}, defaultSceneType = null) {
2160
2538
  const specs = [];
2161
2539
  for (const file of parseListArg(kwargs.file)) specs.push({ file });
2162
2540
  for (const file of parseListArg(kwargs.files)) specs.push({ file });
@@ -2169,11 +2547,14 @@ async function collectFileSpecs(kwargs = {}, defaultSceneType = TASK_UPLOAD_SCEN
2169
2547
  }
2170
2548
  }
2171
2549
  return specs
2172
- .map((item) => ({
2173
- file: trimToNull(item.file ?? item.path ?? item.filePath),
2174
- sceneType: trimToNull(item.sceneType ?? kwargs.sceneType) ?? defaultSceneType,
2175
- projectNo: trimToNull(item.projectNo ?? kwargs.projectNo) ?? '',
2176
- }))
2550
+ .map((item) => {
2551
+ const file = trimToNull(item.file ?? item.path ?? item.filePath);
2552
+ return {
2553
+ file,
2554
+ sceneType: trimToNull(item.sceneType ?? kwargs.sceneType) ?? defaultSceneType ?? defaultUploadSceneForFile(file),
2555
+ projectNo: trimToNull(item.projectNo ?? kwargs.projectNo) ?? '',
2556
+ };
2557
+ })
2177
2558
  .filter((item) => item.file);
2178
2559
  }
2179
2560
 
@@ -2182,7 +2563,7 @@ function dryRunBackendPath(filePath, sceneType) {
2182
2563
  }
2183
2564
 
2184
2565
  export async function uploadFilesCommand(kwargs = {}) {
2185
- const specs = await collectFileSpecs(kwargs, trimToNull(kwargs.sceneType) ?? TASK_UPLOAD_SCENE.DEFAULT);
2566
+ const specs = await collectFileSpecs(kwargs, trimToNull(kwargs.sceneType));
2186
2567
  if (!specs.length) throw argumentError('缺少上传文件', '传 --file <path> 或 --files a.png,b.mp4。');
2187
2568
  if (toBool(kwargs.dryRun)) {
2188
2569
  const files = [];
@@ -2212,7 +2593,7 @@ export async function uploadLocalFile(filePath, options = {}) {
2212
2593
  throw argumentError(`文件不存在:${filePath}`);
2213
2594
  }
2214
2595
  const buffer = await fs.readFile(inspected.filePath);
2215
- const sceneType = options.sceneType ?? TASK_UPLOAD_SCENE.DEFAULT;
2596
+ const sceneType = options.sceneType ?? defaultUploadSceneForFile(inspected.filePath, inspected.mimeType);
2216
2597
  const groupId = crypto.randomUUID().replaceAll('-', '');
2217
2598
  const secret = await awbApi.fetchUploadSecret({
2218
2599
  sceneType,
@@ -2259,6 +2640,262 @@ export async function uploadLocalFile(filePath, options = {}) {
2259
2640
  });
2260
2641
  }
2261
2642
 
2643
+ function isHttpUrl(value) {
2644
+ return /^https?:\/\//i.test(String(value || '').trim());
2645
+ }
2646
+
2647
+ function isUploadedMaterialReference(value) {
2648
+ const text = trimToNull(value);
2649
+ if (!text) return false;
2650
+ if (text.startsWith('material/') || text.startsWith('/material/')) return true;
2651
+ if (!isHttpUrl(text)) return false;
2652
+ try {
2653
+ const url = new URL(text);
2654
+ return url.hostname.endsWith('.myqcloud.com');
2655
+ } catch {
2656
+ return false;
2657
+ }
2658
+ }
2659
+
2660
+ function remoteFileNameFromUrl(remoteUrl, fallback = 'voice-audio') {
2661
+ try {
2662
+ const pathname = decodeURIComponent(new URL(remoteUrl).pathname);
2663
+ const baseName = safeFileName(path.basename(pathname));
2664
+ if (baseName && baseName !== '.' && baseName !== '/') return baseName;
2665
+ } catch {}
2666
+ return `${fallback}.mp3`;
2667
+ }
2668
+
2669
+ function extensionFromContentType(contentType = '') {
2670
+ const normalized = String(contentType || '').split(';')[0].trim().toLowerCase();
2671
+ if (normalized === 'image/bmp') return '.bmp';
2672
+ if (normalized === 'image/gif') return '.gif';
2673
+ if (normalized === 'image/jpeg' || normalized === 'image/jpg') return '.jpg';
2674
+ if (normalized === 'image/png') return '.png';
2675
+ if (normalized === 'image/webp') return '.webp';
2676
+ if (normalized === 'audio/mpeg') return '.mp3';
2677
+ if (normalized === 'audio/wav' || normalized === 'audio/x-wav') return '.wav';
2678
+ if (normalized === 'audio/mp4') return '.m4a';
2679
+ if (normalized === 'audio/aac') return '.aac';
2680
+ if (normalized === 'audio/ogg') return '.ogg';
2681
+ if (normalized === 'video/mp4') return '.mp4';
2682
+ return '';
2683
+ }
2684
+
2685
+ function isSupportedRemoteVoiceDownload(contentType = '', fileName = '') {
2686
+ const normalized = String(contentType || '').split(';')[0].trim().toLowerCase();
2687
+ const extension = path.extname(fileName).toLowerCase();
2688
+ if (REMOTE_VOICE_MIME_TYPES.has(normalized)) return true;
2689
+ if ((!normalized || normalized === 'application/octet-stream') && REMOTE_VOICE_EXTENSIONS.has(extension)) return true;
2690
+ return false;
2691
+ }
2692
+
2693
+ function remoteImageFileNameFromValue(value, fallback = 'resource-image') {
2694
+ const text = trimToNull(value);
2695
+ if (text) {
2696
+ try {
2697
+ const pathname = decodeURIComponent(new URL(text).pathname);
2698
+ const baseName = safeFileName(path.basename(pathname));
2699
+ if (baseName && baseName !== '.' && baseName !== '/') return baseName;
2700
+ } catch {
2701
+ const baseName = safeFileName(path.basename(text.split('?')[0].split('#')[0]));
2702
+ if (baseName && baseName !== '.' && baseName !== '/') return baseName;
2703
+ }
2704
+ }
2705
+ return fallback;
2706
+ }
2707
+
2708
+ function extensionForImageFormat(format) {
2709
+ const normalized = normalizeFileFormat(format);
2710
+ if (!normalized) return '';
2711
+ return normalized === 'jpg' ? '.jpg' : `.${normalized}`;
2712
+ }
2713
+
2714
+ function forceFileExtension(fileName, extension) {
2715
+ const safeName = safeFileName(fileName || 'resource-image');
2716
+ if (!extension) return safeName;
2717
+ return `${path.basename(safeName, path.extname(safeName))}${extension}`;
2718
+ }
2719
+
2720
+ function isSupportedRemoteImageDownload(contentType = '', fileName = '', expectedFormat = null) {
2721
+ const normalized = String(contentType || '').split(';')[0].trim().toLowerCase();
2722
+ const extension = path.extname(fileName).toLowerCase();
2723
+ if (REMOTE_IMAGE_MIME_TYPES.has(normalized)) return true;
2724
+ if ((!normalized || normalized === 'application/octet-stream') && REMOTE_IMAGE_EXTENSIONS.has(extension)) return true;
2725
+ if ((!normalized || normalized === 'application/octet-stream') && expectedFormat && COMMON_IMAGE_FORMATS.has(normalizeFileFormat(expectedFormat))) return true;
2726
+ return false;
2727
+ }
2728
+
2729
+ function firstHttpUrl(value, depth = 0) {
2730
+ if (depth > 4 || value == null) return null;
2731
+ if (typeof value === 'string') return /^https?:\/\//i.test(value) ? value : null;
2732
+ if (Array.isArray(value)) {
2733
+ for (const item of value) {
2734
+ const found = firstHttpUrl(item, depth + 1);
2735
+ if (found) return found;
2736
+ }
2737
+ return null;
2738
+ }
2739
+ if (typeof value !== 'object') return null;
2740
+ for (const key of ['url', 'signedUrl', 'signUrl', 'downloadUrl', 'cosUrl', 'previewUrl', 'data']) {
2741
+ const found = firstHttpUrl(value[key], depth + 1);
2742
+ if (found) return found;
2743
+ }
2744
+ for (const nested of Object.values(value)) {
2745
+ const found = firstHttpUrl(nested, depth + 1);
2746
+ if (found) return found;
2747
+ }
2748
+ return null;
2749
+ }
2750
+
2751
+ async function resolveRemoteResourceDownloadUrl(value) {
2752
+ const text = trimToNull(value);
2753
+ if (!text) throw argumentError('远程图片来源为空');
2754
+ if (/^https?:\/\//i.test(text)) return text;
2755
+ if (text.startsWith('material/') || text.startsWith('/material/')) {
2756
+ const objectName = text.replace(/^\/+/, '');
2757
+ const signed = await awbApi.fetchObjectSignUrl(objectName);
2758
+ const signedUrl = firstHttpUrl(signed);
2759
+ if (signedUrl) return signedUrl;
2760
+ throw new LingjingAwbCliError('获取素材签名 URL 失败', {
2761
+ type: 'api_error',
2762
+ exitCode: 30,
2763
+ details: { objectName, payload: signed },
2764
+ });
2765
+ }
2766
+ throw argumentError(
2767
+ `远程图片来源不支持自动转换:${text}`,
2768
+ '请传 http(s) URL、material backendPath,或先下载为本地文件后重试。',
2769
+ );
2770
+ }
2771
+
2772
+ async function downloadRemoteImageFileToTemp(sourceValue, options = {}) {
2773
+ const timeoutMs = Math.max(1_000, toInt(options.timeoutMs, REMOTE_IMAGE_DOWNLOAD_TIMEOUT_MS));
2774
+ const maxBytes = Math.max(1, toInt(options.maxBytes, REMOTE_IMAGE_DOWNLOAD_MAX_BYTES));
2775
+ const remoteUrl = await resolveRemoteResourceDownloadUrl(sourceValue);
2776
+ const controller = new AbortController();
2777
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
2778
+ let dir = null;
2779
+ try {
2780
+ const response = await fetch(remoteUrl, { signal: controller.signal });
2781
+ if (!response.ok) {
2782
+ throw new LingjingAwbCliError(`下载远程图片失败:${response.status} ${response.statusText}`, {
2783
+ type: 'http_error',
2784
+ exitCode: 30,
2785
+ details: { url: sourceValue, status: response.status },
2786
+ });
2787
+ }
2788
+ const contentType = response.headers.get('content-type') || '';
2789
+ const expectedExtension = extensionForImageFormat(options.expectedFormat);
2790
+ let fileName = remoteImageFileNameFromValue(sourceValue, options.fallbackName || 'resource-image');
2791
+ fileName = expectedExtension
2792
+ ? forceFileExtension(fileName, expectedExtension)
2793
+ : (!path.extname(fileName) ? `${fileName}${extensionFromContentType(contentType) || '.img'}` : fileName);
2794
+ if (!isSupportedRemoteImageDownload(contentType, fileName, options.expectedFormat)) {
2795
+ throw argumentError(
2796
+ `远程图片类型不支持:${contentType || path.extname(fileName) || 'unknown'}`,
2797
+ '自动格式转换只支持常见图片输入,请先手动转换为 jpg/png/webp 后重试。',
2798
+ );
2799
+ }
2800
+ const contentLength = toInt(response.headers.get('content-length'), 0);
2801
+ if (contentLength > maxBytes) {
2802
+ throw argumentError(`远程图片过大:${contentLength} bytes`, `最大支持 ${maxBytes} bytes。`);
2803
+ }
2804
+ dir = await fs.mkdtemp(path.join(tmpdir(), 'lj-awb-image-'));
2805
+ const filePath = path.join(dir, fileName);
2806
+ const file = await fs.open(filePath, 'w');
2807
+ let size = 0;
2808
+ try {
2809
+ if (!response.body) throw new Error('empty response body');
2810
+ for await (const chunk of response.body) {
2811
+ const buffer = Buffer.from(chunk);
2812
+ size += buffer.length;
2813
+ if (size > maxBytes) {
2814
+ throw argumentError(`远程图片过大:超过 ${maxBytes} bytes`);
2815
+ }
2816
+ await file.write(buffer);
2817
+ }
2818
+ } finally {
2819
+ await file.close();
2820
+ }
2821
+ return { filePath, dir, contentType, size };
2822
+ } catch (error) {
2823
+ if (dir) await fs.rm(dir, { recursive: true, force: true }).catch(() => {});
2824
+ if (error instanceof LingjingAwbCliError) throw error;
2825
+ const isAbort = error?.name === 'AbortError';
2826
+ throw new LingjingAwbCliError(`下载远程图片失败:${error.message}`, {
2827
+ type: 'network_error',
2828
+ exitCode: 30,
2829
+ hint: isAbort ? `远程下载超过 ${timeoutMs}ms,请改用本地文件或已上传 material 路径。` : '',
2830
+ details: { url: sourceValue, causeCode: error?.cause?.code },
2831
+ });
2832
+ } finally {
2833
+ clearTimeout(timeout);
2834
+ }
2835
+ }
2836
+
2837
+ async function downloadRemoteFileToTemp(remoteUrl, options = {}) {
2838
+ const timeoutMs = Math.max(1_000, toInt(options.timeoutMs, REMOTE_VOICE_DOWNLOAD_TIMEOUT_MS));
2839
+ const maxBytes = Math.max(1, toInt(options.maxBytes, REMOTE_VOICE_DOWNLOAD_MAX_BYTES));
2840
+ const controller = new AbortController();
2841
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
2842
+ let dir = null;
2843
+ let response;
2844
+ try {
2845
+ response = await fetch(remoteUrl, { signal: controller.signal });
2846
+ if (!response.ok) {
2847
+ throw new LingjingAwbCliError(`下载远程音频失败:${response.status} ${response.statusText}`, {
2848
+ type: 'http_error',
2849
+ exitCode: 30,
2850
+ details: { url: remoteUrl, status: response.status },
2851
+ });
2852
+ }
2853
+ const contentType = response.headers.get('content-type') || '';
2854
+ let fileName = remoteFileNameFromUrl(remoteUrl, options.fallbackName || 'voice-audio');
2855
+ if (!path.extname(fileName)) fileName = `${fileName}${extensionFromContentType(contentType) || '.mp3'}`;
2856
+ if (!isSupportedRemoteVoiceDownload(contentType, fileName)) {
2857
+ throw argumentError(
2858
+ `远程音频类型不支持:${contentType || path.extname(fileName) || 'unknown'}`,
2859
+ 'create subject-voice 只支持 mp3、wav、m4a、aac、ogg 音频或 mp4 视频来源。',
2860
+ );
2861
+ }
2862
+ const contentLength = toInt(response.headers.get('content-length'), 0);
2863
+ if (contentLength > maxBytes) {
2864
+ throw argumentError(`远程音频过大:${contentLength} bytes`, `最大支持 ${maxBytes} bytes。`);
2865
+ }
2866
+ dir = await fs.mkdtemp(path.join(tmpdir(), 'lj-awb-voice-'));
2867
+ const filePath = path.join(dir, fileName);
2868
+ const file = await fs.open(filePath, 'w');
2869
+ let size = 0;
2870
+ try {
2871
+ if (!response.body) throw new Error('empty response body');
2872
+ for await (const chunk of response.body) {
2873
+ const buffer = Buffer.from(chunk);
2874
+ size += buffer.length;
2875
+ if (size > maxBytes) {
2876
+ throw argumentError(`远程音频过大:超过 ${maxBytes} bytes`);
2877
+ }
2878
+ await file.write(buffer);
2879
+ }
2880
+ } finally {
2881
+ await file.close();
2882
+ }
2883
+ return { filePath, dir, contentType, size };
2884
+ } catch (error) {
2885
+ if (dir) await fs.rm(dir, { recursive: true, force: true }).catch(() => {});
2886
+ if (error instanceof LingjingAwbCliError) throw error;
2887
+ const isAbort = error?.name === 'AbortError';
2888
+ throw new LingjingAwbCliError(`下载远程音频失败:${error.message}`, {
2889
+ type: 'network_error',
2890
+ exitCode: 30,
2891
+ hint: isAbort ? `远程下载超过 ${timeoutMs}ms,请改用本地 --file 或已上传 material 路径。` : '',
2892
+ details: { url: remoteUrl, causeCode: error?.cause?.code },
2893
+ });
2894
+ } finally {
2895
+ clearTimeout(timeout);
2896
+ }
2897
+ }
2898
+
2262
2899
  function resolveCustomBizId(explicit) {
2263
2900
  return trimToNull(explicit);
2264
2901
  }
@@ -2297,6 +2934,59 @@ function normalizeUnifiedPromptParams(promptParams) {
2297
2934
  return promptParams;
2298
2935
  }
2299
2936
 
2937
+ async function parseModelParamsJsonArg(value) {
2938
+ const parsed = await readJsonMaybeFile(value, null).catch((error) => {
2939
+ throw argumentError(`model-params-json 解析失败:${error.message}`);
2940
+ });
2941
+ if (parsed == null) return {};
2942
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
2943
+ throw argumentError('model-params-json 必须是 JSON 对象');
2944
+ }
2945
+ return parsed;
2946
+ }
2947
+
2948
+ function parseModelParamAssignments(value) {
2949
+ const params = {};
2950
+ for (const item of parseListArg(value)) {
2951
+ const text = trimToNull(item);
2952
+ if (!text) continue;
2953
+ const eqIndex = text.indexOf('=');
2954
+ if (eqIndex <= 0) {
2955
+ throw argumentError(`model-param 格式错误:${text}`, '格式为 --model-param key=value,可重复传。');
2956
+ }
2957
+ const key = trimToNull(text.slice(0, eqIndex));
2958
+ if (!key) {
2959
+ throw argumentError(`model-param 缺少 key:${text}`);
2960
+ }
2961
+ params[key] = text.slice(eqIndex + 1);
2962
+ }
2963
+ return params;
2964
+ }
2965
+
2966
+ async function collectGenericModelParams(kwargs = {}) {
2967
+ const fromJson = await parseModelParamsJsonArg(kwargs.modelParamsJson);
2968
+ const fromObject = kwargs.modelParams && typeof kwargs.modelParams === 'object' && !Array.isArray(kwargs.modelParams)
2969
+ ? kwargs.modelParams
2970
+ : {};
2971
+ const fromAssignments = parseModelParamAssignments(kwargs.modelParam);
2972
+ const fromDynamicFlags = {};
2973
+ for (const [key, value] of Object.entries(kwargs || {})) {
2974
+ if (CREATE_STANDARD_KWARG_KEYS.has(key)) continue;
2975
+ if (!key.includes('_') && !isLikelyDynamicModelParamKey(key)) continue;
2976
+ fromDynamicFlags[key] = value;
2977
+ }
2978
+ return normalizeUnifiedPromptParams({
2979
+ ...fromJson,
2980
+ ...fromObject,
2981
+ ...fromDynamicFlags,
2982
+ ...fromAssignments,
2983
+ });
2984
+ }
2985
+
2986
+ function isLikelyDynamicModelParamKey(key) {
2987
+ return /^(generation|prompt|negative|seed|style|mode|cfg|guidance|aspect|image|output|response|media|safety|watermark|camera|motion|strength|steps)[A-Z]/.test(String(key || ''));
2988
+ }
2989
+
2300
2990
  function normalizeResourceType(type, index) {
2301
2991
  const normalized = String(type ?? '').trim().toLowerCase();
2302
2992
  if (!RESOURCE_TYPES.has(normalized)) {
@@ -2330,7 +3020,10 @@ function normalizeResourceSource(source, type, index, options = {}) {
2330
3020
  ? explicitKind.toLowerCase()
2331
3021
  : (rawValue?.startsWith('asset:') || type === 'subject' ? 'asset_id' : 'url');
2332
3022
  if (!['url', 'asset_id'].includes(kind)) {
2333
- throw argumentError(`resource[${index}] source.kind 不支持:${kind}`, '支持 url、asset_id。');
3023
+ throw argumentError(
3024
+ `resource[${index}] source.kind 不支持:${explicitKind}`,
3025
+ '只支持 url、asset_id 两个值。本地文件 / http(s) URL / material backendPath 都统一传 kind=url(CLI 按 value 自动识别);平台资产或主体对象传 kind=asset_id。',
3026
+ );
2334
3027
  }
2335
3028
  const value = kind === 'asset_id' ? assetValue : rawValue;
2336
3029
  if (!value) {
@@ -2506,6 +3199,18 @@ function normalizeMaterialUrlValue(value) {
2506
3199
  return text;
2507
3200
  }
2508
3201
 
3202
+ function displayResourceSourceValue(value) {
3203
+ const text = trimToNull(value);
3204
+ if (!text || !/^https?:\/\//i.test(text)) return text;
3205
+ try {
3206
+ const url = new URL(text);
3207
+ const format = imageTransformFormat(text);
3208
+ return `${url.origin}${decodeURIComponent(url.pathname)}${format ? `?format=${format}` : ''}`;
3209
+ } catch {
3210
+ return text.split('?')[0];
3211
+ }
3212
+ }
3213
+
2509
3214
  function conversionOutputExtension(format) {
2510
3215
  const normalized = normalizeFileFormat(format);
2511
3216
  if (normalized === 'jpg') return 'jpg';
@@ -2570,6 +3275,60 @@ async function resolveResourceFileValue(resource, options = {}) {
2570
3275
  }
2571
3276
  const value = resource._source.value;
2572
3277
  if (isRemoteOrBackendPath(value)) {
3278
+ const source = { kind: 'url', value };
3279
+ const conversion = options.resourceRules
3280
+ ? resourceFormatConversion(
3281
+ options.resourceRules.find((item) => resourceRuleMatches(item, { ...base, source })),
3282
+ { resource: { ...base, source } },
3283
+ )
3284
+ : null;
3285
+ if (conversion) {
3286
+ const conversionRecord = compactRecord({
3287
+ resource: resourceText(base),
3288
+ fromFormat: conversion.fromFormat,
3289
+ toFormat: conversion.toFormat,
3290
+ reason: conversion.reason,
3291
+ sourceValue: displayResourceSourceValue(value),
3292
+ dryRun: options.dryRun || undefined,
3293
+ });
3294
+ const convertedName = forceFileExtension(
3295
+ remoteImageFileNameFromValue(value, resourceText(base).replace(/[^0-9A-Za-z._-]+/g, '-')),
3296
+ extensionForImageFormat(conversion.toFormat),
3297
+ );
3298
+ if (options.dryRun) {
3299
+ return {
3300
+ resource: { ...base, source: { kind: 'url', value: dryRunBackendPath(convertedName, options.sceneType) } },
3301
+ upload: null,
3302
+ localFile: null,
3303
+ conversion: conversionRecord,
3304
+ };
3305
+ }
3306
+ const downloaded = await downloadRemoteImageFileToTemp(value, {
3307
+ expectedFormat: conversion.fromFormat,
3308
+ fallbackName: resourceText(base).replace(/[^0-9A-Za-z._-]+/g, '-'),
3309
+ });
3310
+ try {
3311
+ const converted = await convertLocalImageFile(downloaded.filePath, conversion.toFormat);
3312
+ try {
3313
+ const upload = await uploadLocalFile(converted.filePath, { sceneType: options.sceneType });
3314
+ return {
3315
+ resource: { ...base, source: { kind: 'url', value: upload.backendPath } },
3316
+ upload,
3317
+ localFile: null,
3318
+ conversion: {
3319
+ ...conversionRecord,
3320
+ sourceSize: downloaded.size,
3321
+ convertedFile: converted.filePath,
3322
+ convertedSize: converted.size,
3323
+ },
3324
+ };
3325
+ } finally {
3326
+ await fs.rm(converted.filePath, { force: true }).catch(() => {});
3327
+ }
3328
+ } finally {
3329
+ await fs.rm(downloaded.dir, { recursive: true, force: true }).catch(() => {});
3330
+ }
3331
+ }
2573
3332
  return { resource: { ...base, source: { kind: 'url', value: normalizeMaterialUrlValue(value) } }, upload: null, localFile: null };
2574
3333
  }
2575
3334
  const inspected = await inspectLocalFile(value);
@@ -2699,7 +3458,9 @@ async function buildImageRequest(kwargs = {}, options = {}) {
2699
3458
  kind: 'image',
2700
3459
  sceneType: TASK_UPLOAD_SCENE.IMAGE_CREATE,
2701
3460
  });
3461
+ const genericModelParams = await collectGenericModelParams(kwargs);
2702
3462
  const defaultParams = {
3463
+ ...genericModelParams,
2703
3464
  prompt,
2704
3465
  resources: validationResources.resources,
2705
3466
  };
@@ -2765,7 +3526,7 @@ export async function imageFee(kwargs = {}) {
2765
3526
  const built = await buildImageRequest(kwargs, { dryRun: true, includeCustomBizId: false });
2766
3527
  return compactRecord({
2767
3528
  dryRun: true,
2768
- action: 'image fee',
3529
+ action: 'create image-fee',
2769
3530
  request: built.request,
2770
3531
  ...(built.resourceConversions.length ? { resourceConversions: built.resourceConversions } : {}),
2771
3532
  });
@@ -2820,13 +3581,13 @@ export async function imageCreate(kwargs = {}) {
2820
3581
  const built = await buildImageRequest(kwargs, { dryRun: true });
2821
3582
  return compactRecord({
2822
3583
  dryRun: true,
2823
- action: 'image create',
3584
+ action: 'create image',
2824
3585
  request: built.request,
2825
3586
  ...(built.localFiles.length ? { localFiles: built.localFiles } : {}),
2826
3587
  ...(built.resourceConversions.length ? { resourceConversions: built.resourceConversions } : {}),
2827
3588
  });
2828
3589
  }
2829
- ensureConfirmed(kwargs, '正式生图会消耗积分,需要确认', { action: 'image create' });
3590
+ ensureConfirmed(kwargs, '正式生图会消耗积分,需要确认', { action: 'create image' });
2830
3591
  const built = await buildImageRequest(kwargs);
2831
3592
  const feePayload = await awbApi.fetchImageFee(built.request).catch(() => null);
2832
3593
  const estimate = await pointEstimate(feePayload, built.projectGroupNo).catch(() => ({}));
@@ -2877,7 +3638,9 @@ async function buildVideoRequest(kwargs = {}, options = {}) {
2877
3638
  throw argumentError('缺少视频生成输入', '至少传 --prompt 或 --resource。');
2878
3639
  }
2879
3640
  assertVideoReferenceKeysUsed(prompt, validationResources.resources);
3641
+ const genericModelParams = await collectGenericModelParams(kwargs);
2880
3642
  const defaultParams = {
3643
+ ...genericModelParams,
2881
3644
  prompt,
2882
3645
  resources: validationResources.resources,
2883
3646
  };
@@ -2919,7 +3682,7 @@ export async function videoFee(kwargs = {}) {
2919
3682
  const built = await buildVideoRequest(kwargs, { dryRun: true, includeCustomBizId: false });
2920
3683
  return compactRecord({
2921
3684
  dryRun: true,
2922
- action: 'video fee',
3685
+ action: 'create video-fee',
2923
3686
  request: built.request,
2924
3687
  ...(built.resourceConversions.length ? { resourceConversions: built.resourceConversions } : {}),
2925
3688
  });
@@ -2937,13 +3700,13 @@ export async function videoCreate(kwargs = {}) {
2937
3700
  const built = await buildVideoRequest(kwargs, { dryRun: true });
2938
3701
  return compactRecord({
2939
3702
  dryRun: true,
2940
- action: 'video create',
3703
+ action: 'create video',
2941
3704
  request: built.request,
2942
3705
  ...(built.localFiles.length ? { localFiles: built.localFiles } : {}),
2943
3706
  ...(built.resourceConversions.length ? { resourceConversions: built.resourceConversions } : {}),
2944
3707
  });
2945
3708
  }
2946
- ensureConfirmed(kwargs, '正式生视频会消耗积分,需要确认', { action: 'video create' });
3709
+ ensureConfirmed(kwargs, '正式生视频会消耗积分,需要确认', { action: 'create video' });
2947
3710
  const built = await buildVideoRequest(kwargs);
2948
3711
  const feePayload = await awbApi.fetchVideoFee(built.request).catch(() => null);
2949
3712
  const estimate = await pointEstimate(feePayload, built.projectGroupNo).catch(() => ({}));
@@ -3008,6 +3771,11 @@ const IMAGE_BATCH_ITEM_KEYS = new Set([
3008
3771
  'quality',
3009
3772
  'generate_num',
3010
3773
  'generateNum',
3774
+ 'model_param',
3775
+ 'modelParam',
3776
+ 'model_params',
3777
+ 'modelParams',
3778
+ 'modelParamsJson',
3011
3779
  'resource',
3012
3780
  'resources',
3013
3781
  'resourcesJson',
@@ -3020,6 +3788,11 @@ const VIDEO_BATCH_ITEM_KEYS = new Set([
3020
3788
  'duration',
3021
3789
  'need_audio',
3022
3790
  'needAudio',
3791
+ 'model_param',
3792
+ 'modelParam',
3793
+ 'model_params',
3794
+ 'modelParams',
3795
+ 'modelParamsJson',
3023
3796
  'resource',
3024
3797
  'resources',
3025
3798
  'resourcesJson',
@@ -3031,18 +3804,20 @@ function normalizeTaskBatchItem(item, kind, index) {
3031
3804
  throw argumentError(`批量输入第 ${index + 1} 项必须是 JSON 对象或纯文本 prompt`);
3032
3805
  }
3033
3806
  const allowedKeys = kind === 'image' ? IMAGE_BATCH_ITEM_KEYS : VIDEO_BATCH_ITEM_KEYS;
3034
- const unknownKeys = Object.keys(item).filter((key) => !allowedKeys.has(key));
3807
+ const unknownKeys = Object.keys(item).filter((key) => !allowedKeys.has(key) && !key.includes('_'));
3035
3808
  if (unknownKeys.length) {
3036
3809
  throw argumentError(
3037
3810
  `批量输入第 ${index + 1} 项存在未知字段:${unknownKeys.join(', ')}`,
3038
3811
  kind === 'image'
3039
- ? '生图批量项只接受 prompt、ratio、quality、generate_num、resources、resource、customBizId。'
3040
- : '生视频批量项只接受 prompt、ratio、quality、duration、need_audio、resources、resource、customBizId。',
3812
+ ? '生图批量项只接受 prompt、ratio、quality、generate_num、resources、resource、model_params、customBizId,或 model options.params[] 中的下划线参数。'
3813
+ : '生视频批量项只接受 prompt、ratio、quality、duration、need_audio、resources、resource、model_params、customBizId,或 model options.params[] 中的下划线参数。',
3041
3814
  );
3042
3815
  }
3043
3816
  const next = { ...item };
3044
3817
  if (next.generate_num != null && next.generateNum == null) next.generateNum = next.generate_num;
3045
3818
  if (next.need_audio != null && next.needAudio == null) next.needAudio = next.need_audio;
3819
+ if (next.model_param != null && next.modelParam == null) next.modelParam = next.model_param;
3820
+ if (next.model_params != null && next.modelParams == null) next.modelParams = next.model_params;
3046
3821
  return next;
3047
3822
  }
3048
3823
 
@@ -3079,7 +3854,7 @@ export async function imageCreateBatch(kwargs = {}) {
3079
3854
  }
3080
3855
  return { dryRun: true, count: items.length, results };
3081
3856
  }
3082
- ensureConfirmed(kwargs, '批量生图会多次消耗积分,需要确认', { action: 'image create-batch', count: items.length });
3857
+ ensureConfirmed(kwargs, '批量生图会多次消耗积分,需要确认', { action: 'create image-batch', count: items.length });
3083
3858
  const results = await runConcurrent(items, kwargs.concurrency ?? 1, async (item, index) => ({
3084
3859
  inputIndex: index,
3085
3860
  status: 'success',
@@ -3098,7 +3873,7 @@ export async function videoCreateBatch(kwargs = {}) {
3098
3873
  }
3099
3874
  return { dryRun: true, count: items.length, results };
3100
3875
  }
3101
- ensureConfirmed(kwargs, '批量生视频会多次消耗积分,需要确认', { action: 'video create-batch', count: items.length });
3876
+ ensureConfirmed(kwargs, '批量生视频会多次消耗积分,需要确认', { action: 'create video-batch', count: items.length });
3102
3877
  const results = await runConcurrent(items, kwargs.concurrency ?? 1, async (item, index) => ({
3103
3878
  inputIndex: index,
3104
3879
  status: 'success',
@@ -3311,6 +4086,7 @@ function normalizeAssetGroup(item = {}) {
3311
4086
  groupId: item?.id ?? item?.groupId ?? item?.assetGroupsId ?? null,
3312
4087
  name: item?.name ?? item?.groupName ?? null,
3313
4088
  description: item?.description ?? null,
4089
+ platform: item?.platform ?? null,
3314
4090
  projectName: item?.projectName ?? null,
3315
4091
  };
3316
4092
  }
@@ -3384,12 +4160,64 @@ function normalizeSubjectTagIds(tagList) {
3384
4160
  return uniqueNonEmpty(tagList.map((item) => (typeof item === 'string' ? item : item?.tagId ?? item?.id ?? item?.tagCode)));
3385
4161
  }
3386
4162
 
4163
+ function normalizeSubjectTaskMeta(item = {}) {
4164
+ const rawTaskStatus = item?.taskStatus ?? item?.task_status ?? null;
4165
+ const taskStatus = rawTaskStatus ? taskStatusText(rawTaskStatus) : null;
4166
+ const errorMessage = trimToNull(
4167
+ item?.errorMessage
4168
+ ?? item?.error_msg
4169
+ ?? item?.errorMsg
4170
+ ?? item?.resultMessage
4171
+ ?? item?.result_msg
4172
+ ?? item?.resultMsg
4173
+ ?? item?.message
4174
+ ?? item?.msg,
4175
+ );
4176
+ return {
4177
+ taskStatus,
4178
+ errorMessage,
4179
+ isTerminal: taskStatus ? isTerminalTaskStatus(taskStatus) : false,
4180
+ isSuccess: taskStatus ? isSuccessTaskStatus(taskStatus) : false,
4181
+ };
4182
+ }
4183
+
4184
+ function subjectResourceStatus(externalId, taskMeta) {
4185
+ if (externalId) return 'ready';
4186
+ if (taskMeta?.taskStatus && taskMeta.isTerminal) {
4187
+ return taskMeta.isSuccess ? 'missing_external_id' : 'failed';
4188
+ }
4189
+ return 'pending_external_id';
4190
+ }
4191
+
4192
+ function subjectFailureDetails(record, kind = 'subject') {
4193
+ if (!record) return null;
4194
+ const taskStatus = taskStatusText(record.taskStatus);
4195
+ if (!taskStatus || !isTerminalTaskStatus(taskStatus)) return null;
4196
+ const fallback = kind === 'voice'
4197
+ ? '主体音色创建失败'
4198
+ : '主体创建失败';
4199
+ if (!isSuccessTaskStatus(taskStatus)) {
4200
+ return {
4201
+ taskStatus,
4202
+ errorMessage: record.errorMessage || fallback,
4203
+ };
4204
+ }
4205
+ if (!record.externalId) {
4206
+ return {
4207
+ taskStatus,
4208
+ errorMessage: record.errorMessage || `${fallback}:任务已终态但未返回externalId`,
4209
+ };
4210
+ }
4211
+ return null;
4212
+ }
4213
+
3387
4214
  function normalizeSubjectRecord(item = {}) {
3388
4215
  const referList = Array.isArray(item?.elementReferList) ? item.elementReferList : [];
3389
4216
  const videoList = Array.isArray(item?.elementVideoList) ? item.elementVideoList : [];
3390
4217
  const elementId = item?.id ?? item?.subjectId ?? item?.elementId ?? null;
3391
4218
  const externalId = item?.externalId ?? item?.external_id ?? null;
3392
4219
  const name = item?.elementName ?? item?.name ?? item?.subjectName ?? null;
4220
+ const taskMeta = normalizeSubjectTaskMeta(item);
3393
4221
  return {
3394
4222
  subjectId: externalId ?? elementId,
3395
4223
  elementId,
@@ -3412,6 +4240,33 @@ function normalizeSubjectRecord(item = {}) {
3412
4240
  tagIds: normalizeSubjectTagIds(item?.tagList),
3413
4241
  ...(trimToNull(item?.elementVoiceId) ? { voiceId: trimToNull(item.elementVoiceId) } : {}),
3414
4242
  ...(externalId && name ? { nextRefSubject: `${name}=${externalId}` } : {}),
4243
+ taskStatus: taskMeta.taskStatus,
4244
+ errorMessage: taskMeta.errorMessage,
4245
+ isTerminal: externalId ? true : taskMeta.isTerminal,
4246
+ status: subjectResourceStatus(externalId, taskMeta),
4247
+ createdAt: item?.gmtCreate ?? item?.createdAt ?? null,
4248
+ };
4249
+ }
4250
+
4251
+ function normalizeSubjectVoiceRecord(item = {}) {
4252
+ const voiceRecordId = item?.voiceRecordId ?? item?.id ?? item?.reqTaskId ?? item?.voiceTaskId ?? null;
4253
+ const reqTaskId = item?.reqTaskId ?? voiceRecordId;
4254
+ const externalId = item?.externalId ?? item?.external_id ?? item?.voice_id ?? item?.voiceId ?? null;
4255
+ const name = item?.voiceName ?? item?.name ?? null;
4256
+ const taskMeta = normalizeSubjectTaskMeta(item);
4257
+ return {
4258
+ voiceRecordId,
4259
+ reqTaskId,
4260
+ voiceId: externalId,
4261
+ externalId,
4262
+ name,
4263
+ voiceUrl: item?.voiceUrl ?? item?.voice_url ?? item?.audioUrl ?? item?.audio_url ?? null,
4264
+ videoId: item?.videoId ?? item?.video_id ?? null,
4265
+ status: subjectResourceStatus(externalId, taskMeta),
4266
+ taskStatus: taskMeta.taskStatus,
4267
+ errorMessage: taskMeta.errorMessage,
4268
+ isTerminal: externalId ? true : taskMeta.isTerminal,
4269
+ ...(externalId ? { nextVoiceArg: `--voice-id ${externalId}` } : {}),
3415
4270
  createdAt: item?.gmtCreate ?? item?.createdAt ?? null,
3416
4271
  };
3417
4272
  }
@@ -3439,45 +4294,55 @@ export async function assetMatchActor(kwargs = {}) {
3439
4294
  }
3440
4295
 
3441
4296
  export async function assetGroupList(kwargs = {}) {
4297
+ const platform = requireAssetPlatform(kwargs.platform);
3442
4298
  const payload = await awbApi.listAssetGroups({
3443
4299
  name: kwargs.name ?? '',
4300
+ platform,
3444
4301
  pageNumber: toInt(kwargs.pageNumber, 1),
3445
4302
  pageSize: toInt(kwargs.pageSize, 20),
3446
4303
  ...(parseListArg(kwargs.groupIds).length ? { groupIds: parseListArg(kwargs.groupIds) } : {}),
3447
4304
  });
3448
- return { groups: extractAssetGroupRows(payload), raw: toBool(kwargs.includeRaw) ? payload : undefined };
4305
+ return { platform, groups: extractAssetGroupRows(payload), raw: toBool(kwargs.includeRaw) ? payload : undefined };
3449
4306
  }
3450
4307
 
3451
4308
  export async function assetGroupGet(kwargs = {}) {
3452
4309
  const groupId = requireValue(kwargs, 'groupId', 'group-id');
3453
- const payload = await awbApi.getAssetGroup(groupId);
3454
- return payload && typeof payload === 'object' && !Array.isArray(payload)
3455
- ? normalizeAssetGroup(payload)
3456
- : extractAssetGroupRows(payload)[0] ?? { groupId };
4310
+ const platform = requireAssetPlatform(kwargs.platform);
4311
+ const payload = await awbApi.getAssetGroup(groupId, { platform });
4312
+ if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
4313
+ const group = normalizeAssetGroup(payload);
4314
+ return { ...group, platform: group.platform ?? platform };
4315
+ }
4316
+ return extractAssetGroupRows(payload)[0] ?? { groupId, platform };
3457
4317
  }
3458
4318
 
3459
4319
  export async function assetGroupCreate(kwargs = {}) {
3460
4320
  const name = requireValue(kwargs, 'name');
4321
+ const platform = requireAssetPlatform(kwargs.platform);
3461
4322
  const body = {
3462
4323
  name,
3463
4324
  description: kwargs.description ?? '',
4325
+ platform,
3464
4326
  projectName: kwargs.projectName ?? 'default',
3465
4327
  };
3466
- if (toBool(kwargs.dryRun)) return { dryRun: true, action: 'asset group-create', request: body };
3467
- ensureConfirmed(kwargs, '创建素材组是云端写入动作,需要确认', { action: 'asset group-create', body });
4328
+ if (toBool(kwargs.dryRun)) return { dryRun: true, action: 'create asset-group', request: body };
4329
+ ensureConfirmed(kwargs, '创建素材组是云端写入动作,需要确认', { action: 'create asset-group', body });
3468
4330
  const payload = await awbApi.createAssetGroup(body);
3469
- return { created: true, groupId: payload?.id ?? payload?.groupId ?? payload ?? null, name, projectName: body.projectName };
4331
+ return { created: true, groupId: payload?.id ?? payload?.groupId ?? payload ?? null, name, platform, projectName: body.projectName };
3470
4332
  }
3471
4333
 
3472
4334
  export async function assetGroupUpdate(kwargs = {}) {
3473
4335
  const groupId = requireValue(kwargs, 'groupId', 'group-id');
3474
- const body = {};
4336
+ const platform = requireAssetPlatform(kwargs.platform);
4337
+ const body = { platform };
3475
4338
  if (kwargs.name != null) body.name = kwargs.name;
3476
4339
  if (kwargs.description != null) body.description = kwargs.description;
3477
4340
  if (kwargs.projectName != null) body.projectName = kwargs.projectName;
3478
- if (!Object.keys(body).length) throw argumentError('缺少素材组更新字段', '至少传 --name、--description 或 --project-name。');
3479
- if (toBool(kwargs.dryRun)) return { dryRun: true, action: 'asset group-update', groupId, request: body };
3480
- ensureConfirmed(kwargs, '更新素材组是云端写入动作,需要确认', { action: 'asset group-update', groupId, body });
4341
+ if (!['name', 'description', 'projectName'].some((key) => Object.prototype.hasOwnProperty.call(body, key))) {
4342
+ throw argumentError('缺少素材组更新字段', '至少传 --name、--description 或 --project-name;--platform 只用于定位平台资产组。');
4343
+ }
4344
+ if (toBool(kwargs.dryRun)) return { dryRun: true, action: 'create asset-group-update', groupId, request: body };
4345
+ ensureConfirmed(kwargs, '更新素材组是云端写入动作,需要确认', { action: 'create asset-group-update', groupId, body });
3481
4346
  await awbApi.updateAssetGroup(groupId, body);
3482
4347
  return { updated: true, groupId, ...body };
3483
4348
  }
@@ -3491,29 +4356,30 @@ function extractAssetId(payload) {
3491
4356
  export async function assetRegister(kwargs = {}) {
3492
4357
  const groupId = requireValue(kwargs, 'groupId', 'group-id');
3493
4358
  const name = requireValue(kwargs, 'name');
4359
+ const platform = requireAssetPlatform(kwargs.platform);
3494
4360
  const localFile = trimToNull(kwargs.file);
3495
4361
  const assetPath = trimToNull(kwargs.backendPath) ?? normalizeCosAssetPath(kwargs.url);
3496
4362
  if (!localFile && !assetPath) throw argumentError('缺少素材路径', '传 --file、--backend-path 或 --url。');
3497
4363
  if (toBool(kwargs.dryRun)) {
3498
4364
  return {
3499
4365
  dryRun: true,
3500
- action: 'asset register',
4366
+ action: 'create asset',
3501
4367
  request: {
3502
4368
  assetGroupsId: groupId,
3503
- url: localFile ? normalizeCosAssetPath(dryRunBackendPath(localFile, TASK_UPLOAD_SCENE.SUBJECT)) : assetPath,
4369
+ url: localFile ? normalizeCosAssetPath(dryRunBackendPath(localFile, TASK_UPLOAD_SCENE.ASSET_REVIEW)) : assetPath,
3504
4370
  name,
3505
- ...(kwargs.platform ? { platform: kwargs.platform } : {}),
4371
+ platform,
3506
4372
  },
3507
4373
  localFile: localFile ? await inspectLocalFile(localFile) : null,
3508
4374
  };
3509
4375
  }
3510
- ensureConfirmed(kwargs, '注册素材是云端写入动作,需要确认', { action: 'asset register', groupId, name });
3511
- const uploaded = localFile ? await uploadLocalFile(localFile, { sceneType: TASK_UPLOAD_SCENE.SUBJECT }) : null;
4376
+ ensureConfirmed(kwargs, '注册素材是云端写入动作,需要确认', { action: 'create asset', groupId, name });
4377
+ const uploaded = localFile ? await uploadLocalFile(localFile, { sceneType: TASK_UPLOAD_SCENE.ASSET_REVIEW }) : null;
3512
4378
  const body = {
3513
4379
  assetGroupsId: groupId,
3514
4380
  url: normalizeCosAssetPath(uploaded?.backendPath ?? assetPath),
3515
4381
  name,
3516
- ...(kwargs.platform ? { platform: kwargs.platform } : {}),
4382
+ platform,
3517
4383
  };
3518
4384
  const payload = await awbApi.registerAsset(body);
3519
4385
  return {
@@ -3521,6 +4387,7 @@ export async function assetRegister(kwargs = {}) {
3521
4387
  assetId: extractAssetId(payload),
3522
4388
  groupId,
3523
4389
  name,
4390
+ platform,
3524
4391
  assetPath: body.url,
3525
4392
  ...(uploaded ? { upload: uploaded } : {}),
3526
4393
  };
@@ -3542,13 +4409,255 @@ export async function subjectList(kwargs = {}) {
3542
4409
  };
3543
4410
  }
3544
4411
 
4412
+ export async function subjectVoiceList(kwargs = {}) {
4413
+ const keyword = trimToNull(kwargs.keyword ?? kwargs.name);
4414
+ const payload = keyword
4415
+ ? await awbApi.listVoicesByName(keyword)
4416
+ : await awbApi.listVoices();
4417
+ const voices = paginateRows(
4418
+ normalizeRows(payload).map((item) => normalizeSubjectVoiceRecord(item)),
4419
+ kwargs.pageNumber,
4420
+ kwargs.pageSize,
4421
+ );
4422
+ return {
4423
+ voices,
4424
+ ...(toBool(kwargs.includeRaw) ? { raw: payload } : {}),
4425
+ };
4426
+ }
4427
+
4428
+ function subjectVoiceSource(kwargs = {}) {
4429
+ const file = trimToNull(kwargs.file);
4430
+ const voiceUrlArg = trimToNull(kwargs.voiceUrl);
4431
+ const audioUrlArg = trimToNull(kwargs.audioUrl);
4432
+ if (voiceUrlArg && audioUrlArg) {
4433
+ throw argumentError('音色来源只能选择一种', '--voice-url 和 --audio-url 是同一含义的别名,只能传一个。');
4434
+ }
4435
+ const voiceUrl = voiceUrlArg ?? audioUrlArg ?? trimToNull(kwargs.url);
4436
+ const videoId = trimToNull(kwargs.videoId);
4437
+ const sourceCount = [file, voiceUrl, videoId].filter(Boolean).length;
4438
+ if (sourceCount === 0) {
4439
+ throw argumentError('缺少音色来源', '传 --file <audio>、--voice-url/--audio-url <material path> 或 --video-id <id>。');
4440
+ }
4441
+ if (sourceCount > 1) {
4442
+ throw argumentError('音色来源只能选择一种', '--file、--voice-url/--audio-url、--video-id 三者只能传一个。');
4443
+ }
4444
+ const shouldUploadRemoteUrl = Boolean(voiceUrl && isHttpUrl(voiceUrl) && !isUploadedMaterialReference(voiceUrl));
4445
+ return { file, voiceUrl, videoId, shouldUploadRemoteUrl };
4446
+ }
4447
+
4448
+ function buildSubjectVoiceCreateBody(kwargs, source, uploaded = null) {
4449
+ const name = requireValue(kwargs, 'name');
4450
+ const voiceUrl = uploaded
4451
+ ? normalizeCosAssetPath(uploaded.backendPath)
4452
+ : normalizeCosAssetPath(source.voiceUrl);
4453
+ return compactRecord({
4454
+ reqTaskId: trimToNull(kwargs.reqTaskId),
4455
+ voiceName: name,
4456
+ voiceUrl,
4457
+ videoId: source.videoId,
4458
+ });
4459
+ }
4460
+
4461
+ function extractCreatedVoiceRecordId(payload) {
4462
+ if (typeof payload === 'string') return payload;
4463
+ if (!payload || typeof payload !== 'object') return null;
4464
+ return payload.id
4465
+ ?? payload.voiceRecordId
4466
+ ?? payload.reqTaskId
4467
+ ?? payload.voiceTaskId
4468
+ ?? payload.data?.id
4469
+ ?? payload.data?.voiceRecordId
4470
+ ?? payload.data?.reqTaskId
4471
+ ?? null;
4472
+ }
4473
+
4474
+ async function fetchSubjectVoiceByReqTaskId(reqTaskId, options = {}) {
4475
+ if (!reqTaskId) return null;
4476
+ const payload = await awbApi.getVoiceByReqTaskId(reqTaskId).catch((error) => {
4477
+ if (options.optional) return null;
4478
+ throw error;
4479
+ });
4480
+ return payload && typeof payload === 'object' ? normalizeSubjectVoiceRecord(payload) : null;
4481
+ }
4482
+
4483
+ async function waitForSubjectVoiceExternalId(reqTaskId, options = {}) {
4484
+ const waitSeconds = Math.max(0, toInt(options.waitSeconds, 0));
4485
+ const pollIntervalMs = Math.max(500, toInt(options.pollIntervalMs, 2000));
4486
+ const deadline = Date.now() + waitSeconds * 1000;
4487
+ let latest = await fetchSubjectVoiceByReqTaskId(reqTaskId);
4488
+ while (waitSeconds > 0 && !latest?.externalId && !subjectFailureDetails(latest, 'voice') && Date.now() < deadline) {
4489
+ await sleep(pollIntervalMs);
4490
+ latest = await fetchSubjectVoiceByReqTaskId(reqTaskId);
4491
+ }
4492
+ return latest;
4493
+ }
4494
+
4495
+ function subjectVoiceWaitPayload(voiceRecordId, voice) {
4496
+ const externalId = voice?.externalId ?? null;
4497
+ return {
4498
+ voiceRecordId,
4499
+ reqTaskId: voice?.reqTaskId ?? voiceRecordId,
4500
+ voiceId: externalId,
4501
+ externalId,
4502
+ nextVoiceArg: externalId ? `--voice-id ${externalId}` : null,
4503
+ status: voice?.status ?? (externalId ? 'ready' : 'pending_external_id'),
4504
+ taskStatus: voice?.taskStatus ?? null,
4505
+ errorMessage: voice?.errorMessage ?? null,
4506
+ isTerminal: externalId ? true : Boolean(voice?.isTerminal),
4507
+ voice,
4508
+ };
4509
+ }
4510
+
4511
+ export async function subjectVoiceCreate(kwargs = {}) {
4512
+ const name = requireValue(kwargs, 'name');
4513
+ const source = subjectVoiceSource(kwargs);
4514
+ if (toBool(kwargs.dryRun)) {
4515
+ const localFiles = source.file ? [await inspectLocalFile(source.file)] : [];
4516
+ let dryRunSource = source;
4517
+ if (source.file) {
4518
+ dryRunSource = { ...source, voiceUrl: dryRunBackendPath(source.file, TASK_UPLOAD_SCENE.SUBJECT) };
4519
+ } else if (source.shouldUploadRemoteUrl) {
4520
+ dryRunSource = {
4521
+ ...source,
4522
+ voiceUrl: dryRunBackendPath(remoteFileNameFromUrl(source.voiceUrl), TASK_UPLOAD_SCENE.SUBJECT),
4523
+ };
4524
+ }
4525
+ return {
4526
+ dryRun: true,
4527
+ action: 'create subject-voice',
4528
+ name,
4529
+ request: buildSubjectVoiceCreateBody(kwargs, dryRunSource),
4530
+ localFiles,
4531
+ remoteUpload: source.shouldUploadRemoteUrl || undefined,
4532
+ remoteUrl: source.shouldUploadRemoteUrl ? source.voiceUrl : undefined,
4533
+ nextVoiceArg: '--voice-id <externalId>',
4534
+ };
4535
+ }
4536
+ ensureConfirmed(kwargs, '创建主体音色是云端写入动作,需要确认', { action: 'create subject-voice', name });
4537
+ let uploaded = null;
4538
+ let tempDownload = null;
4539
+ try {
4540
+ if (source.file) {
4541
+ uploaded = await uploadLocalFile(source.file, { sceneType: TASK_UPLOAD_SCENE.SUBJECT });
4542
+ } else if (source.shouldUploadRemoteUrl) {
4543
+ tempDownload = await downloadRemoteFileToTemp(source.voiceUrl, { fallbackName: safeFileName(name) || 'voice-audio' });
4544
+ uploaded = await uploadLocalFile(tempDownload.filePath, { sceneType: TASK_UPLOAD_SCENE.SUBJECT });
4545
+ }
4546
+ } finally {
4547
+ if (tempDownload?.dir) await fs.rm(tempDownload.dir, { recursive: true, force: true }).catch(() => {});
4548
+ }
4549
+ const body = buildSubjectVoiceCreateBody(kwargs, source, uploaded);
4550
+ const payload = await awbApi.createVoice(body);
4551
+ const voiceRecordId = extractCreatedVoiceRecordId(payload);
4552
+ if (!voiceRecordId) throw new LingjingAwbCliError('音色创建完成但未拿到 voiceRecordId', { type: 'api_error', exitCode: 1, details: payload });
4553
+ const voice = await fetchSubjectVoiceByReqTaskId(voiceRecordId, { optional: true });
4554
+ const waitPayload = subjectVoiceWaitPayload(voiceRecordId, voice);
4555
+ return {
4556
+ created: true,
4557
+ name,
4558
+ voiceRecordId,
4559
+ reqTaskId: waitPayload.reqTaskId,
4560
+ voiceId: waitPayload.voiceId,
4561
+ externalId: waitPayload.externalId,
4562
+ nextVoiceArg: waitPayload.nextVoiceArg,
4563
+ status: waitPayload.status,
4564
+ request: body,
4565
+ ...(uploaded ? { upload: uploaded } : {}),
4566
+ voice,
4567
+ };
4568
+ }
4569
+
4570
+ function requireSubjectVoiceRecordId(kwargs = {}) {
4571
+ const value = trimToNull(kwargs.voiceRecordId ?? kwargs.reqTaskId);
4572
+ if (!value) throw argumentError('缺少参数:--voice-record-id', '传 create subject-voice 返回的 voiceRecordId;也可用 --req-task-id。');
4573
+ return value;
4574
+ }
4575
+
4576
+ export async function subjectVoiceWait(kwargs = {}) {
4577
+ const voiceRecordId = requireSubjectVoiceRecordId(kwargs);
4578
+ const voice = await waitForSubjectVoiceExternalId(voiceRecordId, kwargs);
4579
+ const payload = subjectVoiceWaitPayload(voiceRecordId, voice);
4580
+ const failure = subjectFailureDetails(voice, 'voice');
4581
+ if (failure) {
4582
+ throw new LingjingAwbCliError(failure.errorMessage, {
4583
+ type: 'subject_voice_failed',
4584
+ exitCode: 1,
4585
+ hint: '主体音色创建任务已失败,请根据 error.details.errorMessage 调整音频/视频来源后重新创建。',
4586
+ details: payload,
4587
+ });
4588
+ }
4589
+ if (!payload.externalId) {
4590
+ throw new LingjingAwbCliError('主体音色 externalId 尚未回填', {
4591
+ type: 'subject_voice_still_pending',
4592
+ exitCode: 20,
4593
+ hint: '稍后重试 create subject-voice-wait,或用 create subject-voice-list --name 查询。',
4594
+ details: payload,
4595
+ });
4596
+ }
4597
+ return payload;
4598
+ }
4599
+
4600
+ const SUBJECT_SLOT_ALIASES = {
4601
+ primary: 'primary',
4602
+ 'three-view': 'three-view',
4603
+ three_view: 'three-view',
4604
+ threeview: 'three-view',
4605
+ face: 'face',
4606
+ side: 'side',
4607
+ back: 'back',
4608
+ };
4609
+
4610
+ const SUBJECT_SLOT_META = {
4611
+ primary: { idField: 'subjectId' },
4612
+ 'three-view': { idField: 'subjectId' },
4613
+ face: { idField: 'faceViewId' },
4614
+ side: { idField: 'sideViewId' },
4615
+ back: { idField: 'backViewId' },
4616
+ };
4617
+
4618
+ function parseSubjectResourceItem(raw, index) {
4619
+ const text = String(raw ?? '').trim();
4620
+ if (!text) {
4621
+ throw argumentError(`resource[${index}] 为空`, '格式:--resource <slot>:<file|url>,slot ∈ primary | three-view | face | side | back。');
4622
+ }
4623
+ const colonIndex = text.indexOf(':');
4624
+ if (colonIndex <= 0) {
4625
+ throw argumentError(
4626
+ `resource[${index}] 缺少 slot`,
4627
+ '格式:--resource <slot>:<file|url>,例如 --resource primary:./three-view.png。',
4628
+ );
4629
+ }
4630
+ const slotRaw = text.slice(0, colonIndex).trim().toLowerCase();
4631
+ const slot = SUBJECT_SLOT_ALIASES[slotRaw];
4632
+ if (!slot) {
4633
+ throw argumentError(`resource[${index}] slot 不支持:${slotRaw}`, 'slot ∈ primary | three-view | face | side | back。');
4634
+ }
4635
+ const value = text.slice(colonIndex + 1).trim();
4636
+ if (!value) {
4637
+ throw argumentError(`resource[${index}] value 不能为空`);
4638
+ }
4639
+ return { slot, value };
4640
+ }
4641
+
3545
4642
  function subjectAssetSpecs(kwargs = {}) {
3546
- return [
3547
- { label: 'primary', idField: 'subjectId', file: kwargs.primaryFile ?? kwargs.threeViewFile, url: kwargs.primaryUrl ?? kwargs.threeViewUrl, isPrimary: true },
3548
- { label: 'face', idField: 'faceViewId', file: kwargs.faceFile, url: kwargs.faceUrl },
3549
- { label: 'side', idField: 'sideViewId', file: kwargs.sideFile, url: kwargs.sideUrl },
3550
- { label: 'back', idField: 'backViewId', file: kwargs.backFile, url: kwargs.backUrl },
3551
- ].filter((item) => trimToNull(item.file) || trimToNull(item.url));
4643
+ const bySlot = new Map();
4644
+ const items = parseListArg(kwargs.resource);
4645
+ for (const [index, raw] of items.entries()) {
4646
+ const { slot, value } = parseSubjectResourceItem(raw, index);
4647
+ if (bySlot.has(slot)) {
4648
+ throw argumentError(`resource[${index}] slot 重复:${slot}`, '每个 slot 只能传一次。');
4649
+ }
4650
+ const isUrl = isRemoteOrBackendPath(value);
4651
+ bySlot.set(slot, { label: slot, idField: SUBJECT_SLOT_META[slot].idField, file: isUrl ? null : value, url: isUrl ? value : null });
4652
+ }
4653
+ const primary = bySlot.get('primary') ?? bySlot.get('three-view');
4654
+ if (!primary) return [];
4655
+ const ordered = [{ ...primary, label: 'primary', isPrimary: true }];
4656
+ for (const slot of ['face', 'side', 'back']) {
4657
+ const item = bySlot.get(slot);
4658
+ if (item) ordered.push(item);
4659
+ }
4660
+ return ordered;
3552
4661
  }
3553
4662
 
3554
4663
  function subjectAssetPathForDryRun(item) {
@@ -3565,15 +4674,37 @@ function tagListFromArg(value) {
3565
4674
  .filter((item) => item.tagId);
3566
4675
  }
3567
4676
 
3568
- function buildSubjectCreateBody(kwargs, specs, assets) {
4677
+ const SUBJECT_MODEL_CODE_HINT = '传 --model-code tx|vidu;KeLing / 可灵主体明确传 tx,Vidu 主体明确传 vidu。';
4678
+
4679
+ function resolveSubjectCreateModelCode(kwargs = {}) {
4680
+ const explicitModelCode = trimToNull(kwargs.modelCode ?? kwargs.model_code);
4681
+ if (explicitModelCode === 'tx' || explicitModelCode === 'vidu') {
4682
+ return { modelCode: explicitModelCode };
4683
+ }
4684
+ if (explicitModelCode) {
4685
+ throw argumentError(
4686
+ `主体 modelCode 不支持:${explicitModelCode}`,
4687
+ SUBJECT_MODEL_CODE_HINT,
4688
+ );
4689
+ }
4690
+
4691
+ throw argumentError(
4692
+ '缺少主体 modelCode',
4693
+ SUBJECT_MODEL_CODE_HINT,
4694
+ );
4695
+ }
4696
+
4697
+ function buildSubjectCreateBody(kwargs, specs, assets, modelCodeResolution = resolveSubjectCreateModelCode(kwargs)) {
3569
4698
  const name = requireValue(kwargs, 'name');
4699
+ const description = trimToNull(kwargs.description ?? kwargs.elementDescription) ?? name;
3570
4700
  const primary = assets.find((item) => item.isPrimary);
3571
4701
  const referAssets = assets.filter((item) => item.assetPath);
4702
+ const { modelCode } = modelCodeResolution;
3572
4703
  return compactRecord({
3573
4704
  reqTaskId: trimToNull(kwargs.reqTaskId),
3574
- modelCode: trimToNull(kwargs.modelCode),
4705
+ modelCode,
3575
4706
  elementName: name,
3576
- elementDescription: trimToNull(kwargs.description ?? kwargs.elementDescription),
4707
+ elementDescription: description,
3577
4708
  elementFrontalImage: primary?.assetPath ?? null,
3578
4709
  elementReferList: referAssets.map((item) => ({
3579
4710
  imageUrl: item.assetPath,
@@ -3591,9 +4722,12 @@ function extractCreatedElementId(payload) {
3591
4722
  return payload.id ?? payload.elementId ?? payload.subjectId ?? payload.reqTaskId ?? payload.data?.id ?? payload.data?.elementId ?? null;
3592
4723
  }
3593
4724
 
3594
- async function fetchSubjectByReqTaskId(reqTaskId) {
4725
+ async function fetchSubjectByReqTaskId(reqTaskId, options = {}) {
3595
4726
  if (!reqTaskId) return null;
3596
- const payload = await awbApi.getElementByReqTaskId(reqTaskId).catch(() => null);
4727
+ const payload = await awbApi.getElementByReqTaskId(reqTaskId).catch((error) => {
4728
+ if (options.optional) return null;
4729
+ throw error;
4730
+ });
3597
4731
  return payload && typeof payload === 'object' ? normalizeSubjectRecord(payload) : null;
3598
4732
  }
3599
4733
 
@@ -3602,7 +4736,7 @@ async function waitForSubjectExternalId(reqTaskId, options = {}) {
3602
4736
  const pollIntervalMs = Math.max(500, toInt(options.pollIntervalMs, 2000));
3603
4737
  const deadline = Date.now() + waitSeconds * 1000;
3604
4738
  let latest = await fetchSubjectByReqTaskId(reqTaskId);
3605
- while (waitSeconds > 0 && !latest?.externalId && Date.now() < deadline) {
4739
+ while (waitSeconds > 0 && !latest?.externalId && !subjectFailureDetails(latest, 'subject') && Date.now() < deadline) {
3606
4740
  await sleep(pollIntervalMs);
3607
4741
  latest = await fetchSubjectByReqTaskId(reqTaskId);
3608
4742
  }
@@ -3616,7 +4750,10 @@ function subjectWaitPayload(elementId, subject) {
3616
4750
  subjectId: externalId ?? elementId,
3617
4751
  externalId,
3618
4752
  nextRefSubject: externalId && subject?.name ? `${subject.name}=${externalId}` : null,
3619
- status: externalId ? 'ready' : 'pending_external_id',
4753
+ status: subject?.status ?? (externalId ? 'ready' : 'pending_external_id'),
4754
+ taskStatus: subject?.taskStatus ?? null,
4755
+ errorMessage: subject?.errorMessage ?? null,
4756
+ isTerminal: externalId ? true : Boolean(subject?.isTerminal),
3620
4757
  subject,
3621
4758
  };
3622
4759
  }
@@ -3625,8 +4762,9 @@ export async function subjectPublish(kwargs = {}) {
3625
4762
  const name = requireValue(kwargs, 'name');
3626
4763
  const specs = subjectAssetSpecs(kwargs);
3627
4764
  if (!specs.some((item) => item.isPrimary)) {
3628
- throw argumentError('缺少主体主参考图', '传 --primary-file、--three-view-file、--primary-url 或 --three-view-url。');
4765
+ throw argumentError('缺少主体主参考图', '传 --resource primary:<path|url>(或 --resource three-view:<path|url> 自动升为主图)。');
3629
4766
  }
4767
+ const modelCodeResolution = resolveSubjectCreateModelCode(kwargs);
3630
4768
  if (toBool(kwargs.dryRun)) {
3631
4769
  const assets = specs.map((item) => ({
3632
4770
  label: item.label,
@@ -3638,15 +4776,15 @@ export async function subjectPublish(kwargs = {}) {
3638
4776
  }));
3639
4777
  return {
3640
4778
  dryRun: true,
3641
- action: 'subject publish',
4779
+ action: 'create subject',
3642
4780
  name,
3643
- request: buildSubjectCreateBody(kwargs, specs, assets),
4781
+ request: buildSubjectCreateBody(kwargs, specs, assets, modelCodeResolution),
3644
4782
  assets,
3645
4783
  localFiles: await inspectLocalFiles(specs.map((item) => item.file).filter(Boolean)),
3646
4784
  nextRefSubject: `${name}=<externalId>`,
3647
4785
  };
3648
4786
  }
3649
- ensureConfirmed(kwargs, '创建平台主体 element 是云端写入动作,需要确认', { action: 'subject publish', name });
4787
+ ensureConfirmed(kwargs, '创建平台主体 element 是云端写入动作,需要确认', { action: 'create subject', name });
3650
4788
  const assets = [];
3651
4789
  for (const spec of specs) {
3652
4790
  const uploaded = spec.file ? await uploadLocalFile(spec.file, { sceneType: TASK_UPLOAD_SCENE.SUBJECT }) : null;
@@ -3660,11 +4798,11 @@ export async function subjectPublish(kwargs = {}) {
3660
4798
  ...(uploaded ? { upload: uploaded } : {}),
3661
4799
  });
3662
4800
  }
3663
- const body = buildSubjectCreateBody(kwargs, specs, assets);
4801
+ const body = buildSubjectCreateBody(kwargs, specs, assets, modelCodeResolution);
3664
4802
  const payload = await awbApi.createElement(body);
3665
4803
  const elementId = extractCreatedElementId(payload);
3666
4804
  if (!elementId) throw new LingjingAwbCliError('主体创建完成但未拿到 elementId', { type: 'api_error', exitCode: 1, details: payload });
3667
- const subject = await fetchSubjectByReqTaskId(elementId);
4805
+ const subject = await fetchSubjectByReqTaskId(elementId, { optional: true });
3668
4806
  const waitPayload = subjectWaitPayload(elementId, subject);
3669
4807
  return {
3670
4808
  created: true,
@@ -3684,11 +4822,20 @@ export async function subjectWait(kwargs = {}) {
3684
4822
  const elementId = requireValue(kwargs, 'elementId', 'element-id');
3685
4823
  const subject = await waitForSubjectExternalId(elementId, kwargs);
3686
4824
  const payload = subjectWaitPayload(elementId, subject);
4825
+ const failure = subjectFailureDetails(subject, 'subject');
4826
+ if (failure) {
4827
+ throw new LingjingAwbCliError(failure.errorMessage, {
4828
+ type: 'subject_failed',
4829
+ exitCode: 1,
4830
+ hint: '主体创建任务已失败,请根据 error.details.errorMessage 调整参考资源/模型后重新创建。',
4831
+ details: payload,
4832
+ });
4833
+ }
3687
4834
  if (!payload.externalId) {
3688
4835
  throw new LingjingAwbCliError('主体 externalId 尚未回填', {
3689
4836
  type: 'subject_still_pending',
3690
4837
  exitCode: 20,
3691
- hint: '稍后重试 subject wait,或用 subject list --name 查询。',
4838
+ hint: '稍后重试 create subject-wait,或用 create subject-list --name 查询。',
3692
4839
  details: payload,
3693
4840
  });
3694
4841
  }
@@ -3704,7 +4851,7 @@ export async function subjectPublishBatch(kwargs = {}) {
3704
4851
  }
3705
4852
  return { dryRun: true, count: items.length, results };
3706
4853
  }
3707
- ensureConfirmed(kwargs, '批量发布主体资产是云端写入动作,需要确认', { action: 'subject publish-batch', count: items.length });
4854
+ ensureConfirmed(kwargs, '批量发布主体资产是云端写入动作,需要确认', { action: 'create subject-batch', count: items.length });
3708
4855
  const results = await runConcurrent(items, kwargs.concurrency ?? 1, async (item, index) => ({
3709
4856
  inputIndex: index,
3710
4857
  status: 'success',
@@ -3714,44 +4861,73 @@ export async function subjectPublishBatch(kwargs = {}) {
3714
4861
  }
3715
4862
 
3716
4863
  export async function subtitleRemove(kwargs = {}) {
3717
- const videoUrl = requireValue(kwargs, 'videoUrl', 'video-url');
4864
+ const built = await buildSubtitleRemovalRequest(kwargs, { dryRun: toBool(kwargs.dryRun) });
3718
4865
  if (toBool(kwargs.dryRun)) {
3719
- return { dryRun: true, action: 'video subtitle-remove', request: { input_type: 'url', video_url: videoUrl } };
3720
- }
3721
- ensureConfirmed(kwargs, '提交视频去字幕任务是云端写入动作,需要确认', { action: 'video subtitle-remove', videoUrl });
3722
- const payload = await awbApi.createSubtitleRemoveTask({
3723
- input_type: 'url',
3724
- video_url: videoUrl,
3725
- ...(kwargs.name ? { name: kwargs.name } : {}),
3726
- ...(kwargs.taskId ? { task_id: kwargs.taskId } : {}),
3727
- ...(kwargs.callbackUrl ? { callback_url: kwargs.callbackUrl } : {}),
4866
+ return {
4867
+ dryRun: true,
4868
+ action: 'create video-subtitle-removal',
4869
+ request: built.request,
4870
+ materialEndpoint: '/api/material/creation/videoSubtitleRemoval',
4871
+ taskType: 'VIDEO_SUBTITLE_REMOVAL',
4872
+ };
4873
+ }
4874
+ ensureConfirmed(kwargs, '提交视频去字幕任务会通过 material 创建任务并消耗积分,需要确认', {
4875
+ action: 'create video-subtitle-removal',
4876
+ sourceTaskId: built.sourceTaskId,
3728
4877
  });
3729
- return {
4878
+ const feePayload = await awbApi.fetchVideoSubtitleRemovalFee(built.request).catch(() => null);
4879
+ const estimate = await pointEstimate(feePayload, built.projectGroupNo).catch(() => ({}));
4880
+ const payload = await awbApi.createVideoSubtitleRemovalTask(built.request);
4881
+ const result = normalizeCreatedTask(payload, {
4882
+ ...estimate,
3730
4883
  submitted: true,
3731
- remoteTaskId: payload?.remote_task_id ?? payload?.remoteTaskId ?? null,
3732
- publicId: payload?.public_id ?? payload?.publicId ?? payload?.id ?? null,
4884
+ taskType: 'VIDEO_SUBTITLE_REMOVAL',
4885
+ sourceTaskId: built.sourceTaskId,
4886
+ projectGroupNo: built.projectGroupNo,
4887
+ });
4888
+ await appendTaskRecord(kwargs, {
4889
+ taskId: result.taskId,
4890
+ taskType: 'VIDEO_SUBTITLE_REMOVAL',
4891
+ projectGroupNo: built.projectGroupNo,
4892
+ promptSummary: `去字幕 sourceTaskId=${built.sourceTaskId}`,
4893
+ });
4894
+ return {
4895
+ ...result,
4896
+ nextCommand: result.taskId
4897
+ ? `lj-awb task video-subtitle-status --task-id ${result.taskId}${built.projectGroupNo ? ` --project-group-no ${built.projectGroupNo}` : ''} -f json`
4898
+ : null,
4899
+ };
4900
+ }
4901
+
4902
+ async function buildSubtitleRemovalRequest(kwargs = {}, options = {}) {
4903
+ const sourceTaskId = trimToNull(kwargs.sourceTaskId);
4904
+ if (!sourceTaskId) {
4905
+ throw argumentError('缺少来源视频任务 ID', '传 --source-task-id <taskId>;必须是 material 中已成功的视频任务。');
4906
+ }
4907
+ const dryRun = Boolean(options.dryRun);
4908
+ const projectGroupNo = await resolveProjectGroupNo(kwargs.projectGroupNo, {
4909
+ allowNull: true,
4910
+ noNetwork: dryRun,
4911
+ noSave: dryRun,
4912
+ }).catch((error) => {
4913
+ if (dryRun) return null;
4914
+ throw error;
4915
+ });
4916
+ return {
4917
+ sourceTaskId,
4918
+ projectGroupNo,
4919
+ request: compactRecord({
4920
+ sourceTaskId,
4921
+ projectGroupNo,
4922
+ }),
3733
4923
  };
3734
4924
  }
3735
4925
 
3736
4926
  export async function subtitleStatus(kwargs = {}) {
3737
- const publicId = trimToNull(kwargs.publicId);
3738
- const remoteTaskId = trimToNull(kwargs.remoteTaskId);
3739
- if (!publicId && !remoteTaskId) throw argumentError('缺少去字幕任务 ID', '传 --public-id 或 --remote-task-id。');
3740
- const payload = publicId
3741
- ? await awbApi.fetchSubtitleTaskByPublicId(publicId)
3742
- : await awbApi.fetchSubtitleTaskByRemoteId(remoteTaskId);
3743
- const resultUrls = uniqueNonEmpty([
3744
- ...parseListArg(payload?.result_url ?? payload?.resultUrl),
3745
- ...parseListArg(payload?.output_url ?? payload?.outputUrl),
3746
- ...parseListArg(payload?.url),
3747
- ]);
3748
- return compactRecord({
3749
- publicId: publicId ?? payload?.public_id ?? payload?.publicId ?? payload?.id ?? null,
3750
- remoteTaskId: remoteTaskId ?? payload?.remote_task_id ?? payload?.remoteTaskId ?? null,
3751
- taskStatus: payload?.status ?? payload?.taskStatus ?? payload?.state ?? null,
3752
- isTerminal: isTerminalTaskStatus(payload?.status ?? payload?.taskStatus ?? payload?.state),
3753
- resultCount: resultUrls.length,
3754
- ...(resultUrls.length ? { resultUrls } : {}),
3755
- errorMessage: payload?.error_message ?? payload?.errorMessage ?? payload?.message ?? null,
4927
+ const taskId = requireValue(kwargs, 'taskId', 'task-id');
4928
+ return taskStatus({
4929
+ ...kwargs,
4930
+ taskId,
4931
+ taskType: 'VIDEO_SUBTITLE_REMOVAL',
3756
4932
  });
3757
4933
  }