@lingjingai/lj-awb-cli 0.4.0 → 0.4.2

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.
@@ -46,6 +46,17 @@ 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']);
49
60
  const REMOTE_VOICE_DOWNLOAD_TIMEOUT_MS = 30_000;
50
61
  const REMOTE_VOICE_DOWNLOAD_MAX_BYTES = 100 * 1024 * 1024;
51
62
  const REMOTE_VOICE_MIME_TYPES = new Set([
@@ -61,6 +72,44 @@ const REMOTE_VOICE_EXTENSIONS = new Set(['.mp3', '.wav', '.m4a', '.aac', '.ogg',
61
72
  const ASSET_PLATFORM_CODES = ['JIMENG', 'BYTEPLUS'];
62
73
  const ASSET_PLATFORM_CODE_SET = new Set(ASSET_PLATFORM_CODES);
63
74
  const ASSET_PLATFORM_HINT = ASSET_PLATFORM_CODES.join('|');
75
+ const PLATFORM_BACKEND_PATH_PREFIXES = [
76
+ 'material/',
77
+ 'material-image-draw/',
78
+ 'material-image-edit/',
79
+ 'material-video-create/',
80
+ 'default/workbench/',
81
+ 'asset-review/',
82
+ ];
83
+ const CREATE_STANDARD_KWARG_KEYS = new Set([
84
+ 'modelGroupCode',
85
+ 'projectGroupNo',
86
+ 'customBizId',
87
+ 'prompt',
88
+ 'ratio',
89
+ 'quality',
90
+ 'generateNum',
91
+ 'generate_num',
92
+ 'duration',
93
+ 'needAudio',
94
+ 'need_audio',
95
+ 'resource',
96
+ 'resources',
97
+ 'resourcesJson',
98
+ 'resources_json',
99
+ 'modelParam',
100
+ 'model_param',
101
+ 'modelParams',
102
+ 'model_params',
103
+ 'modelParamsJson',
104
+ 'model_params_json',
105
+ 'taskRecordFile',
106
+ 'waitSeconds',
107
+ 'pollIntervalMs',
108
+ 'inputFile',
109
+ 'concurrency',
110
+ 'dryRun',
111
+ 'yes',
112
+ ]);
64
113
 
65
114
  export function normalizeUserInfo(payload) {
66
115
  const data = payload && typeof payload === 'object' ? payload : {};
@@ -1047,6 +1096,8 @@ function sourceAllowedByRule(rule = {}, sourceKind) {
1047
1096
  function resourceFormatForValidation(detail = {}) {
1048
1097
  if (detail.localFile?.format) return String(detail.localFile.format).toLowerCase();
1049
1098
  const value = detail.resource?.source?.value;
1099
+ const transformedFormat = imageTransformFormat(value);
1100
+ if (transformedFormat) return transformedFormat;
1050
1101
  const pathname = (() => {
1051
1102
  try {
1052
1103
  return new URL(String(value)).pathname;
@@ -1058,6 +1109,34 @@ function resourceFormatForValidation(detail = {}) {
1058
1109
  return ext || null;
1059
1110
  }
1060
1111
 
1112
+ function imageTransformFormat(value) {
1113
+ const text = String(value || '');
1114
+ if (!text.includes('?') && !text.includes('%2F') && !text.includes('/format/')) return null;
1115
+ const queryText = (() => {
1116
+ try {
1117
+ const url = new URL(text);
1118
+ return url.search || text;
1119
+ } catch {
1120
+ const queryIndex = text.indexOf('?');
1121
+ return queryIndex >= 0 ? text.slice(queryIndex) : text;
1122
+ }
1123
+ })();
1124
+ let decoded = queryText;
1125
+ try {
1126
+ decoded = decodeURIComponent(queryText);
1127
+ } catch {}
1128
+ for (const pattern of [
1129
+ /image(?:mogr2|view2)[^&#?]*?\/format\/([A-Za-z0-9]+)/i,
1130
+ /x-oss-process=image[^&#?]*?format,([A-Za-z0-9]+)/i,
1131
+ /(?:^|[?&#])format=([A-Za-z0-9]+)/i,
1132
+ ]) {
1133
+ const match = decoded.match(pattern);
1134
+ const format = normalizeFileFormat(match?.[1]);
1135
+ if (format) return format;
1136
+ }
1137
+ return null;
1138
+ }
1139
+
1061
1140
  function normalizeFileFormat(value) {
1062
1141
  const format = trimToNull(value)?.toLowerCase();
1063
1142
  if (!format) return null;
@@ -1122,6 +1201,15 @@ function isConvertibleLocalImage(detail = {}) {
1122
1201
  return Boolean(detail.localFile?.exists && String(detail.localFile?.mimeType || '').startsWith('image/'));
1123
1202
  }
1124
1203
 
1204
+ function isDownloadableImageSource(detail = {}) {
1205
+ const sourceKind = resourceSourceKindForValidation(detail);
1206
+ return detail.resource?.source?.kind === 'url' && ['http_url', 'backendPath'].includes(sourceKind);
1207
+ }
1208
+
1209
+ function isConvertibleImageResource(detail = {}) {
1210
+ return isConvertibleLocalImage(detail) || isDownloadableImageSource(detail);
1211
+ }
1212
+
1125
1213
  function resourceFormatConversion(rule = {}, detail = {}) {
1126
1214
  if (!isImageRule(rule)) return null;
1127
1215
  const format = normalizeFileFormat(resourceFormatForValidation(detail));
@@ -1133,7 +1221,7 @@ function resourceFormatConversion(rule = {}, detail = {}) {
1133
1221
  fromFormat: format,
1134
1222
  toFormat: policy.autoConvertTo,
1135
1223
  reason: 'image_webp_not_supported',
1136
- possible: isConvertibleLocalImage(detail),
1224
+ possible: isConvertibleImageResource(detail),
1137
1225
  };
1138
1226
  }
1139
1227
  if (policy.kind === 'normal_plus_webp') return null;
@@ -1142,7 +1230,7 @@ function resourceFormatConversion(rule = {}, detail = {}) {
1142
1230
  fromFormat: format,
1143
1231
  toFormat: policy.autoConvertTo,
1144
1232
  reason: 'image_strict_format_mismatch',
1145
- possible: isConvertibleLocalImage(detail),
1233
+ possible: isConvertibleImageResource(detail),
1146
1234
  allowed: policy.allowed,
1147
1235
  };
1148
1236
  }
@@ -1182,7 +1270,7 @@ function assertResourceShapeAgainstModel(resourceDetails = [], resourceRules = [
1182
1270
  if (conversion && !conversion.possible) {
1183
1271
  throw argumentError(
1184
1272
  `素材格式需要转换但无法自动处理:${resourceText(resource)}`,
1185
- `当前格式 ${conversion.fromFormat},目标格式 ${conversion.toFormat};请使用本地文件,或先转换后再传远程 URL / asset。`,
1273
+ `当前格式 ${conversion.fromFormat},目标格式 ${conversion.toFormat};请使用本地文件、http(s) URL 或平台 backendPath,asset 资源需先转换后再传。`,
1186
1274
  );
1187
1275
  }
1188
1276
  if (!conversion && !fileTypeAllowedByRule(rule, format)) {
@@ -1309,12 +1397,16 @@ function promptParamValue(promptParams = {}, key) {
1309
1397
  }
1310
1398
 
1311
1399
  function providedPromptParamKeys(promptParams = {}) {
1312
- const keys = [];
1400
+ const keys = new Set();
1313
1401
  for (const key of ['prompt', 'ratio', 'quality', 'duration', 'generateNum', 'needAudio']) {
1314
1402
  const value = promptParamValue(promptParams, key);
1315
- if (value !== undefined && value !== null && value !== '') keys.push(key);
1403
+ if (value !== undefined && value !== null && value !== '') keys.add(key);
1316
1404
  }
1317
- return keys;
1405
+ for (const [key, value] of Object.entries(promptParams || {})) {
1406
+ if (key === 'resources' || key === 'generate_num' || key === 'need_audio') continue;
1407
+ if (value !== undefined && value !== null && value !== '') keys.add(key);
1408
+ }
1409
+ return [...keys];
1318
1410
  }
1319
1411
 
1320
1412
  function inferGeneratedMode(resources = []) {
@@ -1512,7 +1604,7 @@ function mergeResourceLimits(base = {}, overrides = {}) {
1512
1604
  function mergeModelParamRules(options = [], rawModel = null) {
1513
1605
  const rawParams = Array.isArray(rawModel?.modelParams) ? rawModel.modelParams : [];
1514
1606
  const rawByKey = new Map(rawParams.map((item) => [item?.paramKey, item]).filter(([key]) => key));
1515
- return options.map((option) => {
1607
+ const merged = options.map((option) => {
1516
1608
  const raw = rawByKey.get(option.paramKey);
1517
1609
  return {
1518
1610
  ...option,
@@ -1520,6 +1612,62 @@ function mergeModelParamRules(options = [], rawModel = null) {
1520
1612
  rules: option.rules ?? raw?.rules ?? null,
1521
1613
  };
1522
1614
  });
1615
+ const mergedKeys = new Set(merged.map((item) => item.paramKey).filter(Boolean));
1616
+ for (const raw of rawParams) {
1617
+ if (!raw?.paramKey || mergedKeys.has(raw.paramKey)) continue;
1618
+ merged.push(raw);
1619
+ }
1620
+ return merged;
1621
+ }
1622
+
1623
+ function modelParamDefaultValue(option = {}) {
1624
+ return option.rules?.defaultValue
1625
+ ?? option.defaultValue
1626
+ ?? null;
1627
+ }
1628
+
1629
+ function modelParamDefaultName(option = {}) {
1630
+ return option.rules?.defaultName
1631
+ ?? option.defaultName
1632
+ ?? null;
1633
+ }
1634
+
1635
+ function modelParamValueSource(option = {}) {
1636
+ const allowedValues = optionAllowedValues(option);
1637
+ if (allowedValues.length) return '只能从 allowedValues 选择。';
1638
+ if (modelParamDefaultValue(option) != null) return '模型配置提供 defaultValue;这是候选默认值,不代表可以静默代选。';
1639
+ return '来自实时 model options 的通用模型配置参数;用户明确选择后通过 --model-param key=value 或 --model-params-json 传入。';
1640
+ }
1641
+
1642
+ function isGenericModelConfigParam(option = {}) {
1643
+ const key = trimToNull(option.paramKey);
1644
+ if (!key) return false;
1645
+ const internalResourceKeys = new Set([
1646
+ 'generated_mode',
1647
+ 'resources',
1648
+ 'iref',
1649
+ 'cref',
1650
+ 'sref',
1651
+ 'frames',
1652
+ 'multi_param',
1653
+ 'multi_prompt',
1654
+ 'subject',
1655
+ 'subject_reference',
1656
+ 'reference_image',
1657
+ 'reference_audio',
1658
+ 'reference_video',
1659
+ 'first_frame',
1660
+ 'first_last_frame',
1661
+ 'last_frame_only',
1662
+ 'storyboard',
1663
+ ]);
1664
+ if (internalResourceKeys.has(key)) return false;
1665
+ const paramType = String(option.paramType || '');
1666
+ return Boolean(
1667
+ optionAllowedValues(option).length
1668
+ || modelParamDefaultValue(option) != null
1669
+ || /Enum|Boolean|Bool|Number|Integer|Float|Double|String|Text|Prompt/i.test(paramType),
1670
+ );
1523
1671
  }
1524
1672
 
1525
1673
  function createParamForModelOption(option = {}, taskKind = 'image') {
@@ -1596,7 +1744,7 @@ function createParamForModelOption(option = {}, taskKind = 'image') {
1596
1744
  requestPath: 'promptParams.resources[]',
1597
1745
  materialLegacyKey: 'iref',
1598
1746
  meaning: '图片任务的参考图输入。',
1599
- valueSource: '本地文件、http(s) URL 或 material backendPath。',
1747
+ valueSource: '本地文件、http(s) URL 或平台 backendPath。',
1600
1748
  resourceSyntax: ['image:reference=./ref.png'],
1601
1749
  },
1602
1750
  resources: {
@@ -1605,7 +1753,7 @@ function createParamForModelOption(option = {}, taskKind = 'image') {
1605
1753
  requestPath: 'promptParams.resources[]',
1606
1754
  materialLegacyKey: 'resources',
1607
1755
  meaning: '模型声明的素材输入;CLI 统一用 resources 表达。',
1608
- valueSource: '本地文件、http(s) URL 或 material backendPath。',
1756
+ valueSource: '本地文件、http(s) URL 或平台 backendPath。',
1609
1757
  resourceSyntax: taskKind === 'image' ? ['image:reference=./ref.png'] : ['image:first_frame=./first.png'],
1610
1758
  },
1611
1759
  frames: {
@@ -1614,7 +1762,7 @@ function createParamForModelOption(option = {}, taskKind = 'image') {
1614
1762
  requestPath: 'promptParams.resources[]',
1615
1763
  materialLegacyKey: 'frames',
1616
1764
  meaning: '视频首帧 / 尾帧 / 关键帧输入。',
1617
- valueSource: '首帧/尾帧可用本地文件、http(s) URL、material backendPath 或 asset:<assetId>;keyframe 仅用文件/URL/backendPath。',
1765
+ valueSource: '首帧/尾帧可用本地文件、http(s) URL、平台 backendPath 或 asset:<assetId>;keyframe 仅用文件/URL/backendPath。',
1618
1766
  resourceSyntax: ['image:first_frame=./first.png', 'image:first_frame=asset:<assetId>', 'image:last_frame=asset:<assetId>', 'image:keyframe#1=./key1.png'],
1619
1767
  },
1620
1768
  multi_param: {
@@ -1655,15 +1803,26 @@ function createParamForModelOption(option = {}, taskKind = 'image') {
1655
1803
  },
1656
1804
  };
1657
1805
  return {
1658
- ...(definitions[key] ?? {
1659
- key,
1660
- cliArg: null,
1661
- requestPath: null,
1662
- materialLegacyKey: key,
1663
- meaning: '模型配置存在该参数,但当前 CLI 没有暴露为稳定创建参数;不要为了调用而硬塞旧字段。',
1664
- valueSource: '如确实需要,先扩展 CLI 显式参数和 Material adapter。',
1665
- notExposedByCli: true,
1666
- }),
1806
+ ...(definitions[key]
1807
+ ?? (isGenericModelConfigParam(option)
1808
+ ? {
1809
+ key,
1810
+ cliArg: '--model-param / --model-params-json',
1811
+ requestPath: `promptParams.${key}`,
1812
+ materialLegacyKey: key,
1813
+ meaning: option.paramName ? `模型配置参数:${option.paramName}` : '模型配置参数。',
1814
+ valueSource: modelParamValueSource(option),
1815
+ genericModelParam: true,
1816
+ }
1817
+ : {
1818
+ key,
1819
+ cliArg: null,
1820
+ requestPath: null,
1821
+ materialLegacyKey: key,
1822
+ meaning: '模型配置存在该参数,但当前 CLI 未将其识别为可安全透传的创建参数。',
1823
+ valueSource: '如确实需要,先确认该字段不是资源或旧 handler 内部字段,再扩展通用参数判定。',
1824
+ notExposedByCli: true,
1825
+ })),
1667
1826
  ...common,
1668
1827
  };
1669
1828
  }
@@ -2032,6 +2191,7 @@ function createSpecParameterControls(createParams, inputModes = []) {
2032
2191
  valueSource: item.valueSource,
2033
2192
  controlKind: item.controlKind,
2034
2193
  allowedValues: item.allowedValues,
2194
+ genericModelParam: item.genericModelParam,
2035
2195
  }));
2036
2196
  const resourceParams = createParams
2037
2197
  .filter((item) => item.key === 'resources')
@@ -2153,7 +2313,8 @@ function cliValueType(option = {}, allowedValues = []) {
2153
2313
  if (allowedValues.length) return 'enum';
2154
2314
  if (option.paramType === 'Prompt') return 'text';
2155
2315
  if (option.paramType === 'BooleanType') return 'boolean';
2156
- if (/Number|Integer|Float/i.test(String(option.paramType || ''))) return 'number';
2316
+ if (/Enum/i.test(String(option.paramType || ''))) return 'enum';
2317
+ if (/Number|Integer|Float|Double/i.test(String(option.paramType || ''))) return 'number';
2157
2318
  return option.paramType || undefined;
2158
2319
  }
2159
2320
 
@@ -2163,6 +2324,7 @@ function modelOptionParams(options = [], taskKind = 'image') {
2163
2324
  .filter(({ createParam }) => createParam.cliArg && createParam.key !== 'resources' && !createParam.internalOnly)
2164
2325
  .map(({ option, createParam }) => {
2165
2326
  const rules = option.rules || {};
2327
+ const defaultValue = modelParamDefaultValue(option);
2166
2328
  const allowedValues = optionAllowedValues(option);
2167
2329
  const required = option.required === true || rules.required === true ? true : undefined;
2168
2330
  const maxLength = option.paramType === 'Prompt'
@@ -2173,10 +2335,15 @@ function modelOptionParams(options = [], taskKind = 'image') {
2173
2335
  label: option.paramName,
2174
2336
  valueType: cliValueType(option, allowedValues),
2175
2337
  values: allowedValues.length ? allowedValues : undefined,
2176
- defaultValue: rules.defaultValue,
2177
- defaultName: rules.defaultName,
2338
+ defaultValue,
2339
+ defaultName: modelParamDefaultName(option),
2178
2340
  maxLength,
2179
2341
  required,
2342
+ cliArg: createParam.cliArg,
2343
+ genericModelParam: createParam.genericModelParam || undefined,
2344
+ modelParamKey: createParam.modelParamKey,
2345
+ modelParamName: createParam.modelParamName,
2346
+ modelParamType: createParam.modelParamType,
2180
2347
  });
2181
2348
  });
2182
2349
  }
@@ -2274,7 +2441,7 @@ export function modelInputGuide() {
2274
2441
  { field: 'resources[].type', values: ['image', 'video', 'audio', 'subject'], description: '资源本体类型;subject 表示已创建的主体对象。' },
2275
2442
  { field: 'resources[].usage', values: ['first_frame', 'last_frame', 'reference', 'keyframe'], description: '素材用途。' },
2276
2443
  { field: 'resources[].reference_key', values: ['custom string'], description: '仅视频 reference 资源需要占位绑定时使用;图片生图 image:reference 不使用 reference_key。subject reference 必须传。' },
2277
- { 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 枚举。' },
2444
+ { field: 'resources[].source.kind', values: ['url', 'asset_id'], description: '只接受 url、asset_id 两个枚举值。本地文件、http(s) URL、平台 backendPath 一律传 kind=url,CLI 按 value 自动识别;asset_id 表示平台资产或主体对象 ID。注意:模型 resources[].valueShapes 列出的 local_file / http_url / backendPath 是 value 形状分类,不是 kind 枚举。' },
2278
2445
  { field: 'resources[].source.value', description: '资源值,必填。url 传素材地址;asset_id 传资源 ID。' },
2279
2446
  { field: 'resources[].order', description: '仅 usage=keyframe 时需要,且同一请求内不能重复。' },
2280
2447
  { field: 'resources[].duration', description: '仅 keyframe 场景下用于表达该帧持续时长,可传小数秒。' },
@@ -2341,6 +2508,7 @@ export async function modelCreateSpec(kwargs = {}) {
2341
2508
  inputRequirement,
2342
2509
  supportedIntents,
2343
2510
  validationRules: createSpecValidationRules(context.taskKind),
2511
+ parameterControls: createSpecParameterControls(context.createParams, context.inputModes),
2344
2512
  agentGuidance: createSpecAgentGuidance(context.taskKind, inputRequirement),
2345
2513
  preflight: createSpecPreflight(context.taskKind),
2346
2514
  examples: createSpecExamples(context.taskKind, supportedIntents),
@@ -2494,14 +2662,26 @@ function isHttpUrl(value) {
2494
2662
  return /^https?:\/\//i.test(String(value || '').trim());
2495
2663
  }
2496
2664
 
2665
+ function backendObjectName(value) {
2666
+ const text = trimToNull(value);
2667
+ if (!text) return null;
2668
+ return text.replace(/^\/+/, '');
2669
+ }
2670
+
2671
+ function isPlatformBackendPath(value) {
2672
+ const objectName = backendObjectName(value);
2673
+ if (!objectName || /^[a-z][a-z0-9+.-]*:\/\//i.test(objectName)) return false;
2674
+ return PLATFORM_BACKEND_PATH_PREFIXES.some((prefix) => objectName.startsWith(prefix));
2675
+ }
2676
+
2497
2677
  function isUploadedMaterialReference(value) {
2498
2678
  const text = trimToNull(value);
2499
2679
  if (!text) return false;
2500
- if (text.startsWith('material/') || text.startsWith('/material/')) return true;
2680
+ if (isPlatformBackendPath(text)) return true;
2501
2681
  if (!isHttpUrl(text)) return false;
2502
2682
  try {
2503
2683
  const url = new URL(text);
2504
- return url.hostname.endsWith('.myqcloud.com');
2684
+ return url.hostname.endsWith('.myqcloud.com') && isPlatformBackendPath(decodeURIComponent(url.pathname));
2505
2685
  } catch {
2506
2686
  return false;
2507
2687
  }
@@ -2518,6 +2698,11 @@ function remoteFileNameFromUrl(remoteUrl, fallback = 'voice-audio') {
2518
2698
 
2519
2699
  function extensionFromContentType(contentType = '') {
2520
2700
  const normalized = String(contentType || '').split(';')[0].trim().toLowerCase();
2701
+ if (normalized === 'image/bmp') return '.bmp';
2702
+ if (normalized === 'image/gif') return '.gif';
2703
+ if (normalized === 'image/jpeg' || normalized === 'image/jpg') return '.jpg';
2704
+ if (normalized === 'image/png') return '.png';
2705
+ if (normalized === 'image/webp') return '.webp';
2521
2706
  if (normalized === 'audio/mpeg') return '.mp3';
2522
2707
  if (normalized === 'audio/wav' || normalized === 'audio/x-wav') return '.wav';
2523
2708
  if (normalized === 'audio/mp4') return '.m4a';
@@ -2535,6 +2720,150 @@ function isSupportedRemoteVoiceDownload(contentType = '', fileName = '') {
2535
2720
  return false;
2536
2721
  }
2537
2722
 
2723
+ function remoteImageFileNameFromValue(value, fallback = 'resource-image') {
2724
+ const text = trimToNull(value);
2725
+ if (text) {
2726
+ try {
2727
+ const pathname = decodeURIComponent(new URL(text).pathname);
2728
+ const baseName = safeFileName(path.basename(pathname));
2729
+ if (baseName && baseName !== '.' && baseName !== '/') return baseName;
2730
+ } catch {
2731
+ const baseName = safeFileName(path.basename(text.split('?')[0].split('#')[0]));
2732
+ if (baseName && baseName !== '.' && baseName !== '/') return baseName;
2733
+ }
2734
+ }
2735
+ return fallback;
2736
+ }
2737
+
2738
+ function extensionForImageFormat(format) {
2739
+ const normalized = normalizeFileFormat(format);
2740
+ if (!normalized) return '';
2741
+ return normalized === 'jpg' ? '.jpg' : `.${normalized}`;
2742
+ }
2743
+
2744
+ function forceFileExtension(fileName, extension) {
2745
+ const safeName = safeFileName(fileName || 'resource-image');
2746
+ if (!extension) return safeName;
2747
+ return `${path.basename(safeName, path.extname(safeName))}${extension}`;
2748
+ }
2749
+
2750
+ function isSupportedRemoteImageDownload(contentType = '', fileName = '', expectedFormat = null) {
2751
+ const normalized = String(contentType || '').split(';')[0].trim().toLowerCase();
2752
+ const extension = path.extname(fileName).toLowerCase();
2753
+ if (REMOTE_IMAGE_MIME_TYPES.has(normalized)) return true;
2754
+ if ((!normalized || normalized === 'application/octet-stream') && REMOTE_IMAGE_EXTENSIONS.has(extension)) return true;
2755
+ if ((!normalized || normalized === 'application/octet-stream') && expectedFormat && COMMON_IMAGE_FORMATS.has(normalizeFileFormat(expectedFormat))) return true;
2756
+ return false;
2757
+ }
2758
+
2759
+ function firstHttpUrl(value, depth = 0) {
2760
+ if (depth > 4 || value == null) return null;
2761
+ if (typeof value === 'string') return /^https?:\/\//i.test(value) ? value : null;
2762
+ if (Array.isArray(value)) {
2763
+ for (const item of value) {
2764
+ const found = firstHttpUrl(item, depth + 1);
2765
+ if (found) return found;
2766
+ }
2767
+ return null;
2768
+ }
2769
+ if (typeof value !== 'object') return null;
2770
+ for (const key of ['url', 'signedUrl', 'signUrl', 'downloadUrl', 'cosUrl', 'previewUrl', 'data']) {
2771
+ const found = firstHttpUrl(value[key], depth + 1);
2772
+ if (found) return found;
2773
+ }
2774
+ for (const nested of Object.values(value)) {
2775
+ const found = firstHttpUrl(nested, depth + 1);
2776
+ if (found) return found;
2777
+ }
2778
+ return null;
2779
+ }
2780
+
2781
+ async function resolveRemoteResourceDownloadUrl(value) {
2782
+ const text = trimToNull(value);
2783
+ if (!text) throw argumentError('远程图片来源为空');
2784
+ if (/^https?:\/\//i.test(text)) return text;
2785
+ if (isPlatformBackendPath(text)) {
2786
+ const objectName = backendObjectName(text);
2787
+ const signed = await awbApi.fetchObjectSignUrl(objectName);
2788
+ const signedUrl = firstHttpUrl(signed);
2789
+ if (signedUrl) return signedUrl;
2790
+ throw new LingjingAwbCliError('获取素材签名 URL 失败', {
2791
+ type: 'api_error',
2792
+ exitCode: 30,
2793
+ details: { objectName, payload: signed },
2794
+ });
2795
+ }
2796
+ throw argumentError(
2797
+ `远程图片来源不支持自动转换:${text}`,
2798
+ '请传 http(s) URL、平台 backendPath,或先下载为本地文件后重试。',
2799
+ );
2800
+ }
2801
+
2802
+ async function downloadRemoteImageFileToTemp(sourceValue, options = {}) {
2803
+ const timeoutMs = Math.max(1_000, toInt(options.timeoutMs, REMOTE_IMAGE_DOWNLOAD_TIMEOUT_MS));
2804
+ const maxBytes = Math.max(1, toInt(options.maxBytes, REMOTE_IMAGE_DOWNLOAD_MAX_BYTES));
2805
+ const remoteUrl = await resolveRemoteResourceDownloadUrl(sourceValue);
2806
+ const controller = new AbortController();
2807
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
2808
+ let dir = null;
2809
+ try {
2810
+ const response = await fetch(remoteUrl, { signal: controller.signal });
2811
+ if (!response.ok) {
2812
+ throw new LingjingAwbCliError(`下载远程图片失败:${response.status} ${response.statusText}`, {
2813
+ type: 'http_error',
2814
+ exitCode: 30,
2815
+ details: { url: sourceValue, status: response.status },
2816
+ });
2817
+ }
2818
+ const contentType = response.headers.get('content-type') || '';
2819
+ const expectedExtension = extensionForImageFormat(options.expectedFormat);
2820
+ let fileName = remoteImageFileNameFromValue(sourceValue, options.fallbackName || 'resource-image');
2821
+ fileName = expectedExtension
2822
+ ? forceFileExtension(fileName, expectedExtension)
2823
+ : (!path.extname(fileName) ? `${fileName}${extensionFromContentType(contentType) || '.img'}` : fileName);
2824
+ if (!isSupportedRemoteImageDownload(contentType, fileName, options.expectedFormat)) {
2825
+ throw argumentError(
2826
+ `远程图片类型不支持:${contentType || path.extname(fileName) || 'unknown'}`,
2827
+ '自动格式转换只支持常见图片输入,请先手动转换为 jpg/png/webp 后重试。',
2828
+ );
2829
+ }
2830
+ const contentLength = toInt(response.headers.get('content-length'), 0);
2831
+ if (contentLength > maxBytes) {
2832
+ throw argumentError(`远程图片过大:${contentLength} bytes`, `最大支持 ${maxBytes} bytes。`);
2833
+ }
2834
+ dir = await fs.mkdtemp(path.join(tmpdir(), 'lj-awb-image-'));
2835
+ const filePath = path.join(dir, fileName);
2836
+ const file = await fs.open(filePath, 'w');
2837
+ let size = 0;
2838
+ try {
2839
+ if (!response.body) throw new Error('empty response body');
2840
+ for await (const chunk of response.body) {
2841
+ const buffer = Buffer.from(chunk);
2842
+ size += buffer.length;
2843
+ if (size > maxBytes) {
2844
+ throw argumentError(`远程图片过大:超过 ${maxBytes} bytes`);
2845
+ }
2846
+ await file.write(buffer);
2847
+ }
2848
+ } finally {
2849
+ await file.close();
2850
+ }
2851
+ return { filePath, dir, contentType, size };
2852
+ } catch (error) {
2853
+ if (dir) await fs.rm(dir, { recursive: true, force: true }).catch(() => {});
2854
+ if (error instanceof LingjingAwbCliError) throw error;
2855
+ const isAbort = error?.name === 'AbortError';
2856
+ throw new LingjingAwbCliError(`下载远程图片失败:${error.message}`, {
2857
+ type: 'network_error',
2858
+ exitCode: 30,
2859
+ hint: isAbort ? `远程下载超过 ${timeoutMs}ms,请改用本地文件或已上传平台 backendPath。` : '',
2860
+ details: { url: sourceValue, causeCode: error?.cause?.code },
2861
+ });
2862
+ } finally {
2863
+ clearTimeout(timeout);
2864
+ }
2865
+ }
2866
+
2538
2867
  async function downloadRemoteFileToTemp(remoteUrl, options = {}) {
2539
2868
  const timeoutMs = Math.max(1_000, toInt(options.timeoutMs, REMOTE_VOICE_DOWNLOAD_TIMEOUT_MS));
2540
2869
  const maxBytes = Math.max(1, toInt(options.maxBytes, REMOTE_VOICE_DOWNLOAD_MAX_BYTES));
@@ -2589,7 +2918,7 @@ async function downloadRemoteFileToTemp(remoteUrl, options = {}) {
2589
2918
  throw new LingjingAwbCliError(`下载远程音频失败:${error.message}`, {
2590
2919
  type: 'network_error',
2591
2920
  exitCode: 30,
2592
- hint: isAbort ? `远程下载超过 ${timeoutMs}ms,请改用本地 --file 或已上传 material 路径。` : '',
2921
+ hint: isAbort ? `远程下载超过 ${timeoutMs}ms,请改用本地 --file 或已上传平台 backendPath。` : '',
2593
2922
  details: { url: remoteUrl, causeCode: error?.cause?.code },
2594
2923
  });
2595
2924
  } finally {
@@ -2635,6 +2964,59 @@ function normalizeUnifiedPromptParams(promptParams) {
2635
2964
  return promptParams;
2636
2965
  }
2637
2966
 
2967
+ async function parseModelParamsJsonArg(value) {
2968
+ const parsed = await readJsonMaybeFile(value, null).catch((error) => {
2969
+ throw argumentError(`model-params-json 解析失败:${error.message}`);
2970
+ });
2971
+ if (parsed == null) return {};
2972
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
2973
+ throw argumentError('model-params-json 必须是 JSON 对象');
2974
+ }
2975
+ return parsed;
2976
+ }
2977
+
2978
+ function parseModelParamAssignments(value) {
2979
+ const params = {};
2980
+ for (const item of parseListArg(value)) {
2981
+ const text = trimToNull(item);
2982
+ if (!text) continue;
2983
+ const eqIndex = text.indexOf('=');
2984
+ if (eqIndex <= 0) {
2985
+ throw argumentError(`model-param 格式错误:${text}`, '格式为 --model-param key=value,可重复传。');
2986
+ }
2987
+ const key = trimToNull(text.slice(0, eqIndex));
2988
+ if (!key) {
2989
+ throw argumentError(`model-param 缺少 key:${text}`);
2990
+ }
2991
+ params[key] = text.slice(eqIndex + 1);
2992
+ }
2993
+ return params;
2994
+ }
2995
+
2996
+ async function collectGenericModelParams(kwargs = {}) {
2997
+ const fromJson = await parseModelParamsJsonArg(kwargs.modelParamsJson ?? kwargs.model_params_json);
2998
+ const fromObject = kwargs.modelParams && typeof kwargs.modelParams === 'object' && !Array.isArray(kwargs.modelParams)
2999
+ ? kwargs.modelParams
3000
+ : {};
3001
+ const fromAssignments = parseModelParamAssignments(kwargs.modelParam);
3002
+ const fromDynamicFlags = {};
3003
+ for (const [key, value] of Object.entries(kwargs || {})) {
3004
+ if (CREATE_STANDARD_KWARG_KEYS.has(key)) continue;
3005
+ if (!key.includes('_') && !isLikelyDynamicModelParamKey(key)) continue;
3006
+ fromDynamicFlags[key] = value;
3007
+ }
3008
+ return normalizeUnifiedPromptParams({
3009
+ ...fromJson,
3010
+ ...fromObject,
3011
+ ...fromDynamicFlags,
3012
+ ...fromAssignments,
3013
+ });
3014
+ }
3015
+
3016
+ function isLikelyDynamicModelParamKey(key) {
3017
+ 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 || ''));
3018
+ }
3019
+
2638
3020
  function normalizeResourceType(type, index) {
2639
3021
  const normalized = String(type ?? '').trim().toLowerCase();
2640
3022
  if (!RESOURCE_TYPES.has(normalized)) {
@@ -2670,7 +3052,7 @@ function normalizeResourceSource(source, type, index, options = {}) {
2670
3052
  if (!['url', 'asset_id'].includes(kind)) {
2671
3053
  throw argumentError(
2672
3054
  `resource[${index}] source.kind 不支持:${explicitKind}`,
2673
- '只支持 url、asset_id 两个值。本地文件 / http(s) URL / material backendPath 都统一传 kind=url(CLI 按 value 自动识别);平台资产或主体对象传 kind=asset_id。',
3055
+ '只支持 url、asset_id 两个值。本地文件 / http(s) URL / 平台 backendPath 都统一传 kind=url(CLI 按 value 自动识别);平台资产或主体对象传 kind=asset_id。',
2674
3056
  );
2675
3057
  }
2676
3058
  const value = kind === 'asset_id' ? assetValue : rawValue;
@@ -2831,22 +3213,33 @@ function isRemoteOrBackendPath(value) {
2831
3213
  if (!text) return false;
2832
3214
  return /^https?:\/\//i.test(text)
2833
3215
  || /^[a-z][a-z0-9+.-]*:\/\//i.test(text)
2834
- || text.startsWith('material/')
2835
- || text.startsWith('/material/');
3216
+ || isPlatformBackendPath(text);
2836
3217
  }
2837
3218
 
2838
- function normalizeMaterialUrlValue(value) {
3219
+ function normalizeBackendPathUrlValue(value) {
2839
3220
  const text = trimToNull(value);
2840
3221
  if (!text) return text;
2841
3222
  if (/^https?:\/\//i.test(text)) {
2842
3223
  try {
2843
3224
  const pathname = decodeURIComponent(new URL(text).pathname);
2844
- if (pathname.startsWith('/material/')) return pathname;
3225
+ if (isPlatformBackendPath(pathname)) return pathname;
2845
3226
  } catch {}
2846
3227
  }
2847
3228
  return text;
2848
3229
  }
2849
3230
 
3231
+ function displayResourceSourceValue(value) {
3232
+ const text = trimToNull(value);
3233
+ if (!text || !/^https?:\/\//i.test(text)) return text;
3234
+ try {
3235
+ const url = new URL(text);
3236
+ const format = imageTransformFormat(text);
3237
+ return `${url.origin}${decodeURIComponent(url.pathname)}${format ? `?format=${format}` : ''}`;
3238
+ } catch {
3239
+ return text.split('?')[0];
3240
+ }
3241
+ }
3242
+
2850
3243
  function conversionOutputExtension(format) {
2851
3244
  const normalized = normalizeFileFormat(format);
2852
3245
  if (normalized === 'jpg') return 'jpg';
@@ -2911,13 +3304,67 @@ async function resolveResourceFileValue(resource, options = {}) {
2911
3304
  }
2912
3305
  const value = resource._source.value;
2913
3306
  if (isRemoteOrBackendPath(value)) {
2914
- return { resource: { ...base, source: { kind: 'url', value: normalizeMaterialUrlValue(value) } }, upload: null, localFile: null };
3307
+ const source = { kind: 'url', value };
3308
+ const conversion = options.resourceRules
3309
+ ? resourceFormatConversion(
3310
+ options.resourceRules.find((item) => resourceRuleMatches(item, { ...base, source })),
3311
+ { resource: { ...base, source } },
3312
+ )
3313
+ : null;
3314
+ if (conversion) {
3315
+ const conversionRecord = compactRecord({
3316
+ resource: resourceText(base),
3317
+ fromFormat: conversion.fromFormat,
3318
+ toFormat: conversion.toFormat,
3319
+ reason: conversion.reason,
3320
+ sourceValue: displayResourceSourceValue(value),
3321
+ dryRun: options.dryRun || undefined,
3322
+ });
3323
+ const convertedName = forceFileExtension(
3324
+ remoteImageFileNameFromValue(value, resourceText(base).replace(/[^0-9A-Za-z._-]+/g, '-')),
3325
+ extensionForImageFormat(conversion.toFormat),
3326
+ );
3327
+ if (options.dryRun) {
3328
+ return {
3329
+ resource: { ...base, source: { kind: 'url', value: dryRunBackendPath(convertedName, options.sceneType) } },
3330
+ upload: null,
3331
+ localFile: null,
3332
+ conversion: conversionRecord,
3333
+ };
3334
+ }
3335
+ const downloaded = await downloadRemoteImageFileToTemp(value, {
3336
+ expectedFormat: conversion.fromFormat,
3337
+ fallbackName: resourceText(base).replace(/[^0-9A-Za-z._-]+/g, '-'),
3338
+ });
3339
+ try {
3340
+ const converted = await convertLocalImageFile(downloaded.filePath, conversion.toFormat);
3341
+ try {
3342
+ const upload = await uploadLocalFile(converted.filePath, { sceneType: options.sceneType });
3343
+ return {
3344
+ resource: { ...base, source: { kind: 'url', value: upload.backendPath } },
3345
+ upload,
3346
+ localFile: null,
3347
+ conversion: {
3348
+ ...conversionRecord,
3349
+ sourceSize: downloaded.size,
3350
+ convertedFile: converted.filePath,
3351
+ convertedSize: converted.size,
3352
+ },
3353
+ };
3354
+ } finally {
3355
+ await fs.rm(converted.filePath, { force: true }).catch(() => {});
3356
+ }
3357
+ } finally {
3358
+ await fs.rm(downloaded.dir, { recursive: true, force: true }).catch(() => {});
3359
+ }
3360
+ }
3361
+ return { resource: { ...base, source: { kind: 'url', value: normalizeBackendPathUrlValue(value) } }, upload: null, localFile: null };
2915
3362
  }
2916
3363
  const inspected = await inspectLocalFile(value);
2917
3364
  if (!inspected.exists) {
2918
3365
  throw argumentError(
2919
3366
  `资源文件不存在:${value}`,
2920
- 'source.kind=url 只接受完整 http(s) URL、material backendPath,或当前工作目录下存在的本地文件路径。',
3367
+ 'source.kind=url 只接受完整 http(s) URL、平台 backendPath,或当前工作目录下存在的本地文件路径。',
2921
3368
  );
2922
3369
  }
2923
3370
  const conversion = options.resourceRules
@@ -3040,7 +3487,9 @@ async function buildImageRequest(kwargs = {}, options = {}) {
3040
3487
  kind: 'image',
3041
3488
  sceneType: TASK_UPLOAD_SCENE.IMAGE_CREATE,
3042
3489
  });
3490
+ const genericModelParams = await collectGenericModelParams(kwargs);
3043
3491
  const defaultParams = {
3492
+ ...genericModelParams,
3044
3493
  prompt,
3045
3494
  resources: validationResources.resources,
3046
3495
  };
@@ -3218,7 +3667,9 @@ async function buildVideoRequest(kwargs = {}, options = {}) {
3218
3667
  throw argumentError('缺少视频生成输入', '至少传 --prompt 或 --resource。');
3219
3668
  }
3220
3669
  assertVideoReferenceKeysUsed(prompt, validationResources.resources);
3670
+ const genericModelParams = await collectGenericModelParams(kwargs);
3221
3671
  const defaultParams = {
3672
+ ...genericModelParams,
3222
3673
  prompt,
3223
3674
  resources: validationResources.resources,
3224
3675
  };
@@ -3349,6 +3800,11 @@ const IMAGE_BATCH_ITEM_KEYS = new Set([
3349
3800
  'quality',
3350
3801
  'generate_num',
3351
3802
  'generateNum',
3803
+ 'model_param',
3804
+ 'modelParam',
3805
+ 'model_params',
3806
+ 'modelParams',
3807
+ 'modelParamsJson',
3352
3808
  'resource',
3353
3809
  'resources',
3354
3810
  'resourcesJson',
@@ -3361,6 +3817,11 @@ const VIDEO_BATCH_ITEM_KEYS = new Set([
3361
3817
  'duration',
3362
3818
  'need_audio',
3363
3819
  'needAudio',
3820
+ 'model_param',
3821
+ 'modelParam',
3822
+ 'model_params',
3823
+ 'modelParams',
3824
+ 'modelParamsJson',
3364
3825
  'resource',
3365
3826
  'resources',
3366
3827
  'resourcesJson',
@@ -3372,18 +3833,21 @@ function normalizeTaskBatchItem(item, kind, index) {
3372
3833
  throw argumentError(`批量输入第 ${index + 1} 项必须是 JSON 对象或纯文本 prompt`);
3373
3834
  }
3374
3835
  const allowedKeys = kind === 'image' ? IMAGE_BATCH_ITEM_KEYS : VIDEO_BATCH_ITEM_KEYS;
3375
- const unknownKeys = Object.keys(item).filter((key) => !allowedKeys.has(key));
3836
+ const unknownKeys = Object.keys(item).filter((key) => !allowedKeys.has(key) && !key.includes('_'));
3376
3837
  if (unknownKeys.length) {
3377
3838
  throw argumentError(
3378
3839
  `批量输入第 ${index + 1} 项存在未知字段:${unknownKeys.join(', ')}`,
3379
3840
  kind === 'image'
3380
- ? '生图批量项只接受 prompt、ratio、quality、generate_num、resources、resource、customBizId。'
3381
- : '生视频批量项只接受 prompt、ratio、quality、duration、need_audio、resources、resource、customBizId。',
3841
+ ? '生图批量项只接受 prompt、ratio、quality、generate_num、resources、resource、model_params、customBizId,或 model options.params[] 中的下划线参数。'
3842
+ : '生视频批量项只接受 prompt、ratio、quality、duration、need_audio、resources、resource、model_params、customBizId,或 model options.params[] 中的下划线参数。',
3382
3843
  );
3383
3844
  }
3384
3845
  const next = { ...item };
3385
3846
  if (next.generate_num != null && next.generateNum == null) next.generateNum = next.generate_num;
3386
3847
  if (next.need_audio != null && next.needAudio == null) next.needAudio = next.need_audio;
3848
+ if (next.model_param != null && next.modelParam == null) next.modelParam = next.model_param;
3849
+ if (next.model_params != null && next.modelParams == null) next.modelParams = next.model_params;
3850
+ if (next.model_params_json != null && next.modelParamsJson == null) next.modelParamsJson = next.model_params_json;
3387
3851
  return next;
3388
3852
  }
3389
3853
 
@@ -3638,7 +4102,8 @@ function normalizeCosAssetPath(value) {
3638
4102
  if (!text) return null;
3639
4103
  if (/^https?:\/\//i.test(text)) {
3640
4104
  try {
3641
- return decodeURIComponent(new URL(text).pathname.replace(/^\/+/, ''));
4105
+ const pathname = decodeURIComponent(new URL(text).pathname);
4106
+ return isPlatformBackendPath(pathname) ? pathname.replace(/^\/+/, '') : text;
3642
4107
  } catch {
3643
4108
  return text.replace(/^\/+/, '');
3644
4109
  }