@lingjingai/lj-awb-cli 0.3.11

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 (36) hide show
  1. package/README.md +314 -0
  2. package/install.mjs +41 -0
  3. package/package.json +40 -0
  4. package/packages/awb-cli/README.md +19 -0
  5. package/packages/awb-cli/bin/lj-awb +19 -0
  6. package/packages/awb-cli/bin/lj-awb.js +11 -0
  7. package/packages/awb-cli/package.json +18 -0
  8. package/packages/awb-core/README.md +12 -0
  9. package/packages/awb-core/package.json +20 -0
  10. package/packages/awb-core/src/api.js +349 -0
  11. package/packages/awb-core/src/auth.js +80 -0
  12. package/packages/awb-core/src/commands.js +817 -0
  13. package/packages/awb-core/src/common.js +508 -0
  14. package/packages/awb-core/src/output.js +758 -0
  15. package/packages/awb-core/src/services.js +2966 -0
  16. package/packages/awb-core/src/standalone.js +820 -0
  17. package/skills/lj-awb/SKILL.md +97 -0
  18. package/skills/lj-awb/VERSION +1 -0
  19. package/skills/lj-awb/compat.json +6 -0
  20. package/skills/lj-awb/modules/account.md +17 -0
  21. package/skills/lj-awb/modules/asset.md +21 -0
  22. package/skills/lj-awb/modules/auth.md +23 -0
  23. package/skills/lj-awb/modules/create-contract.md +112 -0
  24. package/skills/lj-awb/modules/credits.md +20 -0
  25. package/skills/lj-awb/modules/evals.md +152 -0
  26. package/skills/lj-awb/modules/image.md +58 -0
  27. package/skills/lj-awb/modules/model.md +96 -0
  28. package/skills/lj-awb/modules/project.md +24 -0
  29. package/skills/lj-awb/modules/subject.md +22 -0
  30. package/skills/lj-awb/modules/task-manual.md +142 -0
  31. package/skills/lj-awb/modules/task.md +19 -0
  32. package/skills/lj-awb/modules/upload.md +18 -0
  33. package/skills/lj-awb/modules/video.md +81 -0
  34. package/skills/lj-awb/modules/workflows.md +223 -0
  35. package/skills/lj-awb/references/model-options-read.md +43 -0
  36. package/skills/lj-awb/scripts/resolve-lj-awb-cmd.sh +10 -0
@@ -0,0 +1,2966 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import {
5
+ API_ORIGIN,
6
+ APP_HOME_DIR,
7
+ AUTH_PATH,
8
+ DEFAULT_API_ORIGIN,
9
+ STATE_PATH,
10
+ TASK_UPLOAD_SCENE,
11
+ LingjingAwbCliError,
12
+ buildCosAuthorization,
13
+ encodeObjectNamePath,
14
+ firstArray,
15
+ flattenRecord,
16
+ guessMimeType,
17
+ inspectLocalFile,
18
+ inspectLocalFiles,
19
+ isSuccessTaskStatus,
20
+ isTerminalTaskStatus,
21
+ loadState,
22
+ normalizeFeedTaskType,
23
+ nowIso,
24
+ parseJsonArg,
25
+ parseListArg,
26
+ safeFileName,
27
+ saveState,
28
+ sleep,
29
+ splitCsv,
30
+ taskStatusText,
31
+ taskTypeToStatusKind,
32
+ toBool,
33
+ toInt,
34
+ toNumberOrNull,
35
+ trimToNull,
36
+ uniqueNonEmpty,
37
+ } from './common.js';
38
+ import { loadAuth, resolveAuthContext, summarizeAuth } from './auth.js';
39
+ import * as awbApi from './api.js';
40
+
41
+ const SITE = 'lj-awb';
42
+ const REQUEST_SOURCE_CLI = 'LINGJING_AWB_CLI';
43
+ const DEFAULT_TASK_RECORD_FILE_ENV = process.env.LINGJING_AWB_TASK_RECORD_FILE || process.env.AWB_TASK_RECORD_FILE;
44
+
45
+ export function normalizeUserInfo(payload) {
46
+ const data = payload && typeof payload === 'object' ? payload : {};
47
+ return {
48
+ userId: data.userId ?? data.id ?? null,
49
+ userName: data.userName ?? data.name ?? data.nickName ?? null,
50
+ phone: data.phone ?? null,
51
+ avatarUrl: data.avatarUrl ?? data.avatar ?? null,
52
+ groupId: data.groupId ?? data.currentGroupId ?? null,
53
+ groupName: data.groupName ?? data.currentGroupName ?? null,
54
+ permission: data.permission ?? null,
55
+ };
56
+ }
57
+
58
+ export function normalizeRows(payload) {
59
+ if (Array.isArray(payload)) return payload;
60
+ if (!payload || typeof payload !== 'object') return [];
61
+ for (const value of Object.values(payload)) {
62
+ if (Array.isArray(value)) return value;
63
+ }
64
+ return firstArray(payload);
65
+ }
66
+
67
+ function argumentError(message, hint = '') {
68
+ return new LingjingAwbCliError(message, {
69
+ type: 'argument_error',
70
+ exitCode: 2,
71
+ hint,
72
+ });
73
+ }
74
+
75
+ function compactRecord(record = {}) {
76
+ return Object.fromEntries(Object.entries(record)
77
+ .filter(([, value]) => value !== undefined && value !== null && value !== ''));
78
+ }
79
+
80
+ function requireValue(kwargs, key, label = key) {
81
+ const value = trimToNull(kwargs?.[key]);
82
+ if (!value) {
83
+ throw argumentError(`缺少参数:--${label.replace(/[A-Z]/g, (char) => `-${char.toLowerCase()}`)}`);
84
+ }
85
+ return value;
86
+ }
87
+
88
+ export function ensureConfirmed(kwargs, message, details = {}) {
89
+ if (toBool(kwargs?.dryRun)) return;
90
+ if (toBool(kwargs?.yes)) return;
91
+ throw new LingjingAwbCliError(message, {
92
+ type: 'confirmation_required',
93
+ exitCode: 10,
94
+ hint: '确认后追加 --yes 重试;如果只是预览,请追加 --dry-run。',
95
+ details,
96
+ });
97
+ }
98
+
99
+ function envProjectGroupNo() {
100
+ return trimToNull(
101
+ process.env.LINGJING_AWB_PROJECT_GROUP_NO
102
+ || process.env.AWB_PROJECT_GROUP_NO
103
+ || process.env.PROJECT_GROUP_NO
104
+ || process.env.SANDBOX_PROJECT_GROUP_NO,
105
+ );
106
+ }
107
+
108
+ function extractProjectGroupNo(payload) {
109
+ if (typeof payload === 'string') return trimToNull(payload);
110
+ if (!payload || typeof payload !== 'object') return null;
111
+ return trimToNull(
112
+ payload.projectGroupNo
113
+ ?? payload.lastProjectGroupNo
114
+ ?? payload.no
115
+ ?? payload.projectGroup?.projectGroupNo
116
+ ?? payload.projectGroup?.no,
117
+ );
118
+ }
119
+
120
+ export async function resolveProjectGroupNo(explicit, options = {}) {
121
+ const explicitProjectGroupNo = trimToNull(explicit);
122
+ if (explicitProjectGroupNo) {
123
+ if (!options.noSave) await saveState({ currentProjectGroupNo: explicitProjectGroupNo }).catch(() => {});
124
+ return explicitProjectGroupNo;
125
+ }
126
+ const fromEnv = envProjectGroupNo();
127
+ if (fromEnv) {
128
+ if (!options.noSave) await saveState({ currentProjectGroupNo: fromEnv }).catch(() => {});
129
+ return fromEnv;
130
+ }
131
+ if (!options.noNetwork) {
132
+ const current = await awbApi.fetchCurrentProjectGroup().catch(() => null);
133
+ const currentNo = extractProjectGroupNo(current);
134
+ if (currentNo) {
135
+ if (!options.noSave) await saveState({ currentProjectGroupNo: currentNo }).catch(() => {});
136
+ return currentNo;
137
+ }
138
+ }
139
+ const state = await loadState().catch(() => ({}));
140
+ if (trimToNull(state?.currentProjectGroupNo)) return trimToNull(state.currentProjectGroupNo);
141
+ if (options.allowNull) return null;
142
+ throw argumentError('未识别当前项目组', '请传 --project-group-no <no>,或先运行 project list 查看并选择。');
143
+ }
144
+
145
+ function extractPointBalance(payload) {
146
+ if (payload == null) return null;
147
+ if (typeof payload === 'number') return payload;
148
+ if (typeof payload !== 'object') return null;
149
+ for (const value of [
150
+ payload.point,
151
+ payload.groupPoint,
152
+ payload.availablePoint,
153
+ payload.totalPoint,
154
+ payload.teamIntegral,
155
+ payload.projectGroupIntegralCurrent,
156
+ payload.personIntegralCurrent,
157
+ ]) {
158
+ const numeric = toNumberOrNull(value);
159
+ if (numeric != null) return numeric;
160
+ }
161
+ return null;
162
+ }
163
+
164
+ function normalizeProjectGroupRecord(item, selectedProjectGroupNo = null) {
165
+ const projectGroupNo = item?.projectGroupNo ?? item?.no ?? null;
166
+ return {
167
+ projectGroupNo,
168
+ projectGroupName: item?.projectGroupName ?? item?.name ?? null,
169
+ point: item?.point ?? null,
170
+ isSelected: Boolean(projectGroupNo && selectedProjectGroupNo && projectGroupNo === selectedProjectGroupNo),
171
+ };
172
+ }
173
+
174
+ export async function listProjectGroups(kwargs = {}) {
175
+ const [listPayload, currentPayload] = await Promise.all([
176
+ awbApi.fetchProjectGroups(),
177
+ awbApi.fetchCurrentProjectGroup().catch(() => null),
178
+ ]);
179
+ const selectedProjectGroupNo = extractProjectGroupNo(currentPayload);
180
+ if (selectedProjectGroupNo) await saveState({ currentProjectGroupNo: selectedProjectGroupNo }).catch(() => {});
181
+ const keyword = trimToNull(kwargs.name ?? kwargs.keyword)?.toLowerCase();
182
+ const rows = normalizeRows(listPayload)
183
+ .map((item) => normalizeProjectGroupRecord(item, selectedProjectGroupNo))
184
+ .filter((item) => {
185
+ if (!keyword) return true;
186
+ return [item.projectGroupNo, item.projectGroupName]
187
+ .map((value) => String(value ?? '').toLowerCase())
188
+ .some((value) => value.includes(keyword));
189
+ });
190
+ return { projectGroups: rows, currentProjectGroupNo: selectedProjectGroupNo };
191
+ }
192
+
193
+ export async function fetchProjectGroupSummary(projectGroupNo) {
194
+ const actualProjectGroupNo = await resolveProjectGroupNo(projectGroupNo);
195
+ const [groupsPayload, currentPayload, integralPayload] = await Promise.all([
196
+ awbApi.fetchProjectGroups().catch(() => []),
197
+ awbApi.fetchCurrentProjectGroup().catch(() => null),
198
+ awbApi.fetchProjectGroupIntegral(actualProjectGroupNo).catch(() => null),
199
+ ]);
200
+ const groups = normalizeRows(groupsPayload);
201
+ const currentNo = extractProjectGroupNo(currentPayload);
202
+ const row = groups.find((item) => (item?.projectGroupNo ?? item?.no) === actualProjectGroupNo);
203
+ const summary = {
204
+ projectGroupNo: actualProjectGroupNo,
205
+ projectGroupName: row?.projectGroupName ?? row?.name ?? null,
206
+ isSelected: actualProjectGroupNo === currentNo,
207
+ pointBalance: extractPointBalance(integralPayload),
208
+ projectPointBalance: integralPayload?.projectGroupIntegralCurrent ?? extractPointBalance(integralPayload),
209
+ projectPointMax: integralPayload?.projectGroupIntegralMax ?? null,
210
+ personPointBalance: integralPayload?.personIntegralCurrent ?? null,
211
+ personPointMax: integralPayload?.personIntegralMax ?? null,
212
+ teamPointBalance: integralPayload?.teamIntegral ?? null,
213
+ };
214
+ await saveState({
215
+ currentProjectGroupNo: summary.projectGroupNo,
216
+ currentProjectGroupName: summary.projectGroupName,
217
+ }).catch(() => {});
218
+ return summary;
219
+ }
220
+
221
+ export async function accountInfo() {
222
+ const [userInfo, pointPayload, currentProjectGroup] = await Promise.all([
223
+ awbApi.fetchUserInfo(),
224
+ awbApi.fetchPoints().catch(() => null),
225
+ fetchProjectGroupSummary().catch(() => null),
226
+ ]);
227
+ const user = normalizeUserInfo(userInfo);
228
+ await saveState({
229
+ currentUserId: user.userId,
230
+ currentUserName: user.userName,
231
+ currentGroupId: user.groupId,
232
+ currentGroupName: user.groupName,
233
+ currentProjectGroupNo: currentProjectGroup?.projectGroupNo ?? null,
234
+ currentProjectGroupName: currentProjectGroup?.projectGroupName ?? null,
235
+ }).catch(() => {});
236
+ return {
237
+ ...user,
238
+ teamPointBalance: extractPointBalance(pointPayload),
239
+ currentProjectGroupNo: currentProjectGroup?.projectGroupNo ?? null,
240
+ currentProjectGroupName: currentProjectGroup?.projectGroupName ?? null,
241
+ projectPointBalance: currentProjectGroup?.projectPointBalance ?? null,
242
+ projectPointMax: currentProjectGroup?.projectPointMax ?? null,
243
+ };
244
+ }
245
+
246
+ async function pathExists(filePath) {
247
+ if (!filePath) return false;
248
+ try {
249
+ await fs.access(filePath);
250
+ return true;
251
+ } catch {
252
+ return false;
253
+ }
254
+ }
255
+
256
+ function doctorCheck(name, status, message, details = {}) {
257
+ return compactRecord({ name, status, message, details: Object.keys(details).length ? details : undefined });
258
+ }
259
+
260
+ function doctorStatus(checks) {
261
+ if (checks.some((item) => item.status === 'error')) return 'error';
262
+ if (checks.some((item) => item.status === 'warning')) return 'warning';
263
+ return 'ready';
264
+ }
265
+
266
+ function doctorUserSummary(user) {
267
+ return compactRecord({
268
+ userId: user?.userId,
269
+ userName: user?.userName,
270
+ groupId: user?.groupId,
271
+ groupName: user?.groupName,
272
+ permission: user?.permission,
273
+ });
274
+ }
275
+
276
+ export async function doctor(kwargs = {}) {
277
+ const verify = toBool(kwargs.verify);
278
+ const nodeMajor = Number.parseInt(process.versions.node.split('.')[0], 10);
279
+ const auth = await loadAuth().catch(() => ({}));
280
+ const authContext = await resolveAuthContext({ required: false }).catch(() => ({ authenticated: false }));
281
+ const skillInstallDir = trimToNull(process.env.LINGJING_AWB_SKILL_INSTALL_DIR || process.env.ANIME_SKILL_INSTALL_DIR)
282
+ || path.join(process.env.HOME || '', '.cc-switch', 'skills', 'lj-awb');
283
+ const skillInstalled = await pathExists(path.join(skillInstallDir, 'SKILL.md'));
284
+ const locale = trimToNull(process.env.LC_ALL || process.env.LC_CTYPE || process.env.LANG);
285
+ const localeIsUtf8 = locale ? /utf-?8/i.test(locale) : false;
286
+ const apiOriginIsDefault = API_ORIGIN === DEFAULT_API_ORIGIN;
287
+ const checks = [
288
+ doctorCheck(
289
+ 'node',
290
+ nodeMajor >= 20 ? 'ok' : 'error',
291
+ nodeMajor >= 20 ? 'Node.js 版本满足 CLI 要求' : 'Node.js 版本过低,CLI 要求 >=20',
292
+ { nodeVersion: process.versions.node },
293
+ ),
294
+ doctorCheck(
295
+ 'auth',
296
+ authContext.authenticated ? 'ok' : 'warning',
297
+ authContext.authenticated ? '已配置 access key' : '未配置 access key,只能运行本地检查类命令',
298
+ { source: authContext.accessKeyInfo?.source ?? null, sourceName: authContext.accessKeyInfo?.sourceName ?? null },
299
+ ),
300
+ doctorCheck(
301
+ 'api_origin',
302
+ 'ok',
303
+ apiOriginIsDefault ? '正在使用默认 API origin' : '已显式配置 API origin',
304
+ { apiOrigin: API_ORIGIN, isDefault: apiOriginIsDefault },
305
+ ),
306
+ doctorCheck(
307
+ 'locale',
308
+ localeIsUtf8 ? 'ok' : 'warning',
309
+ localeIsUtf8 ? '终端字符集支持 UTF-8' : '当前终端字符集可能不是 UTF-8,中文参数可能出现乱码',
310
+ { locale },
311
+ ),
312
+ doctorCheck(
313
+ 'skill',
314
+ skillInstalled ? 'ok' : 'warning',
315
+ skillInstalled ? '已检测到本地 lj-awb skill' : '未检测到本地 lj-awb skill;不影响 CLI,但会影响 Agent 工作流体验',
316
+ { skillInstallDir },
317
+ ),
318
+ ];
319
+
320
+ let user = null;
321
+ let projectGroup = null;
322
+ if (verify) {
323
+ if (!authContext.authenticated) {
324
+ checks.push(doctorCheck('network_auth', 'error', '无法联网校验:缺少 access key'));
325
+ } else {
326
+ try {
327
+ user = doctorUserSummary(normalizeUserInfo(await awbApi.fetchUserInfo()));
328
+ checks.push(doctorCheck('network_auth', 'ok', 'access key 联网校验通过', {
329
+ userId: user.userId,
330
+ userName: user.userName,
331
+ groupId: user.groupId,
332
+ groupName: user.groupName,
333
+ }));
334
+ } catch (error) {
335
+ checks.push(doctorCheck('network_auth', 'error', 'access key 联网校验失败', {
336
+ type: error?.type ?? 'error',
337
+ message: error?.message ?? String(error),
338
+ }));
339
+ }
340
+ try {
341
+ const projectGroupNo = await resolveProjectGroupNo(kwargs.projectGroupNo, { allowNull: true });
342
+ projectGroup = projectGroupNo ? await fetchProjectGroupSummary(projectGroupNo) : null;
343
+ checks.push(doctorCheck(
344
+ 'project_group',
345
+ projectGroup?.projectGroupNo ? 'ok' : 'warning',
346
+ projectGroup?.projectGroupNo ? '已识别当前项目组' : '未识别当前项目组;生成任务前需要传 --project-group-no 或先选择项目组',
347
+ { projectGroupNo: projectGroup?.projectGroupNo ?? null, projectGroupName: projectGroup?.projectGroupName ?? null },
348
+ ));
349
+ } catch (error) {
350
+ checks.push(doctorCheck('project_group', 'warning', '项目组检查失败', {
351
+ type: error?.type ?? 'error',
352
+ message: error?.message ?? String(error),
353
+ }));
354
+ }
355
+ }
356
+ } else {
357
+ checks.push(doctorCheck('network', 'skipped', '默认不做联网校验;需要时追加 --verify'));
358
+ }
359
+
360
+ return {
361
+ doctorStatus: doctorStatus(checks),
362
+ verify,
363
+ runtime: {
364
+ nodeVersion: process.versions.node,
365
+ platform: process.platform,
366
+ arch: process.arch,
367
+ },
368
+ origins: {
369
+ apiOrigin: API_ORIGIN,
370
+ assetEditOrigin: awbApi.ASSET_EDIT_ORIGIN,
371
+ },
372
+ auth: summarizeAuth(auth, authContext.accessKeyInfo),
373
+ paths: {
374
+ appHomeDir: APP_HOME_DIR,
375
+ authPath: AUTH_PATH,
376
+ statePath: STATE_PATH,
377
+ skillInstallDir,
378
+ },
379
+ user,
380
+ projectGroup,
381
+ checks,
382
+ };
383
+ }
384
+
385
+ export async function selectTeam(kwargs = {}) {
386
+ const groupId = requireValue(kwargs, 'groupId', 'group-id');
387
+ if (toBool(kwargs.dryRun)) {
388
+ return { dryRun: true, action: 'account switch-team', selected: false, request: { groupId } };
389
+ }
390
+ ensureConfirmed(kwargs, '切换团队会改变后续 CLI 调用上下文,需要确认', {
391
+ action: 'account switch-team',
392
+ groupId,
393
+ });
394
+ await awbApi.updateCurrentTeam(groupId);
395
+ await saveState({ currentGroupId: groupId }).catch(() => {});
396
+ return { selected: true, groupId };
397
+ }
398
+
399
+ export async function selectProjectGroupCommand(kwargs = {}) {
400
+ const projectGroupNo = requireValue(kwargs, 'projectGroupNo', 'project-group-no');
401
+ if (toBool(kwargs.dryRun)) {
402
+ return {
403
+ dryRun: true,
404
+ action: 'project use',
405
+ selected: false,
406
+ request: { projectGroupNo },
407
+ };
408
+ }
409
+ ensureConfirmed(kwargs, '切换项目组会改变后续生成任务归属,需要确认', {
410
+ action: 'project use',
411
+ projectGroupNo,
412
+ });
413
+ await awbApi.selectProjectGroup(projectGroupNo);
414
+ await saveState({ currentProjectGroupNo: projectGroupNo }).catch(() => {});
415
+ return { selected: true, ...(await fetchProjectGroupSummary(projectGroupNo)) };
416
+ }
417
+
418
+ function buildProjectGroupUsersFromArgs(kwargs, allUsers = []) {
419
+ const membersJson = parseJsonArg(kwargs.membersJson, null);
420
+ if (Array.isArray(membersJson)) return membersJson;
421
+ const selectedUserIds = new Set(parseListArg(kwargs.userIds));
422
+ const rows = Array.isArray(allUsers) ? allUsers : [];
423
+ const groupUser = rows
424
+ .filter((user) => Boolean(user?.isCheck) || selectedUserIds.has(user?.userId))
425
+ .map((user) => ({
426
+ userId: user.userId,
427
+ role: user.isCheck ? user.role ?? 'CREATOR' : 'USER',
428
+ }))
429
+ .filter((item) => item.userId);
430
+ if (!groupUser.length && selectedUserIds.size) {
431
+ return [...selectedUserIds].map((userId, index) => ({ userId, role: index === 0 ? 'CREATOR' : 'USER' }));
432
+ }
433
+ if (groupUser.length && !groupUser.some((item) => item.role === 'CREATOR')) {
434
+ groupUser[0] = { ...groupUser[0], role: 'CREATOR' };
435
+ }
436
+ return groupUser;
437
+ }
438
+
439
+ export async function createProjectGroupCommand(kwargs = {}) {
440
+ const name = requireValue(kwargs, 'name');
441
+ const point = toInt(kwargs.point, 0);
442
+ if (toBool(kwargs.dryRun)) {
443
+ const groupUser = buildProjectGroupUsersFromArgs(kwargs, []);
444
+ return {
445
+ dryRun: true,
446
+ action: 'project create',
447
+ created: false,
448
+ request: { projectGroupName: name, point, groupUser },
449
+ memberCount: groupUser.length,
450
+ note: groupUser.length ? null : 'dry-run 未联网拉取团队默认成员;正式执行会自动获取已选成员。',
451
+ };
452
+ }
453
+ ensureConfirmed(kwargs, '创建项目组是云端写入动作,需要确认', {
454
+ action: 'project create',
455
+ projectGroupName: name,
456
+ point,
457
+ });
458
+ const before = normalizeRows(await awbApi.fetchProjectGroups().catch(() => []));
459
+ const allUsers = await awbApi.fetchProjectGroupUsers();
460
+ const groupUser = buildProjectGroupUsersFromArgs(kwargs, allUsers);
461
+ if (!groupUser.length) {
462
+ throw argumentError('未解析到项目组成员', '请先运行 project users,或传 --members-json / --user-ids。');
463
+ }
464
+ await awbApi.createProjectGroup({ projectGroupName: name, point, groupUser });
465
+ const after = normalizeRows(await awbApi.fetchProjectGroups());
466
+ const beforeIds = new Set(before.map((item) => item?.projectGroupNo ?? item?.no).filter(Boolean));
467
+ const created = after.find((item) => !beforeIds.has(item?.projectGroupNo ?? item?.no))
468
+ ?? after.find((item) => (item?.projectGroupName ?? item?.name) === name);
469
+ const projectGroupNo = created?.projectGroupNo ?? created?.no ?? null;
470
+ if (!projectGroupNo) {
471
+ throw new LingjingAwbCliError('项目组已创建,但没有解析到新 projectGroupNo', {
472
+ type: 'api_error',
473
+ exitCode: 1,
474
+ details: { name },
475
+ });
476
+ }
477
+ await awbApi.selectProjectGroup(projectGroupNo).catch(() => {});
478
+ return {
479
+ ...(await fetchProjectGroupSummary(projectGroupNo)),
480
+ created: true,
481
+ memberCount: groupUser.length,
482
+ };
483
+ }
484
+
485
+ export async function updateProjectGroupCommand(kwargs = {}) {
486
+ const projectGroupNo = await resolveProjectGroupNo(kwargs.projectGroupNo, {
487
+ allowNull: toBool(kwargs.dryRun),
488
+ noNetwork: toBool(kwargs.dryRun),
489
+ noSave: toBool(kwargs.dryRun),
490
+ });
491
+ if (!projectGroupNo) {
492
+ throw argumentError('缺少项目组编号', '传 --project-group-no <no>,或先选择当前项目组。');
493
+ }
494
+ const body = { projectGroupNo };
495
+ if (kwargs.name != null && String(kwargs.name).trim() !== '') {
496
+ body.projectGroupName = String(kwargs.name).trim();
497
+ }
498
+ if (kwargs.point != null && String(kwargs.point).trim() !== '') {
499
+ body.point = toInt(kwargs.point, 0);
500
+ }
501
+ if (Object.keys(body).length === 1) {
502
+ throw argumentError('缺少项目组更新字段', '至少传 --name 或 --point。');
503
+ }
504
+ if (toBool(kwargs.dryRun)) {
505
+ return {
506
+ dryRun: true,
507
+ action: 'project update',
508
+ updated: false,
509
+ request: body,
510
+ };
511
+ }
512
+ ensureConfirmed(kwargs, '修改项目组是云端写入动作,需要确认', {
513
+ action: 'project update',
514
+ body,
515
+ });
516
+ await awbApi.updateProjectGroup(body);
517
+ return {
518
+ ...(await fetchProjectGroupSummary(projectGroupNo).catch(() => ({ projectGroupNo }))),
519
+ updated: true,
520
+ };
521
+ }
522
+
523
+ export async function ensureProjectGroupCommand(kwargs = {}) {
524
+ const name = requireValue(kwargs, 'name');
525
+ if (toBool(kwargs.dryRun)) {
526
+ return {
527
+ dryRun: true,
528
+ action: 'project ensure',
529
+ request: {
530
+ projectGroupName: name,
531
+ point: toInt(kwargs.point, 0),
532
+ selectExisting: kwargs.selectExisting !== false,
533
+ },
534
+ note: 'dry-run 不联网判断是否已存在;正式执行会先查找同名项目组。',
535
+ };
536
+ }
537
+ const { projectGroups } = await listProjectGroups({ name });
538
+ const existing = projectGroups.find((item) => item.projectGroupName === name) ?? null;
539
+ if (existing?.projectGroupNo) {
540
+ ensureConfirmed(kwargs, '确认复用并切换到已存在项目组', {
541
+ action: 'project ensure',
542
+ projectGroupNo: existing.projectGroupNo,
543
+ });
544
+ await awbApi.selectProjectGroup(existing.projectGroupNo).catch(() => {});
545
+ return {
546
+ ...(await fetchProjectGroupSummary(existing.projectGroupNo)),
547
+ created: false,
548
+ reused: true,
549
+ };
550
+ }
551
+ return await createProjectGroupCommand(kwargs);
552
+ }
553
+
554
+ export async function creditsBalance(kwargs = {}) {
555
+ const projectGroupNo = await resolveProjectGroupNo(kwargs.projectGroupNo, { allowNull: true }).catch(() => null);
556
+ const [teamPayload, projectGroup] = await Promise.all([
557
+ awbApi.fetchPoints(),
558
+ projectGroupNo ? fetchProjectGroupSummary(projectGroupNo).catch(() => null) : Promise.resolve(null),
559
+ ]);
560
+ return {
561
+ teamPointBalance: extractPointBalance(teamPayload),
562
+ currentProjectGroupNo: projectGroup?.projectGroupNo ?? projectGroupNo,
563
+ currentProjectGroupName: projectGroup?.projectGroupName ?? null,
564
+ projectPointBalance: projectGroup?.projectPointBalance ?? null,
565
+ projectPointMax: projectGroup?.projectPointMax ?? null,
566
+ };
567
+ }
568
+
569
+ function parseTimeMs(value, fallback = null) {
570
+ if (value === undefined || value === null || value === '') return fallback;
571
+ const numeric = Number(value);
572
+ if (Number.isFinite(numeric)) return numeric < 1_000_000_000_000 ? numeric * 1000 : numeric;
573
+ const text = String(value).trim();
574
+ const parsed = Date.parse(/\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}/.test(text) ? `${text.replace(' ', 'T')}+08:00` : text);
575
+ return Number.isFinite(parsed) ? parsed : fallback;
576
+ }
577
+
578
+ function taskTimeMs(row) {
579
+ return parseTimeMs(row.gmtCreate ?? row.createdAt ?? row.createTime, null);
580
+ }
581
+
582
+ function usageBucket() {
583
+ return {
584
+ taskCount: 0,
585
+ successTaskCount: 0,
586
+ resultCount: 0,
587
+ pointTotal: 0,
588
+ };
589
+ }
590
+
591
+ function addTaskToUsage(bucket, row) {
592
+ bucket.taskCount += 1;
593
+ if (isSuccessTaskStatus(row.taskStatus)) bucket.successTaskCount += 1;
594
+ bucket.resultCount += toInt(row.resultCount, 0);
595
+ bucket.pointTotal += toNumberOrNull(row.pointNo) ?? 0;
596
+ }
597
+
598
+ export async function creditsUsageSummary(kwargs = {}) {
599
+ const projectGroupNo = await resolveProjectGroupNo(kwargs.projectGroupNo);
600
+ const sinceMs = parseTimeMs(kwargs.sinceMs ?? kwargs.since, null)
601
+ ?? (kwargs.lastHours ? Date.now() - toNumberOrNull(kwargs.lastHours) * 60 * 60 * 1000 : null);
602
+ const untilMs = parseTimeMs(kwargs.untilMs ?? kwargs.until, Date.now());
603
+ const taskTypes = parseListArg(kwargs.taskTypes).length
604
+ ? parseListArg(kwargs.taskTypes)
605
+ : ['IMAGE_CREATE', 'IMAGE_EDIT', 'VIDEO_GROUP'];
606
+ const pageSize = Math.min(Math.max(toInt(kwargs.pageSize, 100), 1), 200);
607
+ const tasks = [];
608
+ for (const taskType of taskTypes) {
609
+ const rows = await taskList({
610
+ taskType,
611
+ projectGroupNo,
612
+ pageSize,
613
+ minTime: untilMs,
614
+ });
615
+ for (const row of rows.tasks) {
616
+ const createdMs = taskTimeMs(row);
617
+ if (sinceMs != null && createdMs != null && createdMs < sinceMs) continue;
618
+ if (untilMs != null && createdMs != null && createdMs > untilMs) continue;
619
+ tasks.push(row);
620
+ }
621
+ }
622
+ const buckets = {};
623
+ for (const row of tasks) {
624
+ const key = normalizeFeedTaskType(row.feedTaskType ?? row.taskType);
625
+ buckets[key] ??= usageBucket();
626
+ addTaskToUsage(buckets[key], row);
627
+ }
628
+ const pointTotal = Object.values(buckets).reduce((sum, bucket) => sum + bucket.pointTotal, 0);
629
+ return {
630
+ projectGroupNo,
631
+ sinceMs,
632
+ sinceText: sinceMs ? new Date(sinceMs).toISOString() : null,
633
+ untilMs,
634
+ untilText: untilMs ? new Date(untilMs).toISOString() : null,
635
+ scannedTaskCount: tasks.length,
636
+ pointTotal,
637
+ buckets,
638
+ ...(toBool(kwargs.includeTasks) ? { tasks } : {}),
639
+ };
640
+ }
641
+
642
+ function modelListMetadata(kind, paramKeys = [], rulesByKey = new Map()) {
643
+ const keys = new Set(paramKeys);
644
+ const imageReferenceParams = ['cref', 'sref', 'iref', 'resources'].filter((key) => keys.has(key));
645
+ const videoResourceParams = ['frames', 'multi_param', 'multi_prompt'].filter((key) => keys.has(key));
646
+ const inputModes = createSpecInputModes(kind, keys, rulesByKey)
647
+ .filter((item) => item.supported)
648
+ .map((item) => item.mode);
649
+ const controls = [];
650
+ if (keys.has('ratio')) controls.push('ratio');
651
+ if (keys.has('quality')) controls.push('quality');
652
+ if (kind === 'image' && keys.has('generate_num')) controls.push('generateNum');
653
+ if (kind === 'video' && keys.has('generated_time')) controls.push('duration');
654
+ if (kind === 'video' && (keys.has('need_audio') || keys.has('audio'))) controls.push('needAudio');
655
+ return {
656
+ inputModes,
657
+ controls,
658
+ resourceParams: kind === 'image' ? imageReferenceParams : videoResourceParams,
659
+ };
660
+ }
661
+
662
+ function normalizeModelRows(payload, kind, options = {}) {
663
+ const includeRaw = Boolean(options.includeRaw);
664
+ const includeInternal = Boolean(options.includeInternal);
665
+ return normalizeRows(payload).map((item) => {
666
+ const modelCode = item?.modelCode ?? item?.code ?? item?.value ?? null;
667
+ const modelGroupCode = item?.modelGroupCode ?? item?.groupCode ?? item?.modelGroup?.modelGroupCode ?? item?.modelGroup?.code ?? null;
668
+ const rawText = JSON.stringify(item);
669
+ const rawOptions = normalizeRawModelOptions(item);
670
+ const rawParamKeys = rawOptions.map((option) => option.paramKey).filter(Boolean);
671
+ const paramKeys = rawParamKeys.length ? uniqueNonEmpty(rawParamKeys) : uniqueNonEmpty([
672
+ ...rawText.matchAll(/"paramKey"\s*:\s*"([^"]+)"/g),
673
+ ].map((match) => match[1]));
674
+ const rulesByKey = new Map(rawOptions.map((option) => [option.paramKey, option.rules]).filter(([key, rules]) => key && rules));
675
+ const metadata = modelListMetadata(kind, paramKeys, rulesByKey);
676
+ const row = compactRecord({
677
+ modelGroupCode,
678
+ displayName: item?.modelName ?? item?.name ?? item?.label ?? null,
679
+ provider: item?.provider ?? item?.vendor ?? item?.supplier ?? item?.componyName ?? null,
680
+ enabled: item?.enabled ?? item?.available ?? item?.status ?? null,
681
+ modelStatus: item?.modelStatus ?? null,
682
+ taskQueueNum: item?.taskQueueNum ?? null,
683
+ feeCalcType: item?.feeCalcType ?? item?.feeType ?? null,
684
+ inputModes: metadata.inputModes,
685
+ params: metadata.controls,
686
+ _searchText: JSON.stringify([
687
+ modelCode,
688
+ modelGroupCode,
689
+ item?.modelName ?? item?.name ?? item?.label,
690
+ item?.provider ?? item?.vendor ?? item?.supplier ?? item?.componyName,
691
+ metadata.inputModes.join(','),
692
+ metadata.controls.join(','),
693
+ metadata.resourceParams.join(','),
694
+ paramKeys.join(','),
695
+ ]),
696
+ ...(includeInternal ? { _modelCode: modelCode } : {}),
697
+ });
698
+ return includeRaw ? { ...row, raw: item } : row;
699
+ });
700
+ }
701
+
702
+ export async function listModels(kind, kwargs = {}) {
703
+ const usage = kind === 'image' ? 'IMAGE_CREATE' : 'VIDEO_CREATE';
704
+ const payload = await awbApi.fetchModelsByUsage(usage, {});
705
+ const keyword = trimToNull(kwargs.model ?? kwargs.keyword)?.toLowerCase();
706
+ const includeRaw = toBool(kwargs.includeRaw);
707
+ const models = normalizeModelRows(payload, kind, { includeRaw })
708
+ .filter((item) => {
709
+ if (!keyword) return true;
710
+ return String(item._searchText ?? '').toLowerCase().includes(keyword);
711
+ })
712
+ .map(({ _searchText, _modelCode, ...item }) => item);
713
+ return { usage, models };
714
+ }
715
+
716
+ async function findModelGroup(modelGroupCode, options = {}) {
717
+ const includeRaw = Boolean(options.includeRaw);
718
+ const [imageResult, videoResult] = await Promise.allSettled([
719
+ awbApi.fetchModelsByUsage('IMAGE_CREATE', {}),
720
+ awbApi.fetchModelsByUsage('VIDEO_CREATE', {}),
721
+ ]);
722
+ const imageModels = imageResult.status === 'fulfilled'
723
+ ? normalizeModelRows(imageResult.value, 'image', { includeRaw, includeInternal: true }).map((item) => ({ ...item, kind: 'image' }))
724
+ : [];
725
+ const videoModels = videoResult.status === 'fulfilled'
726
+ ? normalizeModelRows(videoResult.value, 'video', { includeRaw, includeInternal: true }).map((item) => ({ ...item, kind: 'video' }))
727
+ : [];
728
+ return [...imageModels, ...videoModels].find((item) => item.modelGroupCode === modelGroupCode) ?? null;
729
+ }
730
+
731
+ function resolveTaskModel(kind, kwargs = {}) {
732
+ const modelGroupCode = trimToNull(kwargs.modelGroupCode);
733
+ if (!modelGroupCode) {
734
+ throw argumentError('缺少模型组编码', '传 --model-group-code <code>;推荐先运行 model image-models / model video-models。');
735
+ }
736
+ return {
737
+ kind,
738
+ modelGroupCode,
739
+ };
740
+ }
741
+
742
+ async function fetchNormalizedModelOptions(options = {}) {
743
+ const payload = await awbApi.fetchModelOptions({
744
+ modelCode: options.modelCode,
745
+ modelGroupCode: options.modelGroupCode,
746
+ selectedConfigs: options.selectedConfigs,
747
+ });
748
+ const normalizedOptions = normalizeRows(payload).map((item) => ({
749
+ rank: item?.rank ?? null,
750
+ paramKey: item?.paramKey ?? null,
751
+ paramName: item?.paramName ?? null,
752
+ paramType: item?.paramType ?? null,
753
+ optionList: typeof item?.optionList === 'string' ? parseJsonArg(item.optionList, item.optionList) : item?.optionList ?? null,
754
+ required: item?.required ?? item?.rule?.required ?? null,
755
+ hasConstraint: item?.hasConstraint ?? null,
756
+ rules: item?.rules ?? item?.rule?.rules ?? null,
757
+ raw: options.includeRaw ? item : undefined,
758
+ }));
759
+ return {
760
+ modelGroupCode: options.modelGroupCode,
761
+ selectedConfigs: options.selectedConfigs,
762
+ options: normalizedOptions,
763
+ };
764
+ }
765
+
766
+ function normalizeRawModelOptions(rawModel = {}, options = {}) {
767
+ const rawParams = Array.isArray(rawModel?.modelParams) ? rawModel.modelParams : [];
768
+ return rawParams.map((item) => ({
769
+ rank: item?.rank ?? null,
770
+ paramKey: item?.paramKey ?? null,
771
+ paramName: item?.paramName ?? null,
772
+ paramType: item?.paramType ?? null,
773
+ optionList: typeof item?.optionList === 'string' ? parseJsonArg(item.optionList, item.optionList) : item?.optionList ?? null,
774
+ required: item?.required ?? item?.rules?.required ?? null,
775
+ hasConstraint: item?.hasConstraint ?? null,
776
+ rules: item?.rules ?? null,
777
+ raw: options.includeRaw ? item : undefined,
778
+ }));
779
+ }
780
+
781
+ function modelSummaryFromRaw(rawModel = {}, modelGroupCode, taskKind) {
782
+ return compactRecord({
783
+ modelGroupCode: rawModel?.modelGroupCode ?? modelGroupCode,
784
+ displayName: rawModel?.modelName ?? rawModel?.name ?? null,
785
+ provider: rawModel?.componyName ?? rawModel?.provider ?? rawModel?.vendor ?? null,
786
+ taskKind,
787
+ modelStatus: rawModel?.modelStatus ?? null,
788
+ taskQueueNum: rawModel?.taskQueueNum ?? null,
789
+ feeCalcType: rawModel?.feeCalcType ?? null,
790
+ });
791
+ }
792
+
793
+ async function loadModelOptionContext(modelGroupCode, options = {}) {
794
+ const rawModel = await awbApi.fetchModelGroupInfoAll(modelGroupCode);
795
+ const rawOptions = normalizeRawModelOptions(rawModel, { includeRaw: options.includeRaw });
796
+ let configOptions = [];
797
+ if (rawModel?.modelCode) {
798
+ const optionsPayload = await fetchNormalizedModelOptions({
799
+ modelCode: rawModel.modelCode,
800
+ modelGroupCode,
801
+ selectedConfigs: options.selectedConfigs ?? {},
802
+ includeRaw: options.includeRaw,
803
+ });
804
+ configOptions = Array.isArray(optionsPayload.options) ? optionsPayload.options : [];
805
+ }
806
+ const mergedOptions = mergeModelParamRules(configOptions.length ? configOptions : rawOptions, rawModel);
807
+ const optionKeys = new Set(mergedOptions.map((item) => item.paramKey).filter(Boolean));
808
+ const taskKind = inferTaskKind(rawModel, optionKeys);
809
+ const rulesByKey = new Map(mergedOptions.map((item) => [item.paramKey, item.rules]).filter(([key, rules]) => key && rules));
810
+ const inputModes = createSpecInputModes(taskKind, optionKeys, rulesByKey);
811
+ const createParams = mergedOptions.map((option) => createParamForModelOption(option, taskKind));
812
+ return {
813
+ rawModel,
814
+ model: modelSummaryFromRaw(rawModel, modelGroupCode, taskKind),
815
+ options: mergedOptions,
816
+ optionKeys,
817
+ rulesByKey,
818
+ taskKind,
819
+ inputModes,
820
+ createParams,
821
+ };
822
+ }
823
+
824
+ function optionAllowedValues(option = {}) {
825
+ if (!Array.isArray(option.optionList)) return [];
826
+ return option.optionList
827
+ .filter((item) => item?.available !== false)
828
+ .map((item) => item?.enumValue ?? item?.value ?? item?.code ?? item?.id ?? item)
829
+ .filter((value) => value !== undefined && value !== null && value !== '');
830
+ }
831
+
832
+ function optionAllowedOptions(option = {}) {
833
+ if (!Array.isArray(option.optionList)) return [];
834
+ return option.optionList
835
+ .filter((item) => item?.available !== false)
836
+ .map((item) => compactRecord({
837
+ label: item?.enumName ?? item?.label ?? item?.name ?? item?.enumValue ?? item?.value ?? null,
838
+ value: item?.enumValue ?? item?.value ?? item?.code ?? item?.id ?? item,
839
+ rank: item?.rank,
840
+ }));
841
+ }
842
+
843
+ function arrayOrUndefined(value) {
844
+ return Array.isArray(value) && value.length ? value : undefined;
845
+ }
846
+
847
+ function ruleNumber(value) {
848
+ if (value === undefined || value === null || value === '') return undefined;
849
+ const number = Number(value);
850
+ return Number.isFinite(number) ? number : undefined;
851
+ }
852
+
853
+ function normalizeMediaRule(rule = {}) {
854
+ if (!rule || typeof rule !== 'object') return {};
855
+ return compactRecord({
856
+ mediaType: rule.mediaType,
857
+ fileTypes: arrayOrUndefined(rule.supportedFileTypes),
858
+ minFiles: ruleNumber(rule.minFrameNum ?? rule.minPromptNum),
859
+ maxFiles: ruleNumber(rule.fileListMaxNum ?? rule.maxFrameNum),
860
+ maxSizeKB: ruleNumber(rule.resourceFileMaxSize),
861
+ minDurationMs: ruleNumber(rule.minDuration),
862
+ maxDurationMs: ruleNumber(rule.maxDuration),
863
+ maxTotalDurationMs: ruleNumber(rule.maxTotalDuration),
864
+ minItems: ruleNumber(rule.minPromptNum),
865
+ maxItems: ruleNumber(rule.maxPromptNum),
866
+ maxPromptLength: ruleNumber(rule.maxPromptLength),
867
+ supportLastFrame: rule.supportLastFrame,
868
+ required: rule.required,
869
+ });
870
+ }
871
+
872
+ function mediaRuleFromMultiParam(rules = {}, mediaType) {
873
+ const resources = Array.isArray(rules?.resources) ? rules.resources : [];
874
+ const found = resources.find((item) => String(item?.mediaType || '').toUpperCase() === mediaType);
875
+ return found ? normalizeMediaRule(found) : {};
876
+ }
877
+
878
+ function mergeResourceLimits(base = {}, overrides = {}) {
879
+ return compactRecord({ ...base, ...overrides });
880
+ }
881
+
882
+ function mergeModelParamRules(options = [], rawModel = null) {
883
+ const rawParams = Array.isArray(rawModel?.modelParams) ? rawModel.modelParams : [];
884
+ const rawByKey = new Map(rawParams.map((item) => [item?.paramKey, item]).filter(([key]) => key));
885
+ return options.map((option) => {
886
+ const raw = rawByKey.get(option.paramKey);
887
+ return {
888
+ ...option,
889
+ hasConstraint: option.hasConstraint ?? raw?.hasConstraint ?? null,
890
+ rules: option.rules ?? raw?.rules ?? null,
891
+ };
892
+ });
893
+ }
894
+
895
+ function createParamForModelOption(option = {}, taskKind = 'image') {
896
+ const key = option.paramKey;
897
+ const common = {
898
+ modelParamKey: key,
899
+ modelParamName: option.paramName ?? null,
900
+ modelParamType: option.paramType ?? null,
901
+ allowedValues: optionAllowedValues(option),
902
+ allowedOptions: optionAllowedOptions(option),
903
+ };
904
+ const definitions = {
905
+ prompt: {
906
+ key: 'prompt',
907
+ cliArg: '--prompt',
908
+ requestPath: 'promptParams.prompt',
909
+ materialLegacyKey: 'prompt',
910
+ meaning: taskKind === 'image' ? '用户提供的图片生成提示词文本。' : '用户提供的视频生成提示词文本。',
911
+ valueSource: '以用户明确的创作描述为 prompt 基底;CLI/Agent 负责资源占位符、key 对齐、转义清理和模型约束组装。需求不明确时先追问或使用最小中性表达,不主动编内容补空白。',
912
+ },
913
+ ratio: {
914
+ key: 'ratio',
915
+ cliArg: '--ratio',
916
+ requestPath: 'promptParams.ratio',
917
+ materialLegacyKey: 'ratio',
918
+ meaning: taskKind === 'image' ? '图片画幅比例。' : '视频画面比例。',
919
+ valueSource: '只能从 allowedValues 选择。',
920
+ },
921
+ quality: {
922
+ key: 'quality',
923
+ cliArg: '--quality',
924
+ requestPath: 'promptParams.quality',
925
+ materialLegacyKey: 'quality',
926
+ meaning: taskKind === 'image' ? '图片清晰度 / 分辨率档位。' : '视频清晰度 / 分辨率档位。',
927
+ valueSource: '只能从 allowedValues 选择。',
928
+ },
929
+ generate_num: {
930
+ key: 'generateNum',
931
+ cliArg: '--generate-num',
932
+ requestPath: 'promptParams.generate_num',
933
+ materialLegacyKey: 'generate_num',
934
+ meaning: '一次任务生成的图片张数。',
935
+ valueSource: '只能从 allowedValues 选择;CLI 会转成整数。',
936
+ },
937
+ generated_time: {
938
+ key: 'duration',
939
+ cliArg: '--duration',
940
+ requestPath: 'promptParams.duration',
941
+ materialLegacyKey: 'generated_time',
942
+ meaning: '视频生成时长,单位秒。',
943
+ valueSource: '只能从 allowedValues 选择;CLI 会转成整数。',
944
+ },
945
+ need_audio: {
946
+ key: 'needAudio',
947
+ cliArg: '--need-audio',
948
+ requestPath: 'promptParams.need_audio',
949
+ materialLegacyKey: 'need_audio',
950
+ meaning: '输出视频是否让模型生成 / 携带音频或音效的布尔开关。',
951
+ valueSource: '布尔值 true / false;仅模型配置存在该项且用户明确要求“输出带模型生成音频/音效”时使用。它不是上传音频文件的入口。',
952
+ controlKind: 'output_audio_toggle',
953
+ },
954
+ audio: {
955
+ key: 'needAudio',
956
+ cliArg: '--need-audio',
957
+ requestPath: 'promptParams.need_audio',
958
+ materialLegacyKey: 'audio',
959
+ meaning: '输出视频是否让模型生成 / 携带音频或音效的布尔开关。',
960
+ valueSource: '布尔值 true / false;仅模型配置存在该项且用户明确要求“输出带模型生成音频/音效”时使用。它不是上传音频文件的入口。',
961
+ controlKind: 'output_audio_toggle',
962
+ },
963
+ iref: {
964
+ key: 'resources',
965
+ cliArg: '--resource / --resources-json',
966
+ requestPath: 'promptParams.resources[]',
967
+ materialLegacyKey: 'iref',
968
+ meaning: '图片任务的参考图输入。',
969
+ valueSource: '本地文件、http(s) URL 或 material backendPath。',
970
+ resourceSyntax: ['image:reference=./ref.png'],
971
+ },
972
+ resources: {
973
+ key: 'resources',
974
+ cliArg: '--resource / --resources-json',
975
+ requestPath: 'promptParams.resources[]',
976
+ materialLegacyKey: 'resources',
977
+ meaning: '模型声明的素材输入;CLI 统一用 resources 表达。',
978
+ valueSource: '本地文件、http(s) URL 或 material backendPath。',
979
+ resourceSyntax: taskKind === 'image' ? ['image:reference=./ref.png'] : ['image:first_frame=./first.png'],
980
+ },
981
+ frames: {
982
+ key: 'resources',
983
+ cliArg: '--resource / --resources-json',
984
+ requestPath: 'promptParams.resources[]',
985
+ materialLegacyKey: 'frames',
986
+ meaning: '视频首帧 / 尾帧 / 关键帧输入。',
987
+ valueSource: '首帧/尾帧可用本地文件、http(s) URL、material backendPath 或 asset:<assetId>;keyframe 仅用文件/URL/backendPath。',
988
+ resourceSyntax: ['image:first_frame=./first.png', 'image:first_frame=asset:<assetId>', 'image:last_frame=asset:<assetId>', 'image:keyframe#1=./key1.png'],
989
+ },
990
+ multi_param: {
991
+ key: 'resources',
992
+ cliArg: '--resource / --resources-json',
993
+ requestPath: 'promptParams.resources[]',
994
+ materialLegacyKey: 'multi_param',
995
+ meaning: '参考生视频 / 主体参考 / 音视频参考输入;带 reference_key 的资源必须在 prompt 中出现同名 <<<key>>>。',
996
+ valueSource: '图片/视频/音频参考用对应 type 的 reference 资源;长期复用主体用 subject:reference:<key>=asset:<externalId>。',
997
+ resourceSyntax: [
998
+ 'image:reference:hero=./hero.png',
999
+ 'image:reference:hero=asset:<assetId>',
1000
+ 'video:reference:motion=./motion.mp4',
1001
+ 'audio:reference=./music.mp3',
1002
+ 'audio:reference:voice=./voice.wav',
1003
+ 'subject:reference:hero=asset:<externalId>',
1004
+ ],
1005
+ },
1006
+ multi_prompt: {
1007
+ key: 'resources',
1008
+ cliArg: '--resources-json',
1009
+ requestPath: 'promptParams.resources[]',
1010
+ materialLegacyKey: 'multi_prompt',
1011
+ meaning: '多段提示 / 关键帧提示输入;仅模型配置存在该项时使用。',
1012
+ valueSource: '使用 resources-json,在 keyframe resource 上携带 prompt / duration。',
1013
+ resourceSyntax: ['[{"type":"image","usage":"keyframe","order":1,"prompt":"...","source":{"kind":"url","value":"./k1.png"}}]'],
1014
+ },
1015
+ generated_mode: {
1016
+ key: 'generatedMode',
1017
+ cliArg: null,
1018
+ requestPath: null,
1019
+ materialLegacyKey: 'generated_mode',
1020
+ meaning: '平台旧参数的生成模式。Agent 不要手动传;CLI/Material 会根据 resources usage 推导 frames 或 multi_param。',
1021
+ valueSource: '由资源类型推导,不是用户输入。',
1022
+ internalOnly: true,
1023
+ },
1024
+ };
1025
+ return {
1026
+ ...(definitions[key] ?? {
1027
+ key,
1028
+ cliArg: null,
1029
+ requestPath: null,
1030
+ materialLegacyKey: key,
1031
+ meaning: '模型配置存在该参数,但当前 CLI 没有暴露为稳定创建参数;不要为了调用而硬塞旧字段。',
1032
+ valueSource: '如确实需要,先扩展 CLI 显式参数和 Material adapter。',
1033
+ notExposedByCli: true,
1034
+ }),
1035
+ ...common,
1036
+ };
1037
+ }
1038
+
1039
+ function inferTaskKind(found, optionKeys) {
1040
+ if (found?.kind) return found.kind;
1041
+ if (found?.usage === 'IMAGE_CREATE') return 'image';
1042
+ if (found?.usage === 'VIDEO_CREATE') return 'video';
1043
+ return ['generated_time', 'frames', 'multi_param', 'multi_prompt', 'generated_mode', 'need_audio']
1044
+ .some((key) => optionKeys.has(key)) ? 'video' : 'image';
1045
+ }
1046
+
1047
+ function createSpecInputModes(taskKind, optionKeys, rulesByKey = new Map()) {
1048
+ const hasPrompt = optionKeys.has('prompt');
1049
+ const hasImageReference = ['iref', 'cref', 'sref', 'resources'].some((key) => optionKeys.has(key));
1050
+ const hasFrames = optionKeys.has('frames');
1051
+ const hasMultiParam = optionKeys.has('multi_param');
1052
+ const hasMultiPrompt = optionKeys.has('multi_prompt');
1053
+ const imageReferenceRules = rulesByKey.get('iref') || rulesByKey.get('cref') || rulesByKey.get('sref') || rulesByKey.get('resources') || {};
1054
+ const framesRules = rulesByKey.get('frames') || {};
1055
+ const multiParamRules = rulesByKey.get('multi_param') || {};
1056
+ const multiPromptRules = rulesByKey.get('multi_prompt') || {};
1057
+ const multiParamResources = Array.isArray(multiParamRules.resources) ? multiParamRules.resources : [];
1058
+ const supportsMultiMedia = (mediaType) => {
1059
+ if (!hasMultiParam) return false;
1060
+ if (!multiParamResources.length) return true;
1061
+ return multiParamResources.some((item) => String(item?.mediaType || '').toUpperCase() === mediaType);
1062
+ };
1063
+ const supportsMultiImage = supportsMultiMedia('IMAGE');
1064
+ const supportsMultiVideo = supportsMultiMedia('VIDEO');
1065
+ const supportsMultiAudio = supportsMultiMedia('AUDIO');
1066
+ const supportsLastFrame = framesRules.supportLastFrame !== false;
1067
+ const videoPromptOnlyBlocked = taskKind === 'video' && hasPrompt && (hasFrames || hasMultiParam);
1068
+ const modes = [];
1069
+ modes.push({
1070
+ mode: 'prompt_only',
1071
+ supported: taskKind === 'image' ? hasPrompt : hasPrompt && !hasFrames && !hasMultiParam,
1072
+ intent: taskKind === 'image' ? '文生图' : '文生视频',
1073
+ requiredArgs: ['--model-group-code', '--prompt'],
1074
+ userInput: '只提供 prompt,不提供参考素材。',
1075
+ ...(videoPromptOnlyBlocked ? { unsupportedReason: '该视频模型配置要求在 frames 或 multi_param 模式中选择一种视觉输入,不能只传 prompt。' } : {}),
1076
+ });
1077
+ modes.push({
1078
+ mode: 'reference_image',
1079
+ supported: taskKind === 'image' ? hasImageReference : supportsMultiImage,
1080
+ intent: taskKind === 'image' ? '参考图生图 / 图像编辑式生成' : '参考图生视频',
1081
+ requiredArgs: taskKind === 'image'
1082
+ ? ['--model-group-code', '--prompt', '--resource image:reference=...']
1083
+ : ['--model-group-code', '--prompt', '--resource image:reference:<key>=...'],
1084
+ userInput: taskKind === 'image' ? '用户提供参考图,希望生成或编辑图片。' : '用户提供参考图,希望参考图中主体、风格或构图生成视频。',
1085
+ resourceSyntax: taskKind === 'image'
1086
+ ? ['image:reference=./ref.png']
1087
+ : ['image:reference:hero=./hero.png', 'image:reference:hero=asset:<assetId>'],
1088
+ requiredResources: taskKind === 'image' ? ['image:reference'] : ['image:reference:<key>'],
1089
+ sourceKinds: taskKind === 'image' ? ['local_file', 'http_url', 'backendPath'] : ['local_file', 'http_url', 'backendPath', 'asset_id'],
1090
+ resourceLimits: taskKind === 'image' ? normalizeMediaRule(imageReferenceRules) : mediaRuleFromMultiParam(multiParamRules, 'IMAGE'),
1091
+ promptBinding: taskKind === 'video' ? 'key_required' : 'none',
1092
+ promptPlaceholder: taskKind === 'video' ? '使用带 key 的参考资源时,prompt 必须包含同名 <<<key>>>;例如 image:reference:hero 必须对应 <<<hero>>>。' : null,
1093
+ resourceConstraints: taskKind === 'video' ? ['reference_key_required', 'prompt_must_contain_key'] : [],
1094
+ ...((taskKind === 'image' ? !hasImageReference : !supportsMultiImage) ? { unsupportedReason: '模型配置没有对应参考图片资源参数。' } : {}),
1095
+ });
1096
+ if (taskKind === 'video') {
1097
+ modes.push({
1098
+ mode: 'reference_audio',
1099
+ supported: supportsMultiAudio,
1100
+ intent: '参考音频生视频',
1101
+ requiredArgs: ['--model-group-code', '--prompt', '--resource audio:reference=...'],
1102
+ userInput: '用户上传或提供音乐、声音、配音、节奏等音频,希望作为生成参考;这属于 resources 输入,不是 --need-audio。',
1103
+ resourceSyntax: ['audio:reference=./music.mp3', 'audio:reference:voice=./voice.wav'],
1104
+ requiredResources: ['audio:reference'],
1105
+ sourceKinds: ['local_file', 'http_url', 'backendPath', 'asset_id'],
1106
+ resourceLimits: mediaRuleFromMultiParam(multiParamRules, 'AUDIO'),
1107
+ promptBinding: 'optional_key',
1108
+ promptPlaceholder: '普通音频参考可不写 key;当用户强调音频也要参考 / 显式绑定音频时,可用 audio:reference:<key> 并在 prompt 中包含同名 <<<key>>>。',
1109
+ resourceConstraints: ['use_resource_not_need_audio', 'if_key_then_prompt_must_contain_key'],
1110
+ ...(!supportsMultiAudio ? { unsupportedReason: '模型配置没有音频参考资源规则。' } : {}),
1111
+ });
1112
+ modes.push({
1113
+ mode: 'reference_video',
1114
+ supported: supportsMultiVideo,
1115
+ intent: '参考视频生视频',
1116
+ requiredArgs: ['--model-group-code', '--prompt', '--resource video:reference:<key>=...'],
1117
+ userInput: '用户提供参考视频,希望参考运动、节奏或镜头生成视频。',
1118
+ resourceSyntax: ['video:reference:motion=./motion.mp4', 'video:reference:motion=asset:<assetId>'],
1119
+ requiredResources: ['video:reference:<key>'],
1120
+ sourceKinds: ['local_file', 'http_url', 'backendPath', 'asset_id'],
1121
+ resourceLimits: mediaRuleFromMultiParam(multiParamRules, 'VIDEO'),
1122
+ promptBinding: 'key_required',
1123
+ promptPlaceholder: '使用带 key 的参考视频时,prompt 必须包含同名 <<<key>>>;例如 video:reference:motion 必须对应 <<<motion>>>。',
1124
+ resourceConstraints: ['reference_key_required', 'prompt_must_contain_key'],
1125
+ ...(!supportsMultiVideo ? { unsupportedReason: '模型配置没有视频参考资源规则。' } : {}),
1126
+ });
1127
+ modes.push({
1128
+ mode: 'first_frame',
1129
+ supported: hasFrames,
1130
+ intent: '首帧生视频',
1131
+ requiredArgs: ['--model-group-code', '--resource image:first_frame=...'],
1132
+ userInput: '用户提供起始画面,希望从这张图延展成视频。',
1133
+ resourceSyntax: ['image:first_frame=./first.png', 'image:first_frame=asset:<assetId>'],
1134
+ requiredResources: ['image:first_frame'],
1135
+ sourceKinds: ['local_file', 'http_url', 'backendPath', 'asset_id'],
1136
+ resourceLimits: mergeResourceLimits(normalizeMediaRule(framesRules), { minFiles: 1, maxFiles: 1 }),
1137
+ promptBinding: 'none',
1138
+ promptPlaceholder: '不需要 <<<key>>> 占位符。',
1139
+ resourceConstraints: ['last_frame_not_required', 'key_not_used'],
1140
+ ...(!hasFrames ? { unsupportedReason: '模型配置没有 frames 参数。' } : {}),
1141
+ });
1142
+ modes.push({
1143
+ mode: 'first_last_frame',
1144
+ supported: hasFrames && supportsLastFrame,
1145
+ intent: '首尾帧过渡生视频',
1146
+ requiredArgs: ['--model-group-code', '--resource image:first_frame=...', '--resource image:last_frame=...'],
1147
+ userInput: '用户提供起始画面和结束画面,希望生成中间过渡视频。',
1148
+ resourceSyntax: ['image:first_frame=./first.png', 'image:last_frame=./last.png', 'image:first_frame=asset:<assetId>', 'image:last_frame=asset:<assetId>'],
1149
+ requiredResources: ['image:first_frame', 'image:last_frame'],
1150
+ sourceKinds: ['local_file', 'http_url', 'backendPath', 'asset_id'],
1151
+ resourceLimits: mergeResourceLimits(normalizeMediaRule(framesRules), { minFiles: 2, maxFiles: 2 }),
1152
+ promptBinding: 'none',
1153
+ promptPlaceholder: '不需要 <<<key>>> 占位符。',
1154
+ resourceConstraints: ['both_first_and_last_required', 'key_not_used'],
1155
+ ...(!hasFrames ? { unsupportedReason: '模型配置没有 frames 参数。' } : (!supportsLastFrame ? { unsupportedReason: '模型配置声明 supportLastFrame=false。' } : {})),
1156
+ });
1157
+ modes.push({
1158
+ mode: 'subject_reference',
1159
+ supported: supportsMultiImage,
1160
+ intent: '可复用主体参考生视频',
1161
+ requiredArgs: ['--model-group-code', '--prompt "<<<key>>> ..."', '--resource subject:reference:<key>=asset:<externalId>'],
1162
+ userInput: '用户要长期复用同一个角色 / 主体,并希望 prompt 显式引用该主体。',
1163
+ resourceSyntax: ['subject:reference:hero=asset:<externalId>'],
1164
+ requiredResources: ['subject:reference:<key>=asset:<externalId>'],
1165
+ sourceKinds: ['asset_id'],
1166
+ resourceLimits: mediaRuleFromMultiParam(multiParamRules, 'IMAGE'),
1167
+ promptBinding: 'key_required',
1168
+ promptPlaceholder: '必须使用 <<<key>>>,key 必须等于 subject reference_key。',
1169
+ resourceConstraints: ['external_id_from_subject_wait', 'prompt_must_contain_key'],
1170
+ ...(!supportsMultiImage ? { unsupportedReason: '模型配置没有图片 / 主体参考资源规则。' } : {}),
1171
+ });
1172
+ modes.push({
1173
+ mode: 'storyboard',
1174
+ supported: hasMultiPrompt,
1175
+ intent: '故事板 / 多段关键帧生视频',
1176
+ requiredArgs: ['--model-group-code', '--resources-json <keyframe[]>'],
1177
+ userInput: '用户提供多段分镜,每段可包含 keyframe 图片、局部 prompt 和小数秒 duration。',
1178
+ resourceSyntax: ['[{"type":"image","usage":"keyframe","order":1,"prompt":"...","duration":0.8,"source":{"kind":"url","value":"./k1.png"}}]'],
1179
+ requiredResources: ['image:keyframe#<order>'],
1180
+ sourceKinds: ['local_file', 'http_url', 'backendPath'],
1181
+ resourceLimits: normalizeMediaRule(multiPromptRules),
1182
+ promptBinding: 'none',
1183
+ promptPlaceholder: '不需要 <<<key>>> 占位符;每段文案写在 keyframe.prompt。',
1184
+ resourceConstraints: ['order_required_positive_integer', 'duration_allows_decimal_seconds', 'asset_id_not_supported'],
1185
+ ...(!hasMultiPrompt ? { unsupportedReason: '模型配置没有 multi_prompt 参数。' } : {}),
1186
+ });
1187
+ }
1188
+ return modes;
1189
+ }
1190
+
1191
+ function createSpecSupportedIntents(inputModes) {
1192
+ return inputModes
1193
+ .filter((item) => item.supported)
1194
+ .map((item) => compactRecord({
1195
+ mode: item.mode,
1196
+ intent: item.intent,
1197
+ userInput: item.userInput,
1198
+ requiredArgs: item.requiredArgs,
1199
+ resourceSyntax: item.resourceSyntax,
1200
+ promptBinding: item.promptBinding,
1201
+ promptPlaceholder: item.promptPlaceholder,
1202
+ }));
1203
+ }
1204
+
1205
+ function createSpecResourceRequirements(inputModes) {
1206
+ return inputModes
1207
+ .filter((item) => item.supported && Array.isArray(item.resourceSyntax) && item.resourceSyntax.length)
1208
+ .map((item) => compactRecord({
1209
+ mode: item.mode,
1210
+ intent: item.intent,
1211
+ resource: item.requiredResources,
1212
+ syntax: item.resourceSyntax,
1213
+ sources: item.sourceKinds,
1214
+ ...item.resourceLimits,
1215
+ promptBinding: item.promptBinding,
1216
+ constraints: item.resourceConstraints,
1217
+ }));
1218
+ }
1219
+
1220
+ function createSpecUnsupportedIntents(inputModes) {
1221
+ return inputModes
1222
+ .filter((item) => !item.supported)
1223
+ .map((item) => compactRecord({
1224
+ mode: item.mode,
1225
+ intent: item.intent,
1226
+ userInput: item.userInput,
1227
+ reason: item.unsupportedReason,
1228
+ }));
1229
+ }
1230
+
1231
+ function createSpecInputRequirement(taskKind, inputModes) {
1232
+ const supportedModeItems = inputModes.filter((item) => item.supported);
1233
+ const supportedModes = supportedModeItems.map((item) => item.mode);
1234
+ const promptRequiredModes = supportedModeItems
1235
+ .filter((item) => (item.requiredArgs || []).some((arg) => String(arg).includes('--prompt')))
1236
+ .map((item) => item.mode);
1237
+ const promptOptionalModes = supportedModeItems
1238
+ .filter((item) => !(item.requiredArgs || []).some((arg) => String(arg).includes('--prompt')))
1239
+ .map((item) => item.mode);
1240
+ const promptOnly = inputModes.find((item) => item.mode === 'prompt_only');
1241
+ const visualModes = supportedModes.filter((mode) => mode !== 'prompt_only');
1242
+ const visualInputRequired = taskKind === 'video' && promptOnly && !promptOnly.supported && visualModes.length > 0;
1243
+ const promptRequired = taskKind === 'image'
1244
+ ? true
1245
+ : supportedModes.length > 0 && promptRequiredModes.length === supportedModes.length;
1246
+ return compactRecord({
1247
+ promptRequired,
1248
+ promptRequiredModes: arrayOrUndefined(promptRequiredModes),
1249
+ promptOptionalModes: arrayOrUndefined(promptOptionalModes),
1250
+ visualInputRequired,
1251
+ summary: visualInputRequired
1252
+ ? '必须选择一种受支持的视觉输入;不能只传 prompt 创建视频。'
1253
+ : (taskKind === 'image' ? '至少需要 prompt;参考图按用户意图选择。' : '至少需要 prompt;是否需要素材取决于 selected input mode。'),
1254
+ acceptedModes: supportedModes,
1255
+ blockedModes: inputModes.filter((item) => !item.supported).map((item) => item.mode),
1256
+ });
1257
+ }
1258
+
1259
+ function resourceRequiredInModes(legacyKey, inputModes = []) {
1260
+ const supportedModes = inputModes.filter((item) => item.supported);
1261
+ return supportedModes
1262
+ .filter((item) => {
1263
+ const syntax = Array.isArray(item.resourceSyntax) ? item.resourceSyntax : [];
1264
+ if (['iref', 'cref', 'sref', 'resources'].includes(legacyKey)) {
1265
+ return item.mode === 'reference_image' && syntax.some((value) => String(value).startsWith('image:reference'));
1266
+ }
1267
+ if (legacyKey === 'frames') {
1268
+ return syntax.some((value) => /image:(first_frame|last_frame)=/.test(String(value)));
1269
+ }
1270
+ if (legacyKey === 'multi_param') {
1271
+ return syntax.some((value) => /^(image|video|audio|subject):reference/.test(String(value)));
1272
+ }
1273
+ if (legacyKey === 'multi_prompt') return item.mode === 'storyboard';
1274
+ return false;
1275
+ })
1276
+ .map((item) => item.mode);
1277
+ }
1278
+
1279
+ function createSpecParameterControls(createParams, inputModes = []) {
1280
+ const userParams = createParams
1281
+ .filter((item) => item.cliArg && item.key !== 'resources')
1282
+ .map((item) => compactRecord({
1283
+ key: item.key,
1284
+ cliArg: item.cliArg,
1285
+ meaning: item.meaning,
1286
+ valueSource: item.valueSource,
1287
+ controlKind: item.controlKind,
1288
+ allowedValues: item.allowedValues,
1289
+ }));
1290
+ const resourceParams = createParams
1291
+ .filter((item) => item.key === 'resources')
1292
+ .map((item) => compactRecord({
1293
+ legacyKey: item.materialLegacyKey,
1294
+ meaning: item.meaning,
1295
+ resourceSyntax: item.resourceSyntax,
1296
+ requiredInModes: resourceRequiredInModes(item.materialLegacyKey, inputModes),
1297
+ valueSource: item.valueSource,
1298
+ }));
1299
+ const hasAudioResource = resourceParams.some((item) => item.legacyKey === 'multi_param');
1300
+ const hasGeneratedAudioToggle = userParams.some((item) => item.key === 'needAudio');
1301
+ return compactRecord({
1302
+ userParams,
1303
+ resourceParams,
1304
+ audioSemantics: {
1305
+ uploadedAudioInput: hasAudioResource
1306
+ ? '用户上传音频、音乐、配音、节奏参考时,使用 --resource audio:reference=... 或 resources-json 中 type=audio;不要用 --need-audio。'
1307
+ : '当前模型规格没有 multi_param 资源通道,create-spec 未声明可上传音频参考资源。',
1308
+ generatedAudioToggle: hasGeneratedAudioToggle
1309
+ ? '--need-audio 只表示输出视频是否让模型生成 / 携带音频或音效,是布尔开关,不接收音频文件或 URL。'
1310
+ : '当前模型没有暴露 --need-audio;这只表示没有输出音频布尔开关,不等价于不能使用音频参考资源。',
1311
+ },
1312
+ note: '这里只列当前模型明确暴露的 CLI 可控参数。不要主动把未列出的参数总结成“不支持”;只有用户明确要求对应控制时,才说明 create-spec 没有该参数。',
1313
+ });
1314
+ }
1315
+
1316
+ function createSpecAgentGuidance(taskKind, inputRequirement) {
1317
+ const guidance = [
1318
+ '先用 model options 获取枚举值、文件类型、数量、大小和时长限制;create-spec 只负责创建方式。',
1319
+ '用 inputRequirement 和 supportedIntents 选择 create 输入模式;只传该模式要求的 CLI 参数,不传平台旧参数。',
1320
+ '资源带 reference_key 时,prompt 必须包含同名 <<<key>>>;first_frame、last_frame、keyframe 不需要 key。',
1321
+ '音频文件 / URL / asset 走 --resource audio:reference=...;--need-audio 只控制输出视频是否带模型生成音效。',
1322
+ 'prompt 以用户明确文本为基底,只补必要的 <<<key>>> 占位符和 shell/JSON 转义。',
1323
+ ];
1324
+ if (taskKind === 'video' && inputRequirement.visualInputRequired) {
1325
+ guidance.push('该视频模型必须带视觉输入;创建前必须从 supportedIntents 中选择 reference_image、first_frame、first_last_frame 或 subject_reference。');
1326
+ }
1327
+ return guidance;
1328
+ }
1329
+
1330
+ function createSpecValidationRules(taskKind) {
1331
+ const rules = [
1332
+ 'ratio、quality、duration、generateNum 等参数值以 model options.params[].values 为准。',
1333
+ '素材类型、文件格式、数量、大小和时长以 model options.resources[] 为准。',
1334
+ 'prompt 以用户明确创作描述为基底;没有明确需求时先追问或使用最小中性表达,不主动编内容补空白。',
1335
+ '资源一旦带 reference_key,prompt 必须包含同名 <<<key>>>;如果不想在 prompt 中显式引用该资源,就不要传 reference_key。',
1336
+ '正式扣费前先运行 fee,再运行 create --dry-run,给用户确认后才追加 --yes。',
1337
+ ];
1338
+ if (taskKind === 'video') {
1339
+ rules.push('subject reference 必须使用 asset:<externalId>,externalId 应来自 subject publish + subject wait。');
1340
+ } else {
1341
+ rules.push('图片任务 resources 只接受 image reference。');
1342
+ }
1343
+ return rules;
1344
+ }
1345
+
1346
+ function createSpecPreflight(taskKind) {
1347
+ const modelListCommand = taskKind === 'image' ? 'model image-models' : 'model video-models';
1348
+ const feeCommand = taskKind === 'image' ? 'image fee' : 'video fee';
1349
+ const createCommand = taskKind === 'image' ? 'image create' : 'video create';
1350
+ return [
1351
+ 'doctor --verify',
1352
+ `${modelListCommand} --model <keyword>`,
1353
+ 'model options --model-group-code <code>',
1354
+ 'model create-spec --model-group-code <code>',
1355
+ '按 options 的约束和 create-spec 的 supportedIntents 组装参数',
1356
+ feeCommand,
1357
+ `${createCommand} --dry-run`,
1358
+ '向用户确认模型、项目组、最终 prompt 文本、素材、关键参数和预估积分',
1359
+ `${createCommand} --yes`,
1360
+ ];
1361
+ }
1362
+
1363
+ function createSpecExamples(taskKind, inputModes) {
1364
+ const examples = [];
1365
+ const promptOnly = inputModes.find((item) => item.mode === 'prompt_only' && item.supported);
1366
+ const referenceImage = inputModes.find((item) => item.mode === 'reference_image' && item.supported);
1367
+ if (taskKind === 'image') {
1368
+ if (promptOnly) examples.push('lj-awb image create --model-group-code <code> --prompt "品牌吉祥物表情包四宫格" --ratio 1:1 --quality 1K --dry-run');
1369
+ if (referenceImage) examples.push('lj-awb image create --model-group-code <code> --prompt "保持参考图主体,生成海报" --resource image:reference=./ref.png --dry-run');
1370
+ } else {
1371
+ if (referenceImage) examples.push('lj-awb video create --model-group-code <code> --prompt "让 <<<hero>>> 转身看向镜头" --resource image:reference:hero=./hero.png --duration 5 --dry-run');
1372
+ if (inputModes.some((item) => item.mode === 'reference_audio' && item.supported)) {
1373
+ 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');
1374
+ }
1375
+ if (inputModes.some((item) => item.mode === 'first_frame' && item.supported)) {
1376
+ examples.push('lj-awb video create --model-group-code <code> --prompt "镜头缓慢推进" --resource image:first_frame=./first.png --duration 5 --dry-run');
1377
+ examples.push('lj-awb video create --model-group-code <code> --prompt "镜头缓慢推进" --resource image:first_frame=asset:<assetId> --duration 5 --dry-run');
1378
+ }
1379
+ if (inputModes.some((item) => item.mode === 'subject_reference' && item.supported)) examples.push('lj-awb video create --model-group-code <code> --prompt "<<<hero>>> 在雨夜奔跑" --resource subject:reference:hero=asset:<externalId> --duration 5 --dry-run');
1380
+ }
1381
+ return examples;
1382
+ }
1383
+
1384
+ function cliValueType(option = {}, allowedValues = []) {
1385
+ if (allowedValues.length) return 'enum';
1386
+ if (option.paramType === 'Prompt') return 'text';
1387
+ if (option.paramType === 'BooleanType') return 'boolean';
1388
+ if (/Number|Integer|Float/i.test(String(option.paramType || ''))) return 'number';
1389
+ return option.paramType || undefined;
1390
+ }
1391
+
1392
+ function modelOptionParams(options = [], taskKind = 'image') {
1393
+ return options
1394
+ .map((option) => ({ option, createParam: createParamForModelOption(option, taskKind) }))
1395
+ .filter(({ createParam }) => createParam.cliArg && createParam.key !== 'resources' && !createParam.internalOnly)
1396
+ .map(({ option, createParam }) => {
1397
+ const rules = option.rules || {};
1398
+ const allowedValues = optionAllowedValues(option);
1399
+ const required = option.required === true || rules.required === true ? true : undefined;
1400
+ const maxLength = option.paramType === 'Prompt'
1401
+ ? ruleNumber(rules.maxValue ?? rules.maxLength ?? rules.maxPromptLength)
1402
+ : undefined;
1403
+ return compactRecord({
1404
+ key: createParam.key,
1405
+ label: option.paramName,
1406
+ valueType: cliValueType(option, allowedValues),
1407
+ values: allowedValues.length ? allowedValues : undefined,
1408
+ defaultValue: rules.defaultValue,
1409
+ defaultName: rules.defaultName,
1410
+ maxLength,
1411
+ required,
1412
+ });
1413
+ });
1414
+ }
1415
+
1416
+ function optionResourceMedia(mode) {
1417
+ if (mode === 'reference_audio') return 'AUDIO';
1418
+ if (mode === 'reference_video') return 'VIDEO';
1419
+ if (mode === 'subject_reference') return 'SUBJECT';
1420
+ return 'IMAGE';
1421
+ }
1422
+
1423
+ function optionResourceUsage(mode) {
1424
+ if (mode === 'first_frame') return 'first_frame';
1425
+ if (mode === 'first_last_frame') return 'first_last_frame';
1426
+ if (mode === 'storyboard') return 'keyframe';
1427
+ return 'reference';
1428
+ }
1429
+
1430
+ function modelOptionsResources(inputModes = []) {
1431
+ return createSpecResourceRequirements(inputModes).map((item) => compactRecord({
1432
+ mode: item.mode,
1433
+ mediaType: optionResourceMedia(item.mode),
1434
+ usage: optionResourceUsage(item.mode),
1435
+ sources: item.sources,
1436
+ fileTypes: item.mode === 'subject_reference' ? undefined : item.fileTypes,
1437
+ minFiles: item.mode === 'subject_reference' ? undefined : item.minFiles,
1438
+ maxFiles: item.mode === 'subject_reference' ? undefined : item.maxFiles,
1439
+ maxSizeKB: item.mode === 'subject_reference' ? undefined : item.maxSizeKB,
1440
+ minDurationMs: item.mode === 'subject_reference' ? undefined : item.minDurationMs,
1441
+ maxDurationMs: item.mode === 'subject_reference' ? undefined : item.maxDurationMs,
1442
+ maxTotalDurationMs: item.mode === 'subject_reference' ? undefined : item.maxTotalDurationMs,
1443
+ minItems: item.minItems,
1444
+ maxItems: item.maxItems,
1445
+ maxPromptLength: item.maxPromptLength,
1446
+ supportLastFrame: item.supportLastFrame,
1447
+ }));
1448
+ }
1449
+
1450
+ export async function modelOptions(kwargs = {}) {
1451
+ const modelGroupCode = trimToNull(kwargs.modelGroupCode);
1452
+ if (!modelGroupCode) {
1453
+ throw argumentError('缺少模型组编码', '传 --model-group-code <code>。');
1454
+ }
1455
+ const selectedConfigs = parseJsonArg(kwargs.selectedConfigsJson, {}) ?? {};
1456
+ const includeRaw = toBool(kwargs.includeRaw);
1457
+ const context = await loadModelOptionContext(modelGroupCode, { selectedConfigs, includeRaw });
1458
+ return compactRecord({
1459
+ schemaVersion: 1,
1460
+ modelGroupCode,
1461
+ selectedConfigs,
1462
+ taskKind: context.taskKind,
1463
+ model: context.model,
1464
+ params: modelOptionParams(context.options, context.taskKind),
1465
+ resources: modelOptionsResources(context.inputModes),
1466
+ ...(includeRaw ? { options: context.options, rawModel: context.rawModel } : {}),
1467
+ });
1468
+ }
1469
+
1470
+ export async function modelCreateSpec(kwargs = {}) {
1471
+ const modelGroupCode = trimToNull(kwargs.modelGroupCode);
1472
+ if (!modelGroupCode) {
1473
+ throw argumentError('缺少模型组编码', '传 --model-group-code <code>。');
1474
+ }
1475
+ const includeRaw = toBool(kwargs.includeRaw);
1476
+ const context = await loadModelOptionContext(modelGroupCode, { includeRaw });
1477
+ const inputRequirement = createSpecInputRequirement(context.taskKind, context.inputModes);
1478
+ return compactRecord({
1479
+ schemaVersion: 1,
1480
+ modelGroupCode,
1481
+ taskKind: context.taskKind,
1482
+ createCommand: context.taskKind === 'image' ? 'image create' : 'video create',
1483
+ feeCommand: context.taskKind === 'image' ? 'image fee' : 'video fee',
1484
+ statusCommandTaskType: context.taskKind === 'image' ? 'IMAGE_CREATE' : 'VIDEO_GROUP',
1485
+ optionsCommand: `model options --model-group-code ${modelGroupCode}`,
1486
+ model: context.model,
1487
+ inputRequirement,
1488
+ supportedIntents: createSpecSupportedIntents(context.inputModes),
1489
+ validationRules: createSpecValidationRules(context.taskKind),
1490
+ agentGuidance: createSpecAgentGuidance(context.taskKind, inputRequirement),
1491
+ preflight: createSpecPreflight(context.taskKind),
1492
+ examples: createSpecExamples(context.taskKind, context.inputModes),
1493
+ ...(includeRaw ? { options: context.options, rawModel: context.rawModel } : {}),
1494
+ });
1495
+ }
1496
+
1497
+ async function readJsonMaybeFile(value, fallback) {
1498
+ const text = trimToNull(value);
1499
+ if (!text) return fallback;
1500
+ if (text.startsWith('{') || text.startsWith('[')) return parseJsonArg(text, fallback);
1501
+ const fileText = await fs.readFile(path.resolve(text), 'utf8');
1502
+ return JSON.parse(fileText);
1503
+ }
1504
+
1505
+ async function collectFileSpecs(kwargs = {}, defaultSceneType = TASK_UPLOAD_SCENE.DEFAULT) {
1506
+ const specs = [];
1507
+ for (const file of parseListArg(kwargs.file)) specs.push({ file });
1508
+ for (const file of parseListArg(kwargs.files)) specs.push({ file });
1509
+ const filesJson = await readJsonMaybeFile(kwargs.filesJson, null).catch((error) => {
1510
+ throw argumentError(`files-json 解析失败:${error.message}`);
1511
+ });
1512
+ if (Array.isArray(filesJson)) {
1513
+ for (const item of filesJson) {
1514
+ specs.push(typeof item === 'string' ? { file: item } : item);
1515
+ }
1516
+ }
1517
+ return specs
1518
+ .map((item) => ({
1519
+ file: trimToNull(item.file ?? item.path ?? item.filePath),
1520
+ sceneType: trimToNull(item.sceneType ?? kwargs.sceneType) ?? defaultSceneType,
1521
+ projectNo: trimToNull(item.projectNo ?? kwargs.projectNo) ?? '',
1522
+ }))
1523
+ .filter((item) => item.file);
1524
+ }
1525
+
1526
+ function dryRunBackendPath(filePath, sceneType) {
1527
+ return `/${sceneType}/__dry_run__/${safeFileName(filePath)}`;
1528
+ }
1529
+
1530
+ export async function uploadFilesCommand(kwargs = {}) {
1531
+ const specs = await collectFileSpecs(kwargs, trimToNull(kwargs.sceneType) ?? TASK_UPLOAD_SCENE.DEFAULT);
1532
+ if (!specs.length) throw argumentError('缺少上传文件', '传 --file <path> 或 --files a.png,b.mp4。');
1533
+ if (toBool(kwargs.dryRun)) {
1534
+ const files = [];
1535
+ for (const spec of specs) {
1536
+ const inspected = await inspectLocalFile(spec.file);
1537
+ files.push(compactRecord({
1538
+ ...inspected,
1539
+ sceneType: spec.sceneType,
1540
+ projectNo: spec.projectNo,
1541
+ backendPath: dryRunBackendPath(spec.file, spec.sceneType),
1542
+ url: null,
1543
+ dryRun: true,
1544
+ }));
1545
+ }
1546
+ return { dryRun: true, files };
1547
+ }
1548
+ const files = [];
1549
+ for (const spec of specs) {
1550
+ files.push(await uploadLocalFile(spec.file, spec));
1551
+ }
1552
+ return { files };
1553
+ }
1554
+
1555
+ export async function uploadLocalFile(filePath, options = {}) {
1556
+ const inspected = await inspectLocalFile(filePath);
1557
+ if (!inspected.exists) {
1558
+ throw argumentError(`文件不存在:${filePath}`);
1559
+ }
1560
+ const buffer = await fs.readFile(inspected.filePath);
1561
+ const sceneType = options.sceneType ?? TASK_UPLOAD_SCENE.DEFAULT;
1562
+ const groupId = crypto.randomUUID().replaceAll('-', '');
1563
+ const secret = await awbApi.fetchUploadSecret({
1564
+ sceneType,
1565
+ groupId,
1566
+ projectNo: options.projectNo ?? '',
1567
+ });
1568
+ const credentials = secret.credentials ?? secret;
1569
+ const objectName = `${secret.path ?? ''}${secret.prefix ?? ''}${Date.now()}-${safeFileName(inspected.filePath)}`.replace(/^\/+/, '');
1570
+ const host = `${secret.bucket}.cos.${secret.region}.myqcloud.com`;
1571
+ const authorization = buildCosAuthorization({
1572
+ secretKey: credentials.tmpSecretKey,
1573
+ secretId: credentials.tmpSecretId,
1574
+ method: 'PUT',
1575
+ objectName,
1576
+ contentLength: buffer.length,
1577
+ host,
1578
+ startTime: secret.startTime,
1579
+ expiredTime: secret.expiredTime,
1580
+ });
1581
+ const response = await fetch(`https://${host}/${encodeObjectNamePath(objectName)}`, {
1582
+ method: 'PUT',
1583
+ headers: {
1584
+ authorization,
1585
+ 'content-length': String(buffer.length),
1586
+ 'content-type': inspected.mimeType || guessMimeType(inspected.filePath),
1587
+ host,
1588
+ 'x-cos-security-token': credentials.sessionToken,
1589
+ },
1590
+ body: buffer,
1591
+ });
1592
+ if (!response.ok) {
1593
+ throw new LingjingAwbCliError(`上传 COS 失败:${response.status} ${response.statusText}`, {
1594
+ type: 'upload_failed',
1595
+ exitCode: 30,
1596
+ details: { filePath: inspected.filePath, objectName },
1597
+ });
1598
+ }
1599
+ return compactRecord({
1600
+ ...inspected,
1601
+ sceneType,
1602
+ projectNo: options.projectNo ?? '',
1603
+ backendPath: `/${objectName}`,
1604
+ url: `https://${host}/${encodeObjectNamePath(objectName)}`,
1605
+ });
1606
+ }
1607
+
1608
+ function resolveCustomBizId(explicit) {
1609
+ return trimToNull(explicit);
1610
+ }
1611
+
1612
+ const RESOURCE_OBJECT_KEYS = new Set(['type', 'usage', 'reference_key', 'source', 'order', 'prompt', 'duration']);
1613
+ const RESOURCE_SOURCE_KEYS = new Set(['kind', 'value']);
1614
+ const RESOURCE_TYPES = new Set(['image', 'video', 'audio', 'subject']);
1615
+ const RESOURCE_USAGES = new Set(['reference', 'first_frame', 'last_frame', 'keyframe']);
1616
+
1617
+ function parseIntegerParam(value, name, minValue) {
1618
+ if (value == null || value === '') return null;
1619
+ const text = String(value).trim();
1620
+ if (!/^[+-]?\d+$/.test(text)) {
1621
+ throw argumentError(`${name} 必须是整数`);
1622
+ }
1623
+ const parsed = Number(text);
1624
+ if (!Number.isSafeInteger(parsed)) {
1625
+ throw argumentError(`${name} 超出安全整数范围`);
1626
+ }
1627
+ if (parsed < minValue) {
1628
+ throw argumentError(`${name} 必须是${minValue === 0 ? '非负整数' : '正整数'}`);
1629
+ }
1630
+ return parsed;
1631
+ }
1632
+
1633
+ function normalizeUnifiedPromptParams(promptParams) {
1634
+ if (promptParams.duration != null && promptParams.duration !== '') {
1635
+ promptParams.duration = parseIntegerParam(promptParams.duration, 'promptParams.duration', 0);
1636
+ }
1637
+ if (promptParams.generate_num != null && promptParams.generate_num !== '') {
1638
+ promptParams.generate_num = parseIntegerParam(promptParams.generate_num, 'promptParams.generate_num', 1);
1639
+ }
1640
+ if (promptParams.need_audio != null && promptParams.need_audio !== '') {
1641
+ promptParams.need_audio = toBool(promptParams.need_audio);
1642
+ }
1643
+ return promptParams;
1644
+ }
1645
+
1646
+ function normalizeResourceType(type, index) {
1647
+ const normalized = String(type ?? '').trim().toLowerCase();
1648
+ if (!RESOURCE_TYPES.has(normalized)) {
1649
+ throw argumentError(`resource[${index}] type 不支持:${type}`, '支持 image、video、audio、subject。');
1650
+ }
1651
+ return normalized;
1652
+ }
1653
+
1654
+ function normalizeResourceUsage(usage, index) {
1655
+ const normalized = String(usage ?? '').trim().toLowerCase();
1656
+ if (!RESOURCE_USAGES.has(normalized)) {
1657
+ throw argumentError(`resource[${index}] usage 不支持:${usage}`, '支持 reference、first_frame、last_frame、keyframe。');
1658
+ }
1659
+ return normalized;
1660
+ }
1661
+
1662
+ function stripAssetPrefix(value) {
1663
+ const text = trimToNull(value);
1664
+ if (!text) return null;
1665
+ return text.startsWith('asset:') ? text.slice('asset:'.length) : text;
1666
+ }
1667
+
1668
+ function normalizeResourceSource(source, type, index, options = {}) {
1669
+ const explicitKind = trimToNull(source.source?.kind);
1670
+ const rawValue = trimToNull(source.source?.value ?? (options.allowShortcutValue ? source.value : null));
1671
+ if (!options.allowShortcutValue && !explicitKind) {
1672
+ throw argumentError(`resource[${index}] source.kind 不能为空`);
1673
+ }
1674
+ const assetValue = stripAssetPrefix(rawValue);
1675
+ const kind = explicitKind
1676
+ ? explicitKind.toLowerCase()
1677
+ : (rawValue?.startsWith('asset:') || type === 'subject' ? 'asset_id' : 'url');
1678
+ if (!['url', 'asset_id'].includes(kind)) {
1679
+ throw argumentError(`resource[${index}] source.kind 不支持:${kind}`, '支持 url、asset_id。');
1680
+ }
1681
+ const value = kind === 'asset_id' ? assetValue : rawValue;
1682
+ if (!value) {
1683
+ throw argumentError(`resource[${index}] source.value 不能为空`);
1684
+ }
1685
+ return { kind, value };
1686
+ }
1687
+
1688
+ function parseResourceShortcut(input, index) {
1689
+ const text = String(input ?? '').trim();
1690
+ const eqIndex = text.indexOf('=');
1691
+ if (!text || eqIndex <= 0) {
1692
+ throw argumentError(
1693
+ `resource[${index}] 格式错误`,
1694
+ '格式:--resource image:reference=./ref.png,或 --resource image:first_frame=material/a.png。',
1695
+ );
1696
+ }
1697
+ const left = text.slice(0, eqIndex).trim();
1698
+ const value = text.slice(eqIndex + 1).trim();
1699
+ const parts = left.split(':').map((item) => item.trim()).filter(Boolean);
1700
+ if (parts.length < 2 || parts.length > 3) {
1701
+ throw argumentError(`resource[${index}] 格式错误`, '格式:type:usage[:key]=value。');
1702
+ }
1703
+ const usageMatch = parts[1].match(/^([A-Za-z_]+)(?:#([0-9]+))?$/);
1704
+ if (!usageMatch) {
1705
+ throw argumentError(`resource[${index}] usage 格式错误`);
1706
+ }
1707
+ return {
1708
+ type: parts[0],
1709
+ usage: usageMatch[1],
1710
+ key: parts[2] || null,
1711
+ value,
1712
+ order: usageMatch[2] ? Number.parseInt(usageMatch[2], 10) : undefined,
1713
+ };
1714
+ }
1715
+
1716
+ function normalizeResourceObject(item, index) {
1717
+ const isShortcut = typeof item === 'string';
1718
+ const source = isShortcut ? parseResourceShortcut(item, index) : item;
1719
+ if (!source || typeof source !== 'object' || Array.isArray(source)) {
1720
+ throw argumentError(`resource[${index}] 必须是字符串短语法或 JSON 对象`);
1721
+ }
1722
+ if (!isShortcut) assertAllowedResourceObjectKeys(source, index);
1723
+ const type = normalizeResourceType(source.type, index);
1724
+ const usage = normalizeResourceUsage(source.usage, index);
1725
+ const resourceSource = normalizeResourceSource(source, type, index, { allowShortcutValue: isShortcut });
1726
+ const referenceKey = trimToNull(source.reference_key ?? (isShortcut ? source.key : null));
1727
+ const duration = normalizeResourceDuration(source.duration, index);
1728
+ const normalized = {
1729
+ type,
1730
+ usage,
1731
+ ...(referenceKey ? { reference_key: referenceKey } : {}),
1732
+ ...(source.order != null ? { order: Number(source.order) } : {}),
1733
+ ...(trimToNull(source.prompt) ? { prompt: trimToNull(source.prompt) } : {}),
1734
+ ...(duration != null ? { duration } : {}),
1735
+ _source: resourceSource,
1736
+ };
1737
+ if (usage !== 'reference' && referenceKey) {
1738
+ throw argumentError(`resource[${index}] reference_key 只能用于 usage=reference`);
1739
+ }
1740
+ if (usage !== 'keyframe' && normalized.order != null) {
1741
+ throw argumentError(`resource[${index}] order 只能用于 usage=keyframe`);
1742
+ }
1743
+ if (usage !== 'keyframe' && duration != null) {
1744
+ throw argumentError(`resource[${index}] duration 只能用于 usage=keyframe`);
1745
+ }
1746
+ if (usage !== 'keyframe' && normalized.prompt) {
1747
+ throw argumentError(`resource[${index}] prompt 只能用于 usage=keyframe`);
1748
+ }
1749
+ if (usage === 'keyframe' && resourceSource.kind === 'asset_id') {
1750
+ throw argumentError(`resource[${index}] keyframe 暂只支持 url,本地文件会自动上传为 url`);
1751
+ }
1752
+ if (type === 'subject' && usage !== 'reference') {
1753
+ throw argumentError(`resource[${index}] type=subject 只能用于 usage=reference`);
1754
+ }
1755
+ if (type === 'subject' && !referenceKey) {
1756
+ throw argumentError(`resource[${index}] type=subject 时 reference_key 不能为空`);
1757
+ }
1758
+ if (type === 'subject' && resourceSource.kind !== 'asset_id') {
1759
+ throw argumentError(`resource[${index}] type=subject 时 source.kind 必须为 asset_id`);
1760
+ }
1761
+ if (usage === 'keyframe') {
1762
+ if (!Number.isInteger(normalized.order) || normalized.order <= 0) {
1763
+ throw argumentError(`resource[${index}] keyframe 必须使用正整数 order,例如 image:keyframe#1=./k1.png`);
1764
+ }
1765
+ if (duration != null && duration < 0) {
1766
+ throw argumentError(`resource[${index}] keyframe duration 不能为负数`);
1767
+ }
1768
+ }
1769
+ return normalized;
1770
+ }
1771
+
1772
+ function assertAllowedResourceObjectKeys(source, index) {
1773
+ for (const key of Object.keys(source)) {
1774
+ if (!RESOURCE_OBJECT_KEYS.has(key)) {
1775
+ throw argumentError(
1776
+ `resource[${index}] JSON 对象存在未知字段:${key}`,
1777
+ 'JSON 素材只接受 type、usage、reference_key、source、order、prompt、duration。',
1778
+ );
1779
+ }
1780
+ }
1781
+ if (source.source != null) {
1782
+ if (!source.source || typeof source.source !== 'object' || Array.isArray(source.source)) {
1783
+ throw argumentError(`resource[${index}] source 必须是 JSON 对象`);
1784
+ }
1785
+ for (const key of Object.keys(source.source)) {
1786
+ if (!RESOURCE_SOURCE_KEYS.has(key)) {
1787
+ throw argumentError(
1788
+ `resource[${index}] source 存在未知字段:${key}`,
1789
+ 'source 只接受 kind、value。',
1790
+ );
1791
+ }
1792
+ }
1793
+ }
1794
+ }
1795
+
1796
+ function normalizeResourceDuration(value, index) {
1797
+ if (value == null || value === '') return null;
1798
+ const duration = Number(value);
1799
+ if (!Number.isFinite(duration)) {
1800
+ throw argumentError(`resource[${index}] duration 必须是数字`);
1801
+ }
1802
+ return duration;
1803
+ }
1804
+
1805
+ async function collectResourceSpecs(kwargs = {}, options = {}) {
1806
+ const items = [];
1807
+ for (const item of parseListArg(kwargs.resource)) items.push(item);
1808
+ if (Array.isArray(kwargs.resources)) items.push(...kwargs.resources);
1809
+ const resourcesJson = await readJsonMaybeFile(kwargs.resourcesJson, null).catch((error) => {
1810
+ throw argumentError(`resources-json 解析失败:${error.message}`);
1811
+ });
1812
+ if (Array.isArray(resourcesJson)) items.push(...resourcesJson);
1813
+ return items.map((item, index) => normalizeResourceObject(item, index)).filter((item) => {
1814
+ if (options.kind !== 'image') return true;
1815
+ if (item.type !== 'image') {
1816
+ throw argumentError('图片任务 resource 只支持 type=image');
1817
+ }
1818
+ if (item.usage !== 'reference') {
1819
+ throw argumentError('图片任务 resource 只支持 usage=reference');
1820
+ }
1821
+ if (item._source.kind !== 'url') {
1822
+ throw argumentError('图片任务 resource 暂只支持 url,本地文件会自动上传为 url');
1823
+ }
1824
+ return true;
1825
+ });
1826
+ }
1827
+
1828
+ function isRemoteOrBackendPath(value) {
1829
+ const text = trimToNull(value);
1830
+ if (!text) return false;
1831
+ return /^https?:\/\//i.test(text)
1832
+ || /^[a-z][a-z0-9+.-]*:\/\//i.test(text)
1833
+ || text.startsWith('material/')
1834
+ || text.startsWith('/material/');
1835
+ }
1836
+
1837
+ async function resolveResourceFileValue(resource, options = {}) {
1838
+ if (resource.type === 'subject') {
1839
+ if (resource._source.kind !== 'asset_id') throw argumentError('subject resource 必须使用 asset_id,例如 subject:reference:hero=asset:element_123');
1840
+ return {
1841
+ resource: {
1842
+ type: resource.type,
1843
+ usage: resource.usage,
1844
+ ...(resource.reference_key ? { reference_key: resource.reference_key } : {}),
1845
+ source: resource._source,
1846
+ },
1847
+ upload: null,
1848
+ localFile: null,
1849
+ };
1850
+ }
1851
+ const base = {
1852
+ type: resource.type,
1853
+ usage: resource.usage,
1854
+ ...(resource.reference_key ? { reference_key: resource.reference_key } : {}),
1855
+ ...(resource.order ? { order: resource.order } : {}),
1856
+ ...(resource.prompt ? { prompt: resource.prompt } : {}),
1857
+ ...(resource.duration != null ? { duration: resource.duration } : {}),
1858
+ };
1859
+ if (resource._source.kind === 'asset_id') {
1860
+ return { resource: { ...base, source: resource._source }, upload: null, localFile: null };
1861
+ }
1862
+ const value = resource._source.value;
1863
+ if (isRemoteOrBackendPath(value)) {
1864
+ return { resource: { ...base, source: { kind: 'url', value } }, upload: null, localFile: null };
1865
+ }
1866
+ const inspected = await inspectLocalFile(value);
1867
+ if (!inspected.exists) {
1868
+ throw argumentError(
1869
+ `资源文件不存在:${value}`,
1870
+ 'source.kind=url 只接受完整 http(s) URL、material backendPath,或当前工作目录下存在的本地文件路径。',
1871
+ );
1872
+ }
1873
+ if (options.dryRun) {
1874
+ return {
1875
+ resource: { ...base, source: { kind: 'url', value: dryRunBackendPath(inspected.filePath, options.sceneType) } },
1876
+ upload: null,
1877
+ localFile: inspected,
1878
+ };
1879
+ }
1880
+ const upload = await uploadLocalFile(inspected.filePath, { sceneType: options.sceneType });
1881
+ return {
1882
+ resource: { ...base, source: { kind: 'url', value: upload.backendPath } },
1883
+ upload,
1884
+ localFile: inspected,
1885
+ };
1886
+ }
1887
+
1888
+ async function resolveResources(kwargs = {}, options = {}) {
1889
+ const specs = await collectResourceSpecs(kwargs, options);
1890
+ const resources = [];
1891
+ const uploads = [];
1892
+ const localFiles = [];
1893
+ for (const spec of specs) {
1894
+ const resolved = await resolveResourceFileValue(spec, options);
1895
+ resources.push(resolved.resource);
1896
+ if (resolved.upload) uploads.push(resolved.upload);
1897
+ if (resolved.localFile) localFiles.push(resolved.localFile);
1898
+ }
1899
+ return { resources, uploads, localFiles };
1900
+ }
1901
+
1902
+ function extractPromptReferenceKeys(prompt) {
1903
+ const keys = new Set();
1904
+ const matcher = /<<<([^<>\s]+)>>>/g;
1905
+ const text = String(prompt ?? '');
1906
+ let match;
1907
+ while ((match = matcher.exec(text)) !== null) {
1908
+ keys.add(match[1]);
1909
+ }
1910
+ return keys;
1911
+ }
1912
+
1913
+ function assertVideoReferenceKeysUsed(prompt, resources = []) {
1914
+ const declaredKeys = new Set(resources
1915
+ .filter((resource) => resource?.usage === 'reference' && trimToNull(resource.reference_key))
1916
+ .map((resource) => trimToNull(resource.reference_key)));
1917
+ if (!declaredKeys.size) return;
1918
+ const promptKeys = extractPromptReferenceKeys(prompt);
1919
+ for (const key of declaredKeys) {
1920
+ if (!promptKeys.has(key)) {
1921
+ throw argumentError(
1922
+ `reference_key 未在 prompt 中引用:${key}`,
1923
+ `带 key 的参考资源必须在 prompt 中出现 <<<${key}>>>;如果只是普通参考素材,请去掉 :${key}。`,
1924
+ );
1925
+ }
1926
+ }
1927
+ for (const key of promptKeys) {
1928
+ if (!declaredKeys.has(key)) {
1929
+ throw argumentError(`prompt 引用了未声明的资源占位符:<<<${key}>>>`);
1930
+ }
1931
+ }
1932
+ }
1933
+
1934
+ async function buildImageRequest(kwargs = {}, options = {}) {
1935
+ const dryRun = Boolean(options.dryRun);
1936
+ const model = resolveTaskModel('image', kwargs);
1937
+ const prompt = trimToNull(kwargs.prompt) ?? '';
1938
+ if (!prompt) {
1939
+ throw argumentError('缺少生图 prompt', '传 --prompt "..."。');
1940
+ }
1941
+ const resolvedResources = await resolveResources(kwargs, {
1942
+ dryRun,
1943
+ kind: 'image',
1944
+ sceneType: TASK_UPLOAD_SCENE.IMAGE_CREATE,
1945
+ });
1946
+ const defaultParams = {
1947
+ prompt,
1948
+ resources: resolvedResources.resources,
1949
+ };
1950
+ if (kwargs.ratio != null && kwargs.ratio !== '') defaultParams.ratio = kwargs.ratio;
1951
+ if (kwargs.quality != null && kwargs.quality !== '') defaultParams.quality = kwargs.quality;
1952
+ if (kwargs.generateNum != null && kwargs.generateNum !== '') {
1953
+ defaultParams.generate_num = parseIntegerParam(kwargs.generateNum, '--generate-num', 1);
1954
+ }
1955
+ const promptParams = normalizeUnifiedPromptParams(defaultParams);
1956
+ const projectGroupNo = await resolveProjectGroupNo(kwargs.projectGroupNo, { allowNull: dryRun, noNetwork: dryRun, noSave: dryRun });
1957
+ const customBizId = options.includeCustomBizId === false ? null : resolveCustomBizId(kwargs.customBizId);
1958
+ return {
1959
+ model,
1960
+ projectGroupNo,
1961
+ uploads: resolvedResources.uploads,
1962
+ localFiles: resolvedResources.localFiles,
1963
+ request: {
1964
+ requestSource: REQUEST_SOURCE_CLI,
1965
+ modelGroupCode: model.modelGroupCode,
1966
+ ...(customBizId ? { customBizId } : {}),
1967
+ promptParams,
1968
+ ...(projectGroupNo ? { projectGroupNo } : {}),
1969
+ },
1970
+ };
1971
+ }
1972
+
1973
+ function extractPointCost(payload) {
1974
+ if (typeof payload === 'number') return payload;
1975
+ return toNumberOrNull(payload?.point ?? payload?.pointNo ?? payload?.cost ?? payload);
1976
+ }
1977
+
1978
+ async function pointEstimate(pointCost, projectGroupNo) {
1979
+ const snapshot = projectGroupNo ? await creditsBalance({ projectGroupNo }).catch(() => null) : null;
1980
+ const normalizedPointCost = extractPointCost(pointCost);
1981
+ const projectPointBalance = toNumberOrNull(snapshot?.projectPointBalance);
1982
+ const teamPointBalance = toNumberOrNull(snapshot?.teamPointBalance);
1983
+ return {
1984
+ pointCost: normalizedPointCost,
1985
+ teamPointBalance,
1986
+ projectPointBalance,
1987
+ projectPointMax: snapshot?.projectPointMax ?? null,
1988
+ teamPointRemainingAfter: normalizedPointCost != null && teamPointBalance != null ? teamPointBalance - normalizedPointCost : null,
1989
+ projectPointRemainingAfter: normalizedPointCost != null && projectPointBalance != null ? projectPointBalance - normalizedPointCost : null,
1990
+ };
1991
+ }
1992
+
1993
+ export async function imageFee(kwargs = {}) {
1994
+ if (toBool(kwargs.dryRun)) {
1995
+ const built = await buildImageRequest(kwargs, { dryRun: true, includeCustomBizId: false });
1996
+ return { dryRun: true, action: 'image fee', request: built.request };
1997
+ }
1998
+ const built = await buildImageRequest(kwargs, { includeCustomBizId: false });
1999
+ const payload = await awbApi.fetchImageFee(built.request);
2000
+ return {
2001
+ data: payload,
2002
+ ...(await pointEstimate(payload, built.projectGroupNo)),
2003
+ };
2004
+ }
2005
+
2006
+ function normalizeCreateUploads(uploads = []) {
2007
+ return uploads.map((item) => compactRecord({
2008
+ filePath: item.filePath,
2009
+ fileName: item.fileName,
2010
+ exists: item.exists,
2011
+ size: item.size,
2012
+ mimeType: item.mimeType,
2013
+ width: item.width,
2014
+ height: item.height,
2015
+ format: item.format,
2016
+ backendPath: item.backendPath,
2017
+ url: item.url,
2018
+ }));
2019
+ }
2020
+
2021
+ function extractCreatedTaskId(payload, flat = {}) {
2022
+ if (typeof payload === 'string' || typeof payload === 'number') return String(payload);
2023
+ if (!payload || typeof payload !== 'object') return null;
2024
+ return payload.taskId
2025
+ ?? payload.id
2026
+ ?? payload.task_id
2027
+ ?? flat.taskId
2028
+ ?? flat.id
2029
+ ?? flat.task_id
2030
+ ?? null;
2031
+ }
2032
+
2033
+ function normalizeCreatedTask(payload, extra = {}) {
2034
+ const flat = payload && typeof payload === 'object' ? flattenRecord(payload) : {};
2035
+ const taskId = extractCreatedTaskId(payload, flat);
2036
+ return compactRecord({
2037
+ ...(taskId ? { taskId: String(taskId) } : {}),
2038
+ ...flat,
2039
+ ...extra,
2040
+ });
2041
+ }
2042
+
2043
+ export async function imageCreate(kwargs = {}) {
2044
+ if (toBool(kwargs.dryRun)) {
2045
+ const built = await buildImageRequest(kwargs, { dryRun: true });
2046
+ return compactRecord({
2047
+ dryRun: true,
2048
+ action: 'image create',
2049
+ request: built.request,
2050
+ ...(built.localFiles.length ? { localFiles: built.localFiles } : {}),
2051
+ });
2052
+ }
2053
+ ensureConfirmed(kwargs, '正式生图会消耗积分,需要确认', { action: 'image create' });
2054
+ const built = await buildImageRequest(kwargs);
2055
+ const feePayload = await awbApi.fetchImageFee(built.request).catch(() => null);
2056
+ const estimate = await pointEstimate(feePayload, built.projectGroupNo).catch(() => ({}));
2057
+ const payload = await awbApi.createImageTask(built.request);
2058
+ const result = normalizeCreatedTask(payload, {
2059
+ ...estimate,
2060
+ projectGroupNo: built.projectGroupNo,
2061
+ modelGroupCode: built.request.modelGroupCode,
2062
+ ...(built.uploads.length ? { uploads: normalizeCreateUploads(built.uploads) } : {}),
2063
+ });
2064
+ await appendTaskRecord(kwargs, {
2065
+ taskId: result.taskId,
2066
+ taskType: 'IMAGE_CREATE',
2067
+ projectGroupNo: built.projectGroupNo,
2068
+ modelGroupCode: built.request.modelGroupCode,
2069
+ promptSummary: taskPromptSummary({ prompt: built.request.promptParams?.prompt }),
2070
+ });
2071
+ if (toInt(kwargs.waitSeconds, 0) > 0 && result.taskId) {
2072
+ return {
2073
+ ...result,
2074
+ waited: await waitTask({
2075
+ taskId: result.taskId,
2076
+ taskType: 'IMAGE_CREATE',
2077
+ projectGroupNo: built.projectGroupNo,
2078
+ waitSeconds: kwargs.waitSeconds,
2079
+ pollIntervalMs: kwargs.pollIntervalMs,
2080
+ }),
2081
+ };
2082
+ }
2083
+ return {
2084
+ ...result,
2085
+ nextCommand: result.taskId
2086
+ ? `lj-awb task wait --task-id ${result.taskId} --task-type IMAGE_CREATE --project-group-no ${built.projectGroupNo} -f json`
2087
+ : null,
2088
+ };
2089
+ }
2090
+
2091
+ async function buildVideoRequest(kwargs = {}, options = {}) {
2092
+ const dryRun = Boolean(options.dryRun);
2093
+ const model = resolveTaskModel('video', kwargs);
2094
+ const resolvedResources = await resolveResources(kwargs, {
2095
+ dryRun,
2096
+ kind: 'video',
2097
+ sceneType: TASK_UPLOAD_SCENE.VIDEO_CREATE,
2098
+ });
2099
+ const prompt = trimToNull(kwargs.prompt) ?? '';
2100
+ if (!prompt && !resolvedResources.resources.length) {
2101
+ throw argumentError('缺少视频生成输入', '至少传 --prompt 或 --resource。');
2102
+ }
2103
+ assertVideoReferenceKeysUsed(prompt, resolvedResources.resources);
2104
+ const defaultParams = {
2105
+ prompt,
2106
+ resources: resolvedResources.resources,
2107
+ };
2108
+ if (kwargs.duration != null && kwargs.duration !== '') {
2109
+ defaultParams.duration = parseIntegerParam(kwargs.duration, '--duration', 0);
2110
+ }
2111
+ if (kwargs.ratio != null && kwargs.ratio !== '') defaultParams.ratio = kwargs.ratio;
2112
+ if (kwargs.quality != null && kwargs.quality !== '') defaultParams.quality = kwargs.quality;
2113
+ if (kwargs.needAudio != null && kwargs.needAudio !== '') defaultParams.need_audio = toBool(kwargs.needAudio);
2114
+ const promptParams = normalizeUnifiedPromptParams(defaultParams);
2115
+ const projectGroupNo = await resolveProjectGroupNo(kwargs.projectGroupNo, { allowNull: dryRun, noNetwork: dryRun, noSave: dryRun });
2116
+ const customBizId = options.includeCustomBizId === false ? null : resolveCustomBizId(kwargs.customBizId);
2117
+ return {
2118
+ model,
2119
+ projectGroupNo,
2120
+ uploads: resolvedResources.uploads,
2121
+ localFiles: resolvedResources.localFiles,
2122
+ request: {
2123
+ requestSource: REQUEST_SOURCE_CLI,
2124
+ modelGroupCode: model.modelGroupCode,
2125
+ ...(customBizId ? { customBizId } : {}),
2126
+ promptParams,
2127
+ ...(projectGroupNo ? { projectGroupNo } : {}),
2128
+ },
2129
+ };
2130
+ }
2131
+
2132
+ export async function videoFee(kwargs = {}) {
2133
+ if (toBool(kwargs.dryRun)) {
2134
+ const built = await buildVideoRequest(kwargs, { dryRun: true, includeCustomBizId: false });
2135
+ return { dryRun: true, action: 'video fee', request: built.request };
2136
+ }
2137
+ const built = await buildVideoRequest(kwargs, { includeCustomBizId: false });
2138
+ const payload = await awbApi.fetchVideoFee(built.request);
2139
+ return {
2140
+ data: payload,
2141
+ ...(await pointEstimate(payload, built.projectGroupNo)),
2142
+ };
2143
+ }
2144
+
2145
+ export async function videoCreate(kwargs = {}) {
2146
+ if (toBool(kwargs.dryRun)) {
2147
+ const built = await buildVideoRequest(kwargs, { dryRun: true });
2148
+ return compactRecord({
2149
+ dryRun: true,
2150
+ action: 'video create',
2151
+ request: built.request,
2152
+ ...(built.localFiles.length ? { localFiles: built.localFiles } : {}),
2153
+ });
2154
+ }
2155
+ ensureConfirmed(kwargs, '正式生视频会消耗积分,需要确认', { action: 'video create' });
2156
+ const built = await buildVideoRequest(kwargs);
2157
+ const feePayload = await awbApi.fetchVideoFee(built.request).catch(() => null);
2158
+ const estimate = await pointEstimate(feePayload, built.projectGroupNo).catch(() => ({}));
2159
+ const payload = await awbApi.createVideoTask(built.request);
2160
+ const result = normalizeCreatedTask(payload, {
2161
+ ...estimate,
2162
+ projectGroupNo: built.projectGroupNo,
2163
+ modelGroupCode: built.request.modelGroupCode,
2164
+ ...(built.uploads.length ? { uploads: normalizeCreateUploads(built.uploads) } : {}),
2165
+ });
2166
+ await appendTaskRecord(kwargs, {
2167
+ taskId: result.taskId,
2168
+ taskType: 'VIDEO_GROUP',
2169
+ projectGroupNo: built.projectGroupNo,
2170
+ modelGroupCode: built.request.modelGroupCode,
2171
+ promptSummary: taskPromptSummary({ prompt: built.request.promptParams?.prompt }),
2172
+ });
2173
+ if (toInt(kwargs.waitSeconds, 0) > 0 && result.taskId) {
2174
+ return {
2175
+ ...result,
2176
+ waited: await waitTask({
2177
+ taskId: result.taskId,
2178
+ taskType: 'VIDEO_GROUP',
2179
+ projectGroupNo: built.projectGroupNo,
2180
+ waitSeconds: kwargs.waitSeconds,
2181
+ pollIntervalMs: kwargs.pollIntervalMs,
2182
+ }),
2183
+ };
2184
+ }
2185
+ return {
2186
+ ...result,
2187
+ nextCommand: result.taskId
2188
+ ? `lj-awb task wait --task-id ${result.taskId} --task-type VIDEO_GROUP --project-group-no ${built.projectGroupNo} -f json`
2189
+ : null,
2190
+ };
2191
+ }
2192
+
2193
+ export async function loadBatchItems(inputFile, mode = 'generic') {
2194
+ const filePath = trimToNull(inputFile);
2195
+ if (!filePath) throw argumentError('缺少批量输入文件', '传 --input-file <json|jsonl|txt>。');
2196
+ const text = await fs.readFile(path.resolve(filePath), 'utf8');
2197
+ const trimmed = text.trim();
2198
+ if (!trimmed) return [];
2199
+ if (trimmed.startsWith('[')) {
2200
+ const parsed = JSON.parse(trimmed);
2201
+ if (!Array.isArray(parsed)) throw argumentError('批量 JSON 必须是数组');
2202
+ return parsed;
2203
+ }
2204
+ const lines = trimmed.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
2205
+ if (lines.every((line) => line.startsWith('{'))) return lines.map((line) => JSON.parse(line));
2206
+ if (lines.length === 1 && lines[0].startsWith('{')) {
2207
+ const parsed = JSON.parse(lines[0]);
2208
+ if (Array.isArray(parsed.items)) return parsed.items;
2209
+ return [parsed];
2210
+ }
2211
+ return lines.map((line) => (mode === 'subject' ? { name: line } : { prompt: line }));
2212
+ }
2213
+
2214
+ const IMAGE_BATCH_ITEM_KEYS = new Set([
2215
+ 'prompt',
2216
+ 'ratio',
2217
+ 'quality',
2218
+ 'generate_num',
2219
+ 'generateNum',
2220
+ 'resource',
2221
+ 'resources',
2222
+ 'resourcesJson',
2223
+ 'customBizId',
2224
+ ]);
2225
+ const VIDEO_BATCH_ITEM_KEYS = new Set([
2226
+ 'prompt',
2227
+ 'ratio',
2228
+ 'quality',
2229
+ 'duration',
2230
+ 'need_audio',
2231
+ 'needAudio',
2232
+ 'resource',
2233
+ 'resources',
2234
+ 'resourcesJson',
2235
+ 'customBizId',
2236
+ ]);
2237
+
2238
+ function normalizeTaskBatchItem(item, kind, index) {
2239
+ if (!item || typeof item !== 'object' || Array.isArray(item)) {
2240
+ throw argumentError(`批量输入第 ${index + 1} 项必须是 JSON 对象或纯文本 prompt`);
2241
+ }
2242
+ const allowedKeys = kind === 'image' ? IMAGE_BATCH_ITEM_KEYS : VIDEO_BATCH_ITEM_KEYS;
2243
+ const unknownKeys = Object.keys(item).filter((key) => !allowedKeys.has(key));
2244
+ if (unknownKeys.length) {
2245
+ throw argumentError(
2246
+ `批量输入第 ${index + 1} 项存在未知字段:${unknownKeys.join(', ')}`,
2247
+ kind === 'image'
2248
+ ? '生图批量项只接受 prompt、ratio、quality、generate_num、resources、resource、customBizId。'
2249
+ : '生视频批量项只接受 prompt、ratio、quality、duration、need_audio、resources、resource、customBizId。',
2250
+ );
2251
+ }
2252
+ const next = { ...item };
2253
+ if (next.generate_num != null && next.generateNum == null) next.generateNum = next.generate_num;
2254
+ if (next.need_audio != null && next.needAudio == null) next.needAudio = next.need_audio;
2255
+ return next;
2256
+ }
2257
+
2258
+ async function runConcurrent(items, limit, worker) {
2259
+ const safeLimit = Math.max(1, toInt(limit, 1));
2260
+ const results = new Array(items.length);
2261
+ let nextIndex = 0;
2262
+ async function runOne() {
2263
+ while (nextIndex < items.length) {
2264
+ const index = nextIndex;
2265
+ nextIndex += 1;
2266
+ try {
2267
+ results[index] = await worker(items[index], index);
2268
+ } catch (error) {
2269
+ results[index] = {
2270
+ inputIndex: index,
2271
+ status: 'error',
2272
+ error: error instanceof Error ? error.message : String(error),
2273
+ };
2274
+ }
2275
+ }
2276
+ }
2277
+ await Promise.all(Array.from({ length: Math.min(safeLimit, Math.max(items.length, 1)) }, runOne));
2278
+ return results;
2279
+ }
2280
+
2281
+ export async function imageCreateBatch(kwargs = {}) {
2282
+ const items = (await loadBatchItems(kwargs.inputFile, 'image'))
2283
+ .map((item, index) => normalizeTaskBatchItem(item, 'image', index));
2284
+ if (toBool(kwargs.dryRun)) {
2285
+ const results = [];
2286
+ for (const [index, item] of items.entries()) {
2287
+ results.push({ inputIndex: index, ...(await imageCreate({ ...kwargs, ...item, dryRun: true })) });
2288
+ }
2289
+ return { dryRun: true, count: items.length, results };
2290
+ }
2291
+ ensureConfirmed(kwargs, '批量生图会多次消耗积分,需要确认', { action: 'image create-batch', count: items.length });
2292
+ const results = await runConcurrent(items, kwargs.concurrency ?? 1, async (item, index) => ({
2293
+ inputIndex: index,
2294
+ status: 'success',
2295
+ ...(await imageCreate({ ...kwargs, ...item, yes: true, dryRun: false })),
2296
+ }));
2297
+ return { count: items.length, results };
2298
+ }
2299
+
2300
+ export async function videoCreateBatch(kwargs = {}) {
2301
+ const items = (await loadBatchItems(kwargs.inputFile, 'video'))
2302
+ .map((item, index) => normalizeTaskBatchItem(item, 'video', index));
2303
+ if (toBool(kwargs.dryRun)) {
2304
+ const results = [];
2305
+ for (const [index, item] of items.entries()) {
2306
+ results.push({ inputIndex: index, ...(await videoCreate({ ...kwargs, ...item, dryRun: true })) });
2307
+ }
2308
+ return { dryRun: true, count: items.length, results };
2309
+ }
2310
+ ensureConfirmed(kwargs, '批量生视频会多次消耗积分,需要确认', { action: 'video create-batch', count: items.length });
2311
+ const results = await runConcurrent(items, kwargs.concurrency ?? 1, async (item, index) => ({
2312
+ inputIndex: index,
2313
+ status: 'success',
2314
+ ...(await videoCreate({ ...kwargs, ...item, yes: true, dryRun: false })),
2315
+ }));
2316
+ return { count: items.length, results };
2317
+ }
2318
+
2319
+ function taskPromptSummary(input = {}) {
2320
+ const text = trimToNull(input.prompt ?? input.taskPrompt);
2321
+ return text ? text.slice(0, 160) : null;
2322
+ }
2323
+
2324
+ function resolveTaskRecordFile(kwargs = {}) {
2325
+ const filePath = trimToNull(kwargs.taskRecordFile ?? DEFAULT_TASK_RECORD_FILE_ENV);
2326
+ return filePath ? path.resolve(filePath) : null;
2327
+ }
2328
+
2329
+ async function appendTaskRecord(kwargs, record) {
2330
+ const filePath = resolveTaskRecordFile(kwargs);
2331
+ if (!filePath || !record?.taskId) return null;
2332
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
2333
+ await fs.appendFile(filePath, `${JSON.stringify({
2334
+ schemaVersion: 1,
2335
+ site: SITE,
2336
+ recordedAt: nowIso(),
2337
+ ...record,
2338
+ })}\n`, 'utf8');
2339
+ return filePath;
2340
+ }
2341
+
2342
+ function normalizeTask(payload, taskType = null, extra = {}) {
2343
+ const item = Array.isArray(payload) ? payload[0] : payload ?? {};
2344
+ const resultFileList = Array.isArray(item?.resultFileList) ? item.resultFileList : [];
2345
+ const resultFileDisplayList = Array.isArray(item?.resultFileDisplayList) ? item.resultFileDisplayList : [];
2346
+ const taskExt = item?.taskExt && typeof item.taskExt === 'object' ? item.taskExt : null;
2347
+ const originUrls = uniqueNonEmpty([
2348
+ ...parseListArg(taskExt?.ORIGIN_URL ?? taskExt?.originUrl ?? taskExt?.origin_url),
2349
+ ...parseListArg(item?.originUrl ?? item?.origin_url),
2350
+ ]);
2351
+ const resultUrls = uniqueNonEmpty([
2352
+ ...resultFileDisplayList,
2353
+ ...resultFileList,
2354
+ ...parseListArg(item?.resultUrl),
2355
+ ...parseListArg(item?.url),
2356
+ ]);
2357
+ const taskStatus = item?.taskStatus ?? item?.status ?? item?.state ?? null;
2358
+ return compactRecord({
2359
+ taskId: item?.taskId ?? extra.taskId ?? null,
2360
+ taskType: item?.taskType ?? taskType ?? extra.taskType ?? null,
2361
+ ...(extra.projectGroupNo ? { projectGroupNo: extra.projectGroupNo } : {}),
2362
+ taskStatus,
2363
+ isTerminal: isTerminalTaskStatus(taskStatus),
2364
+ modelGroupCode: item?.modelGroupCode ?? null,
2365
+ pointNo: item?.pointNo ?? null,
2366
+ gmtCreate: item?.gmtCreate ?? item?.createTime ?? item?.createdAt ?? null,
2367
+ gmtModified: item?.gmtModified ?? item?.updateTime ?? item?.updatedAt ?? null,
2368
+ promptSummary: taskPromptSummary({ prompt: item?.taskPrompt }),
2369
+ resultCount: resultUrls.length,
2370
+ ...(resultUrls.length ? { resultUrls } : {}),
2371
+ ...(originUrls.length ? { originUrls } : {}),
2372
+ errorMessage: item?.errorMsg ?? item?.resultMsg ?? item?.message ?? null,
2373
+ ...extra,
2374
+ });
2375
+ }
2376
+
2377
+ export async function taskStatus(kwargs = {}) {
2378
+ const taskId = requireValue(kwargs, 'taskId', 'task-id');
2379
+ const taskType = normalizeFeedTaskType(kwargs.taskType ?? 'IMAGE_CREATE');
2380
+ const kind = taskTypeToStatusKind(taskType);
2381
+ const payload = kind === 'video' ? await awbApi.fetchVideoTask(taskId) : await awbApi.fetchImageTask(taskId);
2382
+ return normalizeTask(payload, taskType, {
2383
+ taskId,
2384
+ taskType,
2385
+ ...(trimToNull(kwargs.projectGroupNo) ? { projectGroupNo: trimToNull(kwargs.projectGroupNo) } : {}),
2386
+ });
2387
+ }
2388
+
2389
+ export async function taskList(kwargs = {}) {
2390
+ const taskType = normalizeFeedTaskType(kwargs.taskType ?? 'IMAGE_CREATE');
2391
+ const projectGroupNo = await resolveProjectGroupNo(kwargs.projectGroupNo);
2392
+ const request = {
2393
+ taskType,
2394
+ minTime: toInt(kwargs.minTime, Date.now()),
2395
+ pageSize: Math.min(Math.max(toInt(kwargs.pageSize, 20), 1), 200),
2396
+ projectGroupNo,
2397
+ };
2398
+ const payload = await awbApi.fetchTaskFeed(request);
2399
+ const tasks = normalizeRows(payload).map((item) => normalizeTask(item, item?.taskType ?? taskType, {
2400
+ projectGroupNo,
2401
+ }));
2402
+ return {
2403
+ taskType,
2404
+ projectGroupNo,
2405
+ pageSize: request.pageSize,
2406
+ minTime: request.minTime,
2407
+ tasks,
2408
+ };
2409
+ }
2410
+
2411
+ export async function waitTask(kwargs = {}) {
2412
+ const taskId = requireValue(kwargs, 'taskId', 'task-id');
2413
+ const taskType = normalizeFeedTaskType(kwargs.taskType ?? 'IMAGE_CREATE');
2414
+ const waitSeconds = Math.max(0, toInt(kwargs.waitSeconds, 300));
2415
+ const pollIntervalMs = Math.max(500, toInt(kwargs.pollIntervalMs, 5000));
2416
+ const deadline = Date.now() + waitSeconds * 1000;
2417
+ let last = null;
2418
+ while (true) {
2419
+ last = await taskStatus({ ...kwargs, taskId, taskType }).catch(async (error) => {
2420
+ if (['network_error', 'auth_failed'].includes(error?.type)) {
2421
+ throw error;
2422
+ }
2423
+ const list = await taskList({ ...kwargs, taskId, taskType, pageSize: kwargs.pageSize ?? 100 }).catch((listError) => {
2424
+ if (['network_error', 'auth_failed'].includes(listError?.type)) {
2425
+ throw listError;
2426
+ }
2427
+ return { tasks: [] };
2428
+ });
2429
+ return list.tasks.find((item) => item.taskId === taskId) ?? null;
2430
+ });
2431
+ if (last?.isTerminal) {
2432
+ return { ...last, timedOut: false, waitedMs: waitSeconds * 1000 - Math.max(0, deadline - Date.now()) };
2433
+ }
2434
+ if (Date.now() >= deadline || waitSeconds === 0) break;
2435
+ await sleep(Math.min(pollIntervalMs, Math.max(0, deadline - Date.now())));
2436
+ }
2437
+ throw new LingjingAwbCliError('任务仍在运行,当前等待窗口已结束', {
2438
+ type: 'task_still_running',
2439
+ exitCode: 20,
2440
+ hint: '稍后再次运行 task wait,或增大 --wait-seconds。',
2441
+ details: {
2442
+ taskId,
2443
+ taskType,
2444
+ waitSeconds,
2445
+ last,
2446
+ },
2447
+ });
2448
+ }
2449
+
2450
+ export async function taskRecords(kwargs = {}) {
2451
+ const filePath = resolveTaskRecordFile(kwargs);
2452
+ if (!filePath) throw argumentError('缺少任务台账文件', '传 --task-record-file <path>,或设置 LINGJING_AWB_TASK_RECORD_FILE。');
2453
+ const text = await fs.readFile(filePath, 'utf8').catch((error) => {
2454
+ if (error?.code === 'ENOENT') return '';
2455
+ throw error;
2456
+ });
2457
+ const records = text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => JSON.parse(line));
2458
+ const latest = new Map();
2459
+ for (const record of records) {
2460
+ if (record?.taskId) latest.set(record.taskId, record);
2461
+ }
2462
+ const taskType = trimToNull(kwargs.taskType);
2463
+ const pendingOnly = toBool(kwargs.pendingOnly);
2464
+ const rows = [...latest.values()]
2465
+ .filter((record) => !taskType || normalizeFeedTaskType(record.taskType) === normalizeFeedTaskType(taskType))
2466
+ .filter((record) => !pendingOnly || !isTerminalTaskStatus(record.taskStatus))
2467
+ .sort((left, right) => String(right.recordedAt ?? '').localeCompare(String(left.recordedAt ?? '')))
2468
+ .slice(0, Math.max(1, toInt(kwargs.limit, 100)));
2469
+ return { filePath, count: rows.length, records: rows };
2470
+ }
2471
+
2472
+ export async function taskRecordPoll(kwargs = {}) {
2473
+ const source = await taskRecords({ ...kwargs, pendingOnly: kwargs.pendingOnly ?? true });
2474
+ const waitSeconds = Math.max(0, toInt(kwargs.waitSeconds, 0));
2475
+ const deadline = Date.now() + waitSeconds * 1000;
2476
+ const results = new Map();
2477
+ do {
2478
+ for (const record of source.records) {
2479
+ if (results.get(record.taskId)?.isTerminal) continue;
2480
+ const status = await taskStatus({
2481
+ taskId: record.taskId,
2482
+ taskType: record.taskType,
2483
+ projectGroupNo: record.projectGroupNo,
2484
+ }).catch((error) => ({
2485
+ taskId: record.taskId,
2486
+ taskType: record.taskType,
2487
+ isTerminal: false,
2488
+ error: error instanceof Error ? error.message : String(error),
2489
+ }));
2490
+ results.set(record.taskId, { ...record, ...status });
2491
+ }
2492
+ if ([...results.values()].every((item) => item.isTerminal)) break;
2493
+ if (Date.now() > deadline) break;
2494
+ await sleep(Math.max(500, toInt(kwargs.pollIntervalMs, 5000)));
2495
+ } while (waitSeconds > 0);
2496
+ return {
2497
+ filePath: source.filePath,
2498
+ count: source.records.length,
2499
+ timedOut: ![...results.values()].every((item) => item.isTerminal),
2500
+ records: [...results.values()],
2501
+ };
2502
+ }
2503
+
2504
+ function normalizeCosAssetPath(value) {
2505
+ const text = trimToNull(value);
2506
+ if (!text) return null;
2507
+ if (/^https?:\/\//i.test(text)) {
2508
+ try {
2509
+ return decodeURIComponent(new URL(text).pathname.replace(/^\/+/, ''));
2510
+ } catch {
2511
+ return text.replace(/^\/+/, '');
2512
+ }
2513
+ }
2514
+ return text.replace(/^\/+/, '');
2515
+ }
2516
+
2517
+ function normalizeAssetGroup(item = {}) {
2518
+ return {
2519
+ id: item?.id ?? item?.groupId ?? item?.assetGroupsId ?? null,
2520
+ groupId: item?.id ?? item?.groupId ?? item?.assetGroupsId ?? null,
2521
+ name: item?.name ?? item?.groupName ?? null,
2522
+ description: item?.description ?? null,
2523
+ projectName: item?.projectName ?? null,
2524
+ };
2525
+ }
2526
+
2527
+ function extractAssetGroupRows(payload) {
2528
+ return normalizeRows(payload).map((item) => normalizeAssetGroup(item));
2529
+ }
2530
+
2531
+ function parseJsonString(value) {
2532
+ if (value == null || value === '') return null;
2533
+ if (typeof value !== 'string') return value;
2534
+ try {
2535
+ return JSON.parse(value);
2536
+ } catch {
2537
+ return value;
2538
+ }
2539
+ }
2540
+
2541
+ function stringifyJsonObjectArg(value, fallback = '{}') {
2542
+ if (value === undefined || value === null || value === '') return fallback;
2543
+ const parsed = parseJsonArg(value, {});
2544
+ return typeof parsed === 'string' ? parsed : JSON.stringify(parsed);
2545
+ }
2546
+
2547
+ function normalizeAssetMatchRecord(item = {}, fallbackPartType = null) {
2548
+ return {
2549
+ assetId: item?.materialId ?? item?.assetId ?? item?.id ?? null,
2550
+ partType: item?.partType ?? fallbackPartType,
2551
+ imageUrl: item?.imageUrl ?? item?.image ?? item?.url ?? null,
2552
+ description: item?.description ?? null,
2553
+ score: toNumberOrNull(item?.matchScore ?? item?.score ?? item?.similarity),
2554
+ tags: parseJsonString(item?.tagInfo ?? item?.tags),
2555
+ };
2556
+ }
2557
+
2558
+ function normalizeAssetMatchRows(payload) {
2559
+ if (Array.isArray(payload)) {
2560
+ return payload
2561
+ .map((item) => normalizeAssetMatchRecord(item))
2562
+ .sort((left, right) => (right.score ?? -Infinity) - (left.score ?? -Infinity));
2563
+ }
2564
+ if (!payload || typeof payload !== 'object') return [];
2565
+
2566
+ const groupSpecs = [
2567
+ ['head', 'HEAD'],
2568
+ ['body', 'BODY'],
2569
+ ['realPersonHead', 'REAL_PERSON_HEAD'],
2570
+ ];
2571
+ const rows = [];
2572
+ for (const [key, partType] of groupSpecs) {
2573
+ for (const item of Array.isArray(payload[key]) ? payload[key] : []) {
2574
+ rows.push(normalizeAssetMatchRecord(item, partType));
2575
+ }
2576
+ }
2577
+ if (rows.length) {
2578
+ return rows.sort((left, right) => (right.score ?? -Infinity) - (left.score ?? -Infinity));
2579
+ }
2580
+ return normalizeRows(payload)
2581
+ .map((item) => normalizeAssetMatchRecord(item))
2582
+ .sort((left, right) => (right.score ?? -Infinity) - (left.score ?? -Infinity));
2583
+ }
2584
+
2585
+ function normalizeSubjectResourceUrls(list, key) {
2586
+ if (!Array.isArray(list)) return [];
2587
+ const upperKey = key.charAt(0).toUpperCase() + key.slice(1);
2588
+ return uniqueNonEmpty(list.map((item) => (typeof item === 'string' ? item : item?.[key] ?? item?.[upperKey])));
2589
+ }
2590
+
2591
+ function normalizeSubjectTagIds(tagList) {
2592
+ if (!Array.isArray(tagList)) return [];
2593
+ return uniqueNonEmpty(tagList.map((item) => (typeof item === 'string' ? item : item?.tagId ?? item?.id ?? item?.tagCode)));
2594
+ }
2595
+
2596
+ function normalizeSubjectRecord(item = {}) {
2597
+ const referList = Array.isArray(item?.elementReferList) ? item.elementReferList : [];
2598
+ const videoList = Array.isArray(item?.elementVideoList) ? item.elementVideoList : [];
2599
+ const elementId = item?.id ?? item?.subjectId ?? item?.elementId ?? null;
2600
+ const externalId = item?.externalId ?? item?.external_id ?? null;
2601
+ const name = item?.elementName ?? item?.name ?? item?.subjectName ?? null;
2602
+ return {
2603
+ subjectId: externalId ?? elementId,
2604
+ elementId,
2605
+ externalId,
2606
+ name,
2607
+ description: item?.elementDescription ?? item?.description ?? item?.subjectDesc ?? null,
2608
+ referenceType: item?.referenceType ?? null,
2609
+ modelCode: item?.modelCode ?? null,
2610
+ imageUrls: uniqueNonEmpty([
2611
+ item?.elementFrontalImage,
2612
+ item?.imageUrl,
2613
+ item?.coverUrl,
2614
+ ...normalizeSubjectResourceUrls(referList, 'imageUrl'),
2615
+ ]),
2616
+ videoUrls: uniqueNonEmpty([
2617
+ item?.videoUrl,
2618
+ ...normalizeSubjectResourceUrls(videoList, 'videoUrl'),
2619
+ ]),
2620
+ audioUrls: normalizeSubjectResourceUrls(referList, 'audioUrl'),
2621
+ tagIds: normalizeSubjectTagIds(item?.tagList),
2622
+ ...(trimToNull(item?.elementVoiceId) ? { voiceId: trimToNull(item.elementVoiceId) } : {}),
2623
+ ...(externalId && name ? { nextRefSubject: `${name}=${externalId}` } : {}),
2624
+ createdAt: item?.gmtCreate ?? item?.createdAt ?? null,
2625
+ };
2626
+ }
2627
+
2628
+ function paginateRows(rows, pageNumber, pageSize) {
2629
+ const actualPageNumber = Math.max(1, toInt(pageNumber, 1));
2630
+ const actualPageSize = Math.max(1, toInt(pageSize, 20));
2631
+ const start = (actualPageNumber - 1) * actualPageSize;
2632
+ return rows.slice(start, start + actualPageSize);
2633
+ }
2634
+
2635
+ export async function assetMatchActor(kwargs = {}) {
2636
+ const description = requireValue(kwargs, 'description');
2637
+ const tagJson = stringifyJsonObjectArg(kwargs.tagsJson ?? kwargs.tagJson);
2638
+ const payload = await awbApi.matchAssetMaterial({
2639
+ description,
2640
+ tagJson,
2641
+ tagWeight: toNumberOrNull(kwargs.tagWeight) ?? 0.5,
2642
+ descWeight: toNumberOrNull(kwargs.descWeight) ?? 0.5,
2643
+ });
2644
+ return {
2645
+ matches: normalizeAssetMatchRows(payload),
2646
+ ...(toBool(kwargs.includeRaw) ? { raw: payload } : {}),
2647
+ };
2648
+ }
2649
+
2650
+ export async function assetGroupList(kwargs = {}) {
2651
+ const payload = await awbApi.listAssetGroups({
2652
+ name: kwargs.name ?? '',
2653
+ pageNumber: toInt(kwargs.pageNumber, 1),
2654
+ pageSize: toInt(kwargs.pageSize, 20),
2655
+ ...(parseListArg(kwargs.groupIds).length ? { groupIds: parseListArg(kwargs.groupIds) } : {}),
2656
+ });
2657
+ return { groups: extractAssetGroupRows(payload), raw: toBool(kwargs.includeRaw) ? payload : undefined };
2658
+ }
2659
+
2660
+ export async function assetGroupGet(kwargs = {}) {
2661
+ const groupId = requireValue(kwargs, 'groupId', 'group-id');
2662
+ const payload = await awbApi.getAssetGroup(groupId);
2663
+ return payload && typeof payload === 'object' && !Array.isArray(payload)
2664
+ ? normalizeAssetGroup(payload)
2665
+ : extractAssetGroupRows(payload)[0] ?? { groupId };
2666
+ }
2667
+
2668
+ export async function assetGroupCreate(kwargs = {}) {
2669
+ const name = requireValue(kwargs, 'name');
2670
+ const body = {
2671
+ name,
2672
+ description: kwargs.description ?? '',
2673
+ projectName: kwargs.projectName ?? 'default',
2674
+ };
2675
+ if (toBool(kwargs.dryRun)) return { dryRun: true, action: 'asset group-create', request: body };
2676
+ ensureConfirmed(kwargs, '创建素材组是云端写入动作,需要确认', { action: 'asset group-create', body });
2677
+ const payload = await awbApi.createAssetGroup(body);
2678
+ return { created: true, groupId: payload?.id ?? payload?.groupId ?? payload ?? null, name, projectName: body.projectName };
2679
+ }
2680
+
2681
+ export async function assetGroupUpdate(kwargs = {}) {
2682
+ const groupId = requireValue(kwargs, 'groupId', 'group-id');
2683
+ const body = {};
2684
+ if (kwargs.name != null) body.name = kwargs.name;
2685
+ if (kwargs.description != null) body.description = kwargs.description;
2686
+ if (kwargs.projectName != null) body.projectName = kwargs.projectName;
2687
+ if (!Object.keys(body).length) throw argumentError('缺少素材组更新字段', '至少传 --name、--description 或 --project-name。');
2688
+ if (toBool(kwargs.dryRun)) return { dryRun: true, action: 'asset group-update', groupId, request: body };
2689
+ ensureConfirmed(kwargs, '更新素材组是云端写入动作,需要确认', { action: 'asset group-update', groupId, body });
2690
+ await awbApi.updateAssetGroup(groupId, body);
2691
+ return { updated: true, groupId, ...body };
2692
+ }
2693
+
2694
+ function extractAssetId(payload) {
2695
+ if (typeof payload === 'string') return payload;
2696
+ if (!payload || typeof payload !== 'object') return null;
2697
+ return payload.id ?? payload.assetId ?? payload.thirdAssetId ?? payload.resourceNo ?? payload.data?.id ?? null;
2698
+ }
2699
+
2700
+ export async function assetRegister(kwargs = {}) {
2701
+ const groupId = requireValue(kwargs, 'groupId', 'group-id');
2702
+ const name = requireValue(kwargs, 'name');
2703
+ const localFile = trimToNull(kwargs.file);
2704
+ const assetPath = trimToNull(kwargs.backendPath) ?? normalizeCosAssetPath(kwargs.url);
2705
+ if (!localFile && !assetPath) throw argumentError('缺少素材路径', '传 --file、--backend-path 或 --url。');
2706
+ if (toBool(kwargs.dryRun)) {
2707
+ return {
2708
+ dryRun: true,
2709
+ action: 'asset register',
2710
+ request: {
2711
+ assetGroupsId: groupId,
2712
+ url: localFile ? normalizeCosAssetPath(dryRunBackendPath(localFile, TASK_UPLOAD_SCENE.SUBJECT)) : assetPath,
2713
+ name,
2714
+ ...(kwargs.platform ? { platform: kwargs.platform } : {}),
2715
+ },
2716
+ localFile: localFile ? await inspectLocalFile(localFile) : null,
2717
+ };
2718
+ }
2719
+ ensureConfirmed(kwargs, '注册素材是云端写入动作,需要确认', { action: 'asset register', groupId, name });
2720
+ const uploaded = localFile ? await uploadLocalFile(localFile, { sceneType: TASK_UPLOAD_SCENE.SUBJECT }) : null;
2721
+ const body = {
2722
+ assetGroupsId: groupId,
2723
+ url: normalizeCosAssetPath(uploaded?.backendPath ?? assetPath),
2724
+ name,
2725
+ ...(kwargs.platform ? { platform: kwargs.platform } : {}),
2726
+ };
2727
+ const payload = await awbApi.registerAsset(body);
2728
+ return {
2729
+ registered: true,
2730
+ assetId: extractAssetId(payload),
2731
+ groupId,
2732
+ name,
2733
+ assetPath: body.url,
2734
+ ...(uploaded ? { upload: uploaded } : {}),
2735
+ };
2736
+ }
2737
+
2738
+ export async function subjectList(kwargs = {}) {
2739
+ const keyword = trimToNull(kwargs.keyword ?? kwargs.name);
2740
+ const payload = keyword
2741
+ ? await awbApi.listElementsByName(keyword)
2742
+ : await awbApi.listElements();
2743
+ const subjects = paginateRows(
2744
+ normalizeRows(payload).map((item) => normalizeSubjectRecord(item)),
2745
+ kwargs.pageNumber,
2746
+ kwargs.pageSize,
2747
+ );
2748
+ return {
2749
+ subjects,
2750
+ ...(toBool(kwargs.includeRaw) ? { raw: payload } : {}),
2751
+ };
2752
+ }
2753
+
2754
+ function subjectAssetSpecs(kwargs = {}) {
2755
+ return [
2756
+ { label: 'primary', idField: 'subjectId', file: kwargs.primaryFile ?? kwargs.threeViewFile, url: kwargs.primaryUrl ?? kwargs.threeViewUrl, isPrimary: true },
2757
+ { label: 'face', idField: 'faceViewId', file: kwargs.faceFile, url: kwargs.faceUrl },
2758
+ { label: 'side', idField: 'sideViewId', file: kwargs.sideFile, url: kwargs.sideUrl },
2759
+ { label: 'back', idField: 'backViewId', file: kwargs.backFile, url: kwargs.backUrl },
2760
+ ].filter((item) => trimToNull(item.file) || trimToNull(item.url));
2761
+ }
2762
+
2763
+ function subjectAssetPathForDryRun(item) {
2764
+ return item.file
2765
+ ? normalizeCosAssetPath(dryRunBackendPath(item.file, TASK_UPLOAD_SCENE.SUBJECT))
2766
+ : normalizeCosAssetPath(item.url);
2767
+ }
2768
+
2769
+ function tagListFromArg(value) {
2770
+ const parsed = parseJsonArg(value, []);
2771
+ if (!Array.isArray(parsed)) return [];
2772
+ return parsed
2773
+ .map((item) => (typeof item === 'string' ? { tagId: item } : { tagId: trimToNull(item?.tagId ?? item?.id ?? item?.tagCode) }))
2774
+ .filter((item) => item.tagId);
2775
+ }
2776
+
2777
+ function buildSubjectCreateBody(kwargs, specs, assets) {
2778
+ const name = requireValue(kwargs, 'name');
2779
+ const primary = assets.find((item) => item.isPrimary);
2780
+ const referAssets = assets.filter((item) => item.assetPath);
2781
+ return compactRecord({
2782
+ reqTaskId: trimToNull(kwargs.reqTaskId),
2783
+ modelCode: trimToNull(kwargs.modelCode),
2784
+ elementName: name,
2785
+ elementDescription: trimToNull(kwargs.description ?? kwargs.elementDescription),
2786
+ elementFrontalImage: primary?.assetPath ?? null,
2787
+ elementReferList: referAssets.map((item) => ({
2788
+ imageUrl: item.assetPath,
2789
+ audioUrl: null,
2790
+ })),
2791
+ referenceType: trimToNull(kwargs.referenceType) ?? 'image_refer',
2792
+ elementVoiceId: trimToNull(kwargs.voiceId ?? kwargs.elementVoiceId),
2793
+ tagList: tagListFromArg(kwargs.tagsJson ?? kwargs.tagJson),
2794
+ });
2795
+ }
2796
+
2797
+ function extractCreatedElementId(payload) {
2798
+ if (typeof payload === 'string') return payload;
2799
+ if (!payload || typeof payload !== 'object') return null;
2800
+ return payload.id ?? payload.elementId ?? payload.subjectId ?? payload.reqTaskId ?? payload.data?.id ?? payload.data?.elementId ?? null;
2801
+ }
2802
+
2803
+ async function fetchSubjectByReqTaskId(reqTaskId) {
2804
+ if (!reqTaskId) return null;
2805
+ const payload = await awbApi.getElementByReqTaskId(reqTaskId).catch(() => null);
2806
+ return payload && typeof payload === 'object' ? normalizeSubjectRecord(payload) : null;
2807
+ }
2808
+
2809
+ async function waitForSubjectExternalId(reqTaskId, options = {}) {
2810
+ const waitSeconds = Math.max(0, toInt(options.waitSeconds, 0));
2811
+ const pollIntervalMs = Math.max(500, toInt(options.pollIntervalMs, 2000));
2812
+ const deadline = Date.now() + waitSeconds * 1000;
2813
+ let latest = await fetchSubjectByReqTaskId(reqTaskId);
2814
+ while (waitSeconds > 0 && !latest?.externalId && Date.now() < deadline) {
2815
+ await sleep(pollIntervalMs);
2816
+ latest = await fetchSubjectByReqTaskId(reqTaskId);
2817
+ }
2818
+ return latest;
2819
+ }
2820
+
2821
+ function subjectWaitPayload(elementId, subject) {
2822
+ const externalId = subject?.externalId ?? null;
2823
+ return {
2824
+ elementId,
2825
+ subjectId: externalId ?? elementId,
2826
+ externalId,
2827
+ nextRefSubject: externalId && subject?.name ? `${subject.name}=${externalId}` : null,
2828
+ status: externalId ? 'ready' : 'pending_external_id',
2829
+ subject,
2830
+ };
2831
+ }
2832
+
2833
+ export async function subjectPublish(kwargs = {}) {
2834
+ const name = requireValue(kwargs, 'name');
2835
+ const specs = subjectAssetSpecs(kwargs);
2836
+ if (!specs.some((item) => item.isPrimary)) {
2837
+ throw argumentError('缺少主体主参考图', '传 --primary-file、--three-view-file、--primary-url 或 --three-view-url。');
2838
+ }
2839
+ if (toBool(kwargs.dryRun)) {
2840
+ const assets = specs.map((item) => ({
2841
+ label: item.label,
2842
+ file: item.file ?? null,
2843
+ url: item.url ?? null,
2844
+ assetPath: subjectAssetPathForDryRun(item),
2845
+ isPrimary: Boolean(item.isPrimary),
2846
+ dryRun: true,
2847
+ }));
2848
+ return {
2849
+ dryRun: true,
2850
+ action: 'subject publish',
2851
+ name,
2852
+ request: buildSubjectCreateBody(kwargs, specs, assets),
2853
+ assets,
2854
+ localFiles: await inspectLocalFiles(specs.map((item) => item.file).filter(Boolean)),
2855
+ nextRefSubject: `${name}=<externalId>`,
2856
+ };
2857
+ }
2858
+ ensureConfirmed(kwargs, '创建平台主体 element 是云端写入动作,需要确认', { action: 'subject publish', name });
2859
+ const assets = [];
2860
+ for (const spec of specs) {
2861
+ const uploaded = spec.file ? await uploadLocalFile(spec.file, { sceneType: TASK_UPLOAD_SCENE.SUBJECT }) : null;
2862
+ const assetPath = normalizeCosAssetPath(uploaded?.backendPath ?? spec.url);
2863
+ assets.push({
2864
+ label: spec.label,
2865
+ file: spec.file ?? null,
2866
+ url: spec.url ?? null,
2867
+ assetPath,
2868
+ isPrimary: Boolean(spec.isPrimary),
2869
+ ...(uploaded ? { upload: uploaded } : {}),
2870
+ });
2871
+ }
2872
+ const body = buildSubjectCreateBody(kwargs, specs, assets);
2873
+ const payload = await awbApi.createElement(body);
2874
+ const elementId = extractCreatedElementId(payload);
2875
+ if (!elementId) throw new LingjingAwbCliError('主体创建完成但未拿到 elementId', { type: 'api_error', exitCode: 1, details: payload });
2876
+ const subject = await fetchSubjectByReqTaskId(elementId);
2877
+ const waitPayload = subjectWaitPayload(elementId, subject);
2878
+ return {
2879
+ created: true,
2880
+ name,
2881
+ elementId,
2882
+ subjectId: waitPayload.subjectId,
2883
+ externalId: waitPayload.externalId,
2884
+ nextRefSubject: waitPayload.nextRefSubject,
2885
+ status: waitPayload.status,
2886
+ request: body,
2887
+ assets,
2888
+ subject,
2889
+ };
2890
+ }
2891
+
2892
+ export async function subjectWait(kwargs = {}) {
2893
+ const elementId = requireValue(kwargs, 'elementId', 'element-id');
2894
+ const subject = await waitForSubjectExternalId(elementId, kwargs);
2895
+ const payload = subjectWaitPayload(elementId, subject);
2896
+ if (!payload.externalId) {
2897
+ throw new LingjingAwbCliError('主体 externalId 尚未回填', {
2898
+ type: 'subject_still_pending',
2899
+ exitCode: 20,
2900
+ hint: '稍后重试 subject wait,或用 subject list --name 查询。',
2901
+ details: payload,
2902
+ });
2903
+ }
2904
+ return payload;
2905
+ }
2906
+
2907
+ export async function subjectPublishBatch(kwargs = {}) {
2908
+ const items = await loadBatchItems(kwargs.inputFile, 'subject');
2909
+ if (toBool(kwargs.dryRun)) {
2910
+ const results = [];
2911
+ for (const [index, item] of items.entries()) {
2912
+ results.push({ inputIndex: index, ...(await subjectPublish({ ...kwargs, ...item, dryRun: true })) });
2913
+ }
2914
+ return { dryRun: true, count: items.length, results };
2915
+ }
2916
+ ensureConfirmed(kwargs, '批量发布主体资产是云端写入动作,需要确认', { action: 'subject publish-batch', count: items.length });
2917
+ const results = await runConcurrent(items, kwargs.concurrency ?? 1, async (item, index) => ({
2918
+ inputIndex: index,
2919
+ status: 'success',
2920
+ ...(await subjectPublish({ ...kwargs, ...item, yes: true, dryRun: false })),
2921
+ }));
2922
+ return { count: items.length, results };
2923
+ }
2924
+
2925
+ export async function subtitleRemove(kwargs = {}) {
2926
+ const videoUrl = requireValue(kwargs, 'videoUrl', 'video-url');
2927
+ if (toBool(kwargs.dryRun)) {
2928
+ return { dryRun: true, action: 'video subtitle-remove', request: { input_type: 'url', video_url: videoUrl } };
2929
+ }
2930
+ ensureConfirmed(kwargs, '提交视频去字幕任务是云端写入动作,需要确认', { action: 'video subtitle-remove', videoUrl });
2931
+ const payload = await awbApi.createSubtitleRemoveTask({
2932
+ input_type: 'url',
2933
+ video_url: videoUrl,
2934
+ ...(kwargs.name ? { name: kwargs.name } : {}),
2935
+ ...(kwargs.taskId ? { task_id: kwargs.taskId } : {}),
2936
+ ...(kwargs.callbackUrl ? { callback_url: kwargs.callbackUrl } : {}),
2937
+ });
2938
+ return {
2939
+ submitted: true,
2940
+ remoteTaskId: payload?.remote_task_id ?? payload?.remoteTaskId ?? null,
2941
+ publicId: payload?.public_id ?? payload?.publicId ?? payload?.id ?? null,
2942
+ };
2943
+ }
2944
+
2945
+ export async function subtitleStatus(kwargs = {}) {
2946
+ const publicId = trimToNull(kwargs.publicId);
2947
+ const remoteTaskId = trimToNull(kwargs.remoteTaskId);
2948
+ if (!publicId && !remoteTaskId) throw argumentError('缺少去字幕任务 ID', '传 --public-id 或 --remote-task-id。');
2949
+ const payload = publicId
2950
+ ? await awbApi.fetchSubtitleTaskByPublicId(publicId)
2951
+ : await awbApi.fetchSubtitleTaskByRemoteId(remoteTaskId);
2952
+ const resultUrls = uniqueNonEmpty([
2953
+ ...parseListArg(payload?.result_url ?? payload?.resultUrl),
2954
+ ...parseListArg(payload?.output_url ?? payload?.outputUrl),
2955
+ ...parseListArg(payload?.url),
2956
+ ]);
2957
+ return compactRecord({
2958
+ publicId: publicId ?? payload?.public_id ?? payload?.publicId ?? payload?.id ?? null,
2959
+ remoteTaskId: remoteTaskId ?? payload?.remote_task_id ?? payload?.remoteTaskId ?? null,
2960
+ taskStatus: payload?.status ?? payload?.taskStatus ?? payload?.state ?? null,
2961
+ isTerminal: isTerminalTaskStatus(payload?.status ?? payload?.taskStatus ?? payload?.state),
2962
+ resultCount: resultUrls.length,
2963
+ ...(resultUrls.length ? { resultUrls } : {}),
2964
+ errorMessage: payload?.error_message ?? payload?.errorMessage ?? payload?.message ?? null,
2965
+ });
2966
+ }