@lingjingai/lj-awb-cli 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { LingjingAwbCliError, createEnvelope, toBool, toInt } from './common.js';
5
5
  import { registerAwbCommands } from './commands.js';
6
+ import { checkCliUpdate } from './update.js';
6
7
  import {
7
8
  formatCsvOutput,
8
9
  formatPrettyError,
@@ -210,6 +211,21 @@ function buildOutputContext(command, kwargs = {}) {
210
211
  };
211
212
  }
212
213
 
214
+ function updateCheckDisabledByEnv() {
215
+ return ['1', 'true', 'yes', 'on'].includes(String(process.env.LINGJING_AWB_DISABLE_UPDATE_CHECK || '').trim().toLowerCase())
216
+ || ['1', 'true', 'yes', 'on'].includes(String(process.env.AWB_DISABLE_UPDATE_CHECK || '').trim().toLowerCase());
217
+ }
218
+
219
+ function shouldSkipUpdateCheck(argv = [], commandName = '') {
220
+ if (updateCheckDisabledByEnv()) return true;
221
+ return commandName === 'update';
222
+ }
223
+
224
+ async function resolveUpdateNotice(argv = [], commandName = '', version = 'unknown') {
225
+ if (shouldSkipUpdateCheck(argv, commandName)) return null;
226
+ return await checkCliUpdate({ currentVersion: version }).catch(() => null);
227
+ }
228
+
213
229
  const OUTPUT_FORMAT_ALIASES = {
214
230
  agent: 'text',
215
231
  table: 'pretty',
@@ -480,6 +496,8 @@ const GROUP_EXAMPLES = {
480
496
  system: [
481
497
  'lj-awb doctor',
482
498
  'lj-awb doctor --verify',
499
+ 'lj-awb update --check',
500
+ 'lj-awb update',
483
501
  'lj-awb schema --brief -f json',
484
502
  'lj-awb schema -f json',
485
503
  'lj-awb schema --domain create -f json',
@@ -712,6 +730,7 @@ const REMOTE_WRITE_COMMANDS = new Set([
712
730
  ]);
713
731
 
714
732
  const LOCAL_STATE_WRITE_COMMANDS = new Set([
733
+ 'update',
715
734
  'auth login',
716
735
  'auth clear',
717
736
  'project use',
@@ -726,6 +745,7 @@ const NETWORK_CONDITIONAL_COMMANDS = new Set(['doctor', 'auth login']);
726
745
 
727
746
  const OUTPUT_KIND_BY_COMMAND = {
728
747
  doctor: 'environment_report',
748
+ update: 'update_result',
729
749
  schema: 'command_schema',
730
750
  'auth status': 'auth_status',
731
751
  'auth verify': 'auth_status',
@@ -891,9 +911,10 @@ function buildCommandSafety(command, optionKeys) {
891
911
  const costsPoints = COST_COMMANDS.has(name);
892
912
  const destructive = DESTRUCTIVE_COMMANDS.has(name);
893
913
  const supportsDryRun = optionKeys.has('dryRun');
914
+ const updateInstall = name === 'update';
894
915
  return {
895
- safeToAutoRun: !(remoteWrite || localStateWrite || requiresConfirmation || costsPoints || destructive),
896
- network: commandNetworkMode(name),
916
+ safeToAutoRun: !(remoteWrite || localStateWrite || requiresConfirmation || costsPoints || destructive || updateInstall),
917
+ network: updateInstall ? 'conditional' : commandNetworkMode(name),
897
918
  remoteWrite,
898
919
  localStateWrite,
899
920
  costsPoints,
@@ -1134,6 +1155,7 @@ function buildAgentContract() {
1134
1155
  workflowPolicy: [
1135
1156
  '模型口语名命中后必须先展示候选模型、真实参数取值和资源能力,并在清单后 STOP 等用户选择或明确授权默认;没有完成用户可见候选清单和确认前,不得代选默认模型 / 参数,也不得进入 create-spec、fee、dry-run 或 create。',
1136
1157
  '模型探索阶段只读 model list / options / create-spec;fee 只在用户确认关键参数后跑一次。',
1158
+ 'model options.params[] 中带 cliArg/genericModelParam 的新增模型配置参数可通过 --model-param key=value、--model-params-json 或同名下划线长参数传入;defaultValue 只能展示为候选默认,不能静默代选。',
1137
1159
  'supportsDryRun=true 的写入 / 扣费命令先 dry-run,确认后 yes;不要把 dry-run 当参数探索工具反复跑。',
1138
1160
  '用户给出多条同模型同参数任务时优先 batch + task-record-file,不要单条循环 create。',
1139
1161
  '命令返回 nextCommand / nextRefSubject / nextVoiceArg 时优先复用返回值,不手拼等价命令。',
@@ -1190,7 +1212,7 @@ function buildAgentContract() {
1190
1212
  jsonCommand: `${commandPrefix()} model options --model-group-code <code> -f json`,
1191
1213
  purpose: '查询指定模型支持的 CLI 参数、枚举值、默认值、素材约束和条件约束。Agent 默认读 textCommand;只有程序化校验完整嵌套结构时读 jsonCommand。',
1192
1214
  useBefore: ['model create-spec', 'create image-fee', 'create image', 'create video-fee', 'create video'],
1193
- keyFields: ['params[].values', 'params[].defaultValue', 'resources[].mediaType', 'resources[].usage', 'resources[].fileTypes', 'resources[].maxFiles', 'resources[].supportLastFrameOnly', 'resources[].minDurationMs', 'resources[].maxDurationMs', 'constraints[].target', 'constraints[].conditions', 'constraints[].effect'],
1215
+ keyFields: ['params[].key', 'params[].cliArg', 'params[].genericModelParam', 'params[].values', 'params[].defaultValue', 'resources[].mediaType', 'resources[].usage', 'resources[].fileTypes', 'resources[].maxFiles', 'resources[].supportLastFrameOnly', 'resources[].minDurationMs', 'resources[].maxDurationMs', 'constraints[].target', 'constraints[].conditions', 'constraints[].effect'],
1194
1216
  },
1195
1217
  modelCreateSpec: {
1196
1218
  command: `${commandPrefix()} model create-spec --model-group-code <code>`,
@@ -1452,7 +1474,10 @@ function printCommandHelp(command) {
1452
1474
  function validateCommandOptions(command, kwargs, kwargRawFlags = {}) {
1453
1475
  const allowedKeys = (command.args || []).map((arg) => normalizeKey(arg.name));
1454
1476
  const allowed = new Set(allowedKeys);
1455
- const unknown = Object.keys(kwargs).filter((key) => !allowed.has(key));
1477
+ const unknown = Object.keys(kwargs).filter((key) => (
1478
+ !allowed.has(key)
1479
+ && !(command.allowDynamicModelParams && key.includes('_'))
1480
+ ));
1456
1481
  if (!unknown.length) return;
1457
1482
  const displayFlag = (key) => kwargRawFlags[key] || formatOptionName(key);
1458
1483
  const suggestions = {};
@@ -1485,6 +1510,21 @@ function validateCommandOptions(command, kwargs, kwargRawFlags = {}) {
1485
1510
  });
1486
1511
  }
1487
1512
 
1513
+ function normalizeDynamicModelParamFlags(command, kwargs = {}, kwargRawFlags = {}) {
1514
+ if (!command.allowDynamicModelParams) return;
1515
+ const allowed = new Set((command.args || []).map((arg) => normalizeKey(arg.name)));
1516
+ for (const key of Object.keys(kwargs)) {
1517
+ if (allowed.has(key) || key.includes('_')) continue;
1518
+ const flag = kwargRawFlags[key] || formatOptionName(key);
1519
+ if (!flag.startsWith('--') || !flag.includes('-')) continue;
1520
+ const normalized = flag.slice(2).replaceAll('-', '_');
1521
+ if (!normalized || normalized === key || allowed.has(normalized)) continue;
1522
+ if (kwargs[normalized] === undefined) kwargs[normalized] = kwargs[key];
1523
+ delete kwargs[key];
1524
+ if (kwargRawFlags[key] && !kwargRawFlags[normalized]) kwargRawFlags[normalized] = kwargRawFlags[key];
1525
+ }
1526
+ }
1527
+
1488
1528
  function printData(data, format, meta = {}, context = {}) {
1489
1529
  const outputFormat = resolveOutputFormat(format);
1490
1530
  if (outputFormat === 'json') {
@@ -1506,6 +1546,19 @@ function printData(data, format, meta = {}, context = {}) {
1506
1546
  process.stdout.write(formatPrettyOutput(meta.command, data, context));
1507
1547
  }
1508
1548
 
1549
+ function printUpdateNotice(updateNotice) {
1550
+ if (!updateNotice?.message) return;
1551
+ process.stderr.write(`${updateNotice.message}\n`);
1552
+ }
1553
+
1554
+ function isStructuredOutputFormat(format) {
1555
+ try {
1556
+ return ['json', 'yaml'].includes(resolveOutputFormat(format));
1557
+ } catch {
1558
+ return false;
1559
+ }
1560
+ }
1561
+
1509
1562
  function printError(error, format, meta = {}) {
1510
1563
  let outputFormat = 'text';
1511
1564
  try {
@@ -1567,6 +1620,7 @@ export async function runStandaloneCli(argv = process.argv.slice(2)) {
1567
1620
  const { commandName: rawCommandName, kwargs, kwargRawFlags, format } = parseArgv(argv);
1568
1621
  const commandName = resolveCommandName(rawCommandName, commands);
1569
1622
  const command = commands.find((item) => item.name === commandName);
1623
+ const updateNotice = await resolveUpdateNotice(argv, commandName || rawCommandName, version);
1570
1624
  if (!command) {
1571
1625
  if (isCommandSubgroupName(rawCommandName, commands)) {
1572
1626
  const [group, subgroup] = rawCommandName.split(' ');
@@ -1581,19 +1635,27 @@ export async function runStandaloneCli(argv = process.argv.slice(2)) {
1581
1635
  type: 'unknown_command',
1582
1636
  exitCode: 2,
1583
1637
  hint: unknownCommandHint(rawCommandName),
1584
- }), format, { command: rawCommandName });
1638
+ }), format, {
1639
+ command: rawCommandName,
1640
+ ...(updateNotice ? { _notice: { update: updateNotice } } : {}),
1641
+ });
1585
1642
  process.exitCode = 2;
1643
+ if (!isStructuredOutputFormat(format)) printUpdateNotice(updateNotice);
1586
1644
  return;
1587
1645
  }
1588
1646
 
1589
1647
  const startedAt = Date.now();
1590
1648
  try {
1591
1649
  const outputFormat = resolveOutputFormat(format);
1650
+ normalizeDynamicModelParamFlags(command, kwargs, kwargRawFlags);
1592
1651
  validateCommandOptions(command, kwargs, kwargRawFlags);
1593
1652
  const data = command.virtual === 'schema'
1594
1653
  ? buildCommandSchema(commands, kwargs, version)
1595
1654
  : await command.func({ command }, kwargs);
1596
- printData(data, outputFormat, { command: command.name, elapsedMs: Date.now() - startedAt }, buildOutputContext(command, kwargs));
1655
+ const meta = { command: command.name, elapsedMs: Date.now() - startedAt };
1656
+ if (updateNotice) meta._notice = { update: updateNotice };
1657
+ printData(data, outputFormat, meta, buildOutputContext(command, kwargs));
1658
+ if (outputFormat !== 'json' && outputFormat !== 'yaml') printUpdateNotice(updateNotice);
1597
1659
  } catch (error) {
1598
1660
  const cliError = error instanceof LingjingAwbCliError
1599
1661
  ? error
@@ -0,0 +1,327 @@
1
+ import { execFile } from 'node:child_process';
2
+ import fsSync from 'node:fs';
3
+ import fs from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { promisify } from 'node:util';
7
+ import {
8
+ LingjingAwbCliError,
9
+ loadState,
10
+ nowIso,
11
+ saveState,
12
+ toBool,
13
+ toInt,
14
+ trimToNull,
15
+ } from './common.js';
16
+
17
+ const execFileAsync = promisify(execFile);
18
+ const DEFAULT_CLI_PACKAGE_NAME = '@lingjingai/lj-awb-cli';
19
+ const DEFAULT_NPM_REGISTRY = 'https://registry.npmjs.org/';
20
+ const DEFAULT_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
21
+ const DEFAULT_NPM_TIMEOUT_MS = 15_000;
22
+ const AUTO_CHECK_TIMEOUT_MS = 4_000;
23
+
24
+ function commandPrefix() {
25
+ return process.env.LINGJING_AWB_COMMAND_PREFIX || 'lj-awb';
26
+ }
27
+
28
+ function boolEnv(value) {
29
+ return ['1', 'true', 'yes', 'y', 'on'].includes(String(value ?? '').trim().toLowerCase());
30
+ }
31
+
32
+ function readPackageJsonSync(packagePath) {
33
+ try {
34
+ return JSON.parse(fsSync.readFileSync(packagePath, 'utf8'));
35
+ } catch {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ function corePackagePath() {
41
+ return path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
42
+ }
43
+
44
+ function rootPackagePath() {
45
+ return path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', '..', 'package.json');
46
+ }
47
+
48
+ export async function readCurrentCliVersion() {
49
+ const pkg = JSON.parse(await fs.readFile(corePackagePath(), 'utf8'));
50
+ return pkg.version || 'unknown';
51
+ }
52
+
53
+ function currentRootDir() {
54
+ return path.dirname(rootPackagePath());
55
+ }
56
+
57
+ function isLocalCheckout() {
58
+ return fsSync.existsSync(path.join(currentRootDir(), '.git'));
59
+ }
60
+
61
+ export function resolveCliPackageName(kwargs = {}) {
62
+ const explicit = trimToNull(kwargs.packageName || kwargs.package || process.env.LINGJING_AWB_CLI_PACKAGE);
63
+ if (explicit) return explicit;
64
+ const rootPkg = readPackageJsonSync(rootPackagePath());
65
+ const name = trimToNull(rootPkg?.name);
66
+ return name?.startsWith('@lingjingai/lj-awb-cli') ? name : DEFAULT_CLI_PACKAGE_NAME;
67
+ }
68
+
69
+ function resolveRegistry(kwargs = {}) {
70
+ return trimToNull(
71
+ kwargs.registry
72
+ || process.env.LINGJING_AWB_UPDATE_REGISTRY
73
+ || process.env.NPM_CONFIG_REGISTRY
74
+ || process.env.npm_config_registry,
75
+ ) || DEFAULT_NPM_REGISTRY;
76
+ }
77
+
78
+ function updateCheckIntervalMs() {
79
+ const raw = process.env.LINGJING_AWB_UPDATE_CHECK_INTERVAL_MS;
80
+ if (raw === undefined || raw === null || raw === '') return DEFAULT_CHECK_INTERVAL_MS;
81
+ return Math.max(0, toInt(raw, DEFAULT_CHECK_INTERVAL_MS));
82
+ }
83
+
84
+ function updateCheckDisabled() {
85
+ return boolEnv(process.env.LINGJING_AWB_DISABLE_UPDATE_CHECK)
86
+ || boolEnv(process.env.AWB_DISABLE_UPDATE_CHECK)
87
+ || ['0', 'false', 'off', 'no'].includes(String(process.env.LINGJING_AWB_UPDATE_CHECK ?? '').trim().toLowerCase());
88
+ }
89
+
90
+ function forceAutoUpdateCheck() {
91
+ return boolEnv(process.env.LINGJING_AWB_UPDATE_CHECK)
92
+ || String(process.env.LINGJING_AWB_UPDATE_CHECK || '').trim().toLowerCase() === 'force';
93
+ }
94
+
95
+ function parseVersion(value) {
96
+ const text = String(value || '').trim().replace(/^v/i, '');
97
+ const [main, pre = ''] = text.split('-', 2);
98
+ const parts = main.split('.').map((item) => Number.parseInt(item, 10));
99
+ if (parts.some((item) => !Number.isFinite(item))) return null;
100
+ return { parts, pre };
101
+ }
102
+
103
+ export function semverLessThan(a, b) {
104
+ const left = parseVersion(a);
105
+ const right = parseVersion(b);
106
+ if (!left || !right) return false;
107
+ for (let index = 0; index < 3; index += 1) {
108
+ const lv = left.parts[index] || 0;
109
+ const rv = right.parts[index] || 0;
110
+ if (lv < rv) return true;
111
+ if (lv > rv) return false;
112
+ }
113
+ if (left.pre && !right.pre) return true;
114
+ if (!left.pre && right.pre) return false;
115
+ return left.pre < right.pre;
116
+ }
117
+
118
+ function npmArgsWithRegistry(args, registry) {
119
+ return registry ? [...args, `--registry=${registry}`] : args;
120
+ }
121
+
122
+ function npmInstallSpec(packageName, version) {
123
+ return version && version !== 'latest' ? `${packageName}@${version}` : packageName;
124
+ }
125
+
126
+ async function runNpm(args, options = {}) {
127
+ try {
128
+ const result = await execFileAsync('npm', args, {
129
+ cwd: currentRootDir(),
130
+ encoding: 'utf8',
131
+ timeout: options.timeoutMs || DEFAULT_NPM_TIMEOUT_MS,
132
+ maxBuffer: 1024 * 1024,
133
+ env: process.env,
134
+ });
135
+ return result;
136
+ } catch (error) {
137
+ const stderr = String(error.stderr || '').trim();
138
+ const stdout = String(error.stdout || '').trim();
139
+ throw new LingjingAwbCliError('npm 命令执行失败', {
140
+ type: 'network_error',
141
+ exitCode: 30,
142
+ hint: stderr || stdout || error.message || '请确认 npm 可用,并且当前网络可以访问 npm registry。',
143
+ details: {
144
+ command: `npm ${args.join(' ')}`,
145
+ code: error.code,
146
+ signal: error.signal,
147
+ },
148
+ });
149
+ }
150
+ }
151
+
152
+ export async function fetchLatestCliVersion(options = {}) {
153
+ const mocked = trimToNull(process.env.LINGJING_AWB_UPDATE_LATEST_VERSION);
154
+ if (mocked) return mocked;
155
+ const packageName = options.packageName || resolveCliPackageName(options);
156
+ const registry = options.registry || resolveRegistry(options);
157
+ const result = await runNpm(
158
+ npmArgsWithRegistry(['view', packageName, 'version'], registry),
159
+ { timeoutMs: options.timeoutMs || DEFAULT_NPM_TIMEOUT_MS },
160
+ );
161
+ const version = String(result.stdout || '').trim().replace(/^"|"$/g, '');
162
+ if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) {
163
+ throw new LingjingAwbCliError('无法识别 npm latest 版本', {
164
+ type: 'runtime_error',
165
+ exitCode: 1,
166
+ hint: `npm view ${packageName} version 返回了非 semver 内容。`,
167
+ details: { version },
168
+ });
169
+ }
170
+ return version;
171
+ }
172
+
173
+ function buildUpdateNotice({ currentVersion, latestVersion, packageName, checkedAt }) {
174
+ const command = `${commandPrefix()} update`;
175
+ return {
176
+ message: `检测到 ${commandPrefix()} 新版本 ${latestVersion}(当前 ${currentVersion})。运行 ${command} 更新 CLI 和 skill。`,
177
+ command,
178
+ checkCommand: `${commandPrefix()} update --check`,
179
+ packageName,
180
+ currentVersion,
181
+ latestVersion,
182
+ checkedAt,
183
+ };
184
+ }
185
+
186
+ function cachedNotice(state, currentVersion, packageName) {
187
+ const cached = state?.updateCheck;
188
+ if (!cached || cached.packageName !== packageName || cached.currentVersion !== currentVersion) return null;
189
+ if (!cached.latestVersion || !semverLessThan(currentVersion, cached.latestVersion)) return null;
190
+ return buildUpdateNotice({
191
+ currentVersion,
192
+ latestVersion: cached.latestVersion,
193
+ packageName,
194
+ checkedAt: cached.checkedAtText || null,
195
+ });
196
+ }
197
+
198
+ function shouldSkipAutoCheck() {
199
+ if (updateCheckDisabled()) return true;
200
+ if (forceAutoUpdateCheck()) return false;
201
+ if (process.env.CI) return true;
202
+ if (isLocalCheckout()) return true;
203
+ return false;
204
+ }
205
+
206
+ export async function checkCliUpdate(options = {}) {
207
+ const currentVersion = options.currentVersion || await readCurrentCliVersion().catch(() => 'unknown');
208
+ const packageName = resolveCliPackageName(options);
209
+ if (!currentVersion || currentVersion === 'unknown' || shouldSkipAutoCheck()) return null;
210
+
211
+ const state = await loadState().catch(() => ({}));
212
+ const cached = state?.updateCheck || {};
213
+ const now = Date.now();
214
+ const intervalMs = options.force ? 0 : updateCheckIntervalMs();
215
+ const cacheHit = cached.packageName === packageName
216
+ && cached.currentVersion === currentVersion
217
+ && cached.checkedAt
218
+ && (now - Number(cached.checkedAt) < intervalMs);
219
+ if (cacheHit) return cachedNotice(state, currentVersion, packageName);
220
+
221
+ try {
222
+ const registry = resolveRegistry(options);
223
+ const latestVersion = await fetchLatestCliVersion({
224
+ packageName,
225
+ registry,
226
+ timeoutMs: options.timeoutMs || AUTO_CHECK_TIMEOUT_MS,
227
+ });
228
+ const checkedAtText = nowIso();
229
+ await saveState({
230
+ updateCheck: {
231
+ packageName,
232
+ registry,
233
+ currentVersion,
234
+ latestVersion,
235
+ checkedAt: now,
236
+ checkedAtText,
237
+ },
238
+ }).catch(() => {});
239
+ if (!semverLessThan(currentVersion, latestVersion)) return null;
240
+ return buildUpdateNotice({ currentVersion, latestVersion, packageName, checkedAt: checkedAtText });
241
+ } catch (error) {
242
+ await saveState({
243
+ updateCheck: {
244
+ packageName,
245
+ currentVersion,
246
+ latestVersion: cached.latestVersion || null,
247
+ checkedAt: now,
248
+ checkedAtText: nowIso(),
249
+ error: error.message || String(error),
250
+ },
251
+ }).catch(() => {});
252
+ return cachedNotice({ updateCheck: cached }, currentVersion, packageName);
253
+ }
254
+ }
255
+
256
+ function tailLines(value, limit = 8) {
257
+ const lines = String(value || '').trim().split(/\r?\n/).filter(Boolean);
258
+ return lines.slice(Math.max(0, lines.length - limit));
259
+ }
260
+
261
+ export async function runCliUpdate(kwargs = {}) {
262
+ const currentVersion = await readCurrentCliVersion().catch(() => 'unknown');
263
+ const packageName = resolveCliPackageName(kwargs);
264
+ const registry = resolveRegistry(kwargs);
265
+ const latestVersion = await fetchLatestCliVersion({ packageName, registry });
266
+ const updateAvailable = currentVersion !== 'unknown' && semverLessThan(currentVersion, latestVersion);
267
+ const checkOnly = toBool(kwargs.check);
268
+ const force = toBool(kwargs.force);
269
+ const installVersion = latestVersion || 'latest';
270
+ const installSpec = npmInstallSpec(packageName, force ? 'latest' : installVersion);
271
+ const installArgs = npmArgsWithRegistry(['install', '-g', installSpec], registry);
272
+
273
+ if (checkOnly) {
274
+ return {
275
+ checked: true,
276
+ updated: false,
277
+ updateAvailable,
278
+ packageName,
279
+ currentVersion,
280
+ latestVersion,
281
+ command: updateAvailable ? `${commandPrefix()} update` : null,
282
+ message: updateAvailable
283
+ ? `发现新版本 ${latestVersion},运行 ${commandPrefix()} update 更新。`
284
+ : '当前已是最新版本。',
285
+ };
286
+ }
287
+
288
+ if (!updateAvailable && !force) {
289
+ return {
290
+ checked: true,
291
+ updated: false,
292
+ updateAvailable: false,
293
+ packageName,
294
+ currentVersion,
295
+ latestVersion,
296
+ message: '当前已是最新版本。',
297
+ };
298
+ }
299
+
300
+ const result = await runNpm(installArgs, { timeoutMs: 120_000 });
301
+ await saveState({
302
+ updateCheck: {
303
+ packageName,
304
+ registry,
305
+ currentVersion: latestVersion,
306
+ latestVersion,
307
+ checkedAt: Date.now(),
308
+ checkedAtText: nowIso(),
309
+ },
310
+ }).catch(() => {});
311
+
312
+ return {
313
+ checked: true,
314
+ updated: true,
315
+ updateAvailable,
316
+ packageName,
317
+ previousVersion: currentVersion,
318
+ currentVersion: latestVersion,
319
+ latestVersion,
320
+ command: `npm ${installArgs.join(' ')}`,
321
+ skillUpdated: true,
322
+ restartRecommended: true,
323
+ message: '更新完成。请退出并重新打开 AI Agent,以加载最新 CLI 和 skill。',
324
+ stdoutTail: tailLines(result.stdout),
325
+ stderrTail: tailLines(result.stderr),
326
+ };
327
+ }
@@ -1,16 +1,19 @@
1
1
  ---
2
2
  name: lj-awb
3
- version: 0.4.0
3
+ version: 0.4.1
4
4
  description: "灵境 AWB CLI skill。使用 `lj-awb` 命令调用动漫平台 / AWB 云端能力,覆盖认证、项目组、积分、模型发现、上传、统一 create 创建域、任务查询、最终产物 artifact CRUD 与本地 JSON 导入。用户说生图、生视频、主体、音色、素材加白、去字幕、artifact 写入或查询时使用。正式生成、切换项目组、清空认证、artifact 写入等写入或扣费动作前必须确认。"
5
5
  metadata:
6
- requires:
7
- bins: ["lj-awb"]
6
+ bootstrap:
7
+ package: "@lingjingai/lj-awb-cli"
8
+ version: "0.4.1"
9
+ bin: "lj-awb"
8
10
  cliHelp: "lj-awb --help"
9
11
  ---
10
12
 
11
13
  # lj-awb CLI Skill
12
14
 
13
15
  `lj-awb` 是确定性 CLI,skill 的职责是调度:少查、少问、少重跑,按 schema 和业务链条把命令串对。不要把本 skill 当成一堆命令片段来拼。
16
+ 普通命令如果 JSON 输出里出现 `meta._notice.update`,先完成当前用户请求,再告诉用户当前版本和最新版本,并建议执行 `lj-awb update`;更新后提醒重新打开 AI Agent。
14
17
 
15
18
  ## 先读驱动器
16
19
 
@@ -25,22 +28,35 @@ metadata:
25
28
 
26
29
  ## 入口命令
27
30
 
28
- 优先直接使用全局 CLI:
31
+ 本 skill 是完整入口:如果用户只安装了 skill,也要先自举补齐 CLI。每个新环境第一次使用 `lj-awb` 前,先解析命令:
29
32
 
30
33
  ```bash
31
- lj-awb --help
34
+ for dir in "$PWD/skills/lj-awb" "$HOME/.codex/skills/lj-awb" "$HOME/.claude/skills/lj-awb" "$HOME/.cc-switch/skills/lj-awb"; do
35
+ if [ -x "$dir/scripts/resolve-lj-awb-cmd.sh" ]; then
36
+ LINGJING_AWB_CMD="$(bash "$dir/scripts/resolve-lj-awb-cmd.sh")"
37
+ break
38
+ fi
39
+ done
40
+ : "${LINGJING_AWB_CMD:?lj-awb bootstrap script not found}"
32
41
  ```
33
42
 
34
- 源码调试或不确定路径时再解析:
43
+ `resolve-lj-awb-cmd.sh` 会按顺序处理:
44
+
45
+ - 已存在兼容版本 `lj-awb`:直接返回命令路径。
46
+ - 未安装或版本低于 [`compat.json`](compat.json) 的 `minCliVersion`:自动执行 `npm install -g @lingjingai/lj-awb-cli@<minCliVersion>`。
47
+ - 用户要预发环境时,安装前设置 `LINGJING_AWB_CLI_PACKAGE=@lingjingai/lj-awb-cli-pre`。
48
+ - 缺少 npm / Node 时,提示用户先安装 Node.js `>=20`,再重试。
49
+
50
+ 脚本 stdout 只输出可执行命令;安装日志和错误走 stderr。后续命令优先使用解析结果:
35
51
 
36
52
  ```bash
37
- LINGJING_AWB_CMD="$(bash "$(dirname "$0")/scripts/resolve-lj-awb-cmd.sh")"
53
+ "$LINGJING_AWB_CMD" --help
38
54
  ```
39
55
 
40
56
  非单条查询任务、命令不确定或涉及写入 / 扣费时,本轮只读一次机器契约:
41
57
 
42
58
  ```bash
43
- lj-awb schema --brief -f json
59
+ "$LINGJING_AWB_CMD" schema --brief -f json
44
60
  ```
45
61
 
46
62
  `schema --brief` 只用于掌握能力域、安全分组、业务路由和 agentContract。执行具体命令前,如果命令、参数、requiredOptions、safety 或 nextActions 不确定,再读精确契约,例如 `lj-awb schema --domain model --command video-models -f json`。不要把完整 `lj-awb schema -f json` 当默认入口;只有校验覆盖、脚本生成或 brief 缺失字段时才读完整 schema。
@@ -48,6 +64,7 @@ lj-awb schema --brief -f json
48
64
  schema 查询必须先返回,再组织业务命令;不要把 schema 查询和猜测命令放进同一批并行调用。
49
65
 
50
66
  如果用户已经给出完整只读命令,且该命令在本 skill 已知范围内,可以直接执行,不必为了形式补跑 schema。命令名、参数名、requiredOptions、safety、workflow.nextActions 都以 schema 为准。旧根域 `image` / `video` / `asset` / `subject` 不存在,不要尝试旧入口。
67
+ `update` 只做显式安装;`update --check` 只检查不安装。
51
68
 
52
69
  ## 能力地图
53
70
 
@@ -105,6 +122,8 @@ schema 查询必须先返回,再组织业务命令;不要把 schema 查询
105
122
 
106
123
  ## 安装与版本
107
124
 
125
+ 如果用户只安装了 skill,第一次使用时会由 bootstrap 脚本自动安装 CLI。手动安装命令如下:
126
+
108
127
  ```bash
109
128
  npm install -g @lingjingai/lj-awb-cli
110
129
  ```
@@ -1 +1 @@
1
- 0.4.0
1
+ 0.4.1
@@ -1,6 +1,6 @@
1
1
  {
2
- "skillVersion": "0.4.0",
3
- "minCliVersion": "0.4.0",
2
+ "skillVersion": "0.4.1",
3
+ "minCliVersion": "0.4.1",
4
4
  "preferredCommand": "lj-awb",
5
- "updatedAt": "2026-05-20"
5
+ "updatedAt": "2026-05-26"
6
6
  }
@@ -13,6 +13,8 @@
13
13
  | `--generate-num` | 生图张数 | 仅图片模型支持时使用 |
14
14
  | `--duration` | 生视频时长,单位秒 | 对应平台旧参数 `generated_time`,只能从允许值选择 |
15
15
  | `--need-audio` | 是否需要输出音效 | 仅用户明确要求输出音效,且 `model options.params[key=needAudio]` 存在时使用;不是上传音频入口。模型未暴露该 param 时**不要为了"显式关闭"传 `--need-audio false`**,CLI 会以 `argument_error: 模型不支持参数:needAudio` 拒绝;不传等价于不开音效 |
16
+ | `--model-param key=value` | 新增 / 未硬编码的模型配置参数 | key 必须来自 `model options.params[]`;可重复传。适合 `generation_effort=high` 这类通用 Enum / Boolean / Number / String 配置 |
17
+ | `--model-params-json` | 一次传多个通用模型配置参数 | JSON 对象或 JSON 文件路径;命令行专用参数如 `--ratio`、`--quality`、`--duration` 优先级更高 |
16
18
  | `--resource` | 单个素材输入,可重复传 | `type:usage[:key]=path|url|asset:<id>` |
17
19
  | `--resources-json` | 多素材输入,适合复杂 keyframe / 批量构造 | JSON 数组或 JSON 文件路径 |
18
20
  | `--project-group-no` | 任务归属项目组 | 用户明确指定,或来自当前项目组 |
@@ -94,6 +96,7 @@ JSON 语法:
94
96
  | `quality` | `--quality` | `promptParams.quality` | `quality` |
95
97
  | `generate_num` | `--generate-num` | `promptParams.generate_num` | `generate_num` |
96
98
  | `generated_time` | `--duration` | `promptParams.duration` | `generated_time` |
99
+ | 其他带 `cliArg` 的模型配置参数 | `--model-param <key>=...` / `--model-params-json` | `promptParams.<key>` | 同名透传 |
97
100
  | `iref` | `--resource image:reference=...` | `promptParams.resources[]` | `iref` |
98
101
  | `frames` | `--resource image:first_frame=...` | `promptParams.resources[]` | `frames` |
99
102
  | `multi_param` | `--resource image/video/audio/subject:reference[:key]=...` | `promptParams.resources[]` | `multi_param` |
@@ -117,11 +120,11 @@ Agent 必须按顺序做:
117
120
  5. 若本轮已读取 `model create-spec` 则直接复用;否则运行 `model create-spec --model-group-code <code> -f json`。
118
121
  6. 先读 `inputRequirement`,确认是否必须提供视觉输入。
119
122
  7. 用 `supportedIntents[]` 匹配用户意图;不要只看模型列表摘要就生成最终能力结论。
120
- 8. 参数枚举值只从 `model options.params[].values` 选择,素材限制只从 `model options.resources[]` 校验,参数 / 资源联动限制按 `model options.constraints[]` 收窄。
123
+ 8. 参数枚举值只从 `model options.params[].values` 选择,素材限制只从 `model options.resources[]` 校验,参数 / 资源联动限制按 `model options.constraints[]` 收窄。新增通用参数只要在 `params[]` 中出现且带 `cliArg`,就通过 `--model-param` / `--model-params-json` 显式传入。
121
124
  9. 不主动列举所有缺失控制项;只追问会影响价格 / 效果的关键参数。视频包括 `quality`、`duration`、约束后仍可选的 `ratio`,以及用户明确要求输出音效时的 `needAudio`;图片包括 `quality`、`ratio`、`generateNum`。
122
125
  10. 组装最终 prompt;如果可见文本发生变化,先展示给用户。
123
126
  11. 若用户上传或指定音频文件,必须先确认 `model options.resources[]` 中存在 `mediaType=AUDIO usage=reference` 后再组织 `audio:reference` 资源;只有用户明确要求“输出是否带模型生成音效/音频”时,才检查 `model options.params[]` 是否存在 `needAudio`。
124
- 12. 用户未提供关键参数时,把 `model options.params[].values` 和 `defaultValue` 转成候选问题;用户选择或确认“按默认”前,不跑 `create image-fee` / `create video-fee`,也不跑 `create --dry-run`。
127
+ 12. 用户未提供关键参数时,把 `model options.params[].values` 和 `defaultValue` 转成候选问题;用户选择或确认“按默认”前,不跑 `create image-fee` / `create video-fee`,也不跑 `create --dry-run`。即使模型给了 `defaultValue`,也不要静默写入请求。
125
128
  13. 跑 `create image-fee` / `create video-fee` 获取预估积分——**只跑一次,参数取用户已确认的那组**。`fee` 是"用户敲定参数后的最终估价",不是参数探索 / 候选比较工具:不要为了对比价格档跑 `fee` × 多个 `quality` / `duration` / `ratio` 组合,也不要为了横向比同款不同渠道跑 `fee` × 多个 `modelGroupCode`;价格档差异从 `model options.feeCalcType` + 参数取值表里就能口算/展示给用户,比较应该发生在 `model options` 阶段。
126
129
  14. 跑 `create --dry-run` 检查请求体和本地素材。
127
130
  15. 用户确认模型、项目组、最终 prompt 文本、素材、关键参数和积分后,才追加 `--yes` 正式提交。
@@ -10,6 +10,7 @@
10
10
  - Skill 是驱动器,不是命令百科。先在本模块决定链路,只在需要时加载一个细节模块。
11
11
  - 同一对话维护 AWB 状态账本;除非用户切换账号、团队、项目组、模型、素材、prompt 或关键参数,否则不要重复跑同样的查询。
12
12
  - 写入 / 扣费命令遵循 schema safety:`supportsDryRun=true` 先 dry-run,`requiresConfirmation=true` 经用户确认后再 `--yes`。
13
+ - 如果 JSON 输出带 `meta._notice.update`,先继续完成当前业务链路,收尾时告知当前版本 / 最新版本并建议 `lj-awb update`;不要静默忽略更新提示。
13
14
  - 旧根域 `image` / `video` / `asset` / `subject` 已移除,不要尝试旧入口,也不要给旧命令做兼容推理。
14
15
 
15
16
  ## 状态账本
@@ -21,6 +21,7 @@
21
21
  | `--ratio` | 需要指定画幅时 | `model options.params[key=ratio].values` |
22
22
  | `--quality` | 需要指定清晰度时 | `model options.params[key=quality].values` |
23
23
  | `--generate-num` | 指定生成张数;模型暴露该控制项时属于价格关键参数 | `model options.params[key=generateNum].values` |
24
+ | `--model-param key=value` / `--model-params-json` | 新增通用模型配置参数,如 `generation_effort` | `model options.params[]` 中带 `cliArg` / `genericModelParam` 的参数 |
24
25
  | `--resource image:reference=...` | 参考图生图 | `model create-spec.supportedIntents.mode=reference` 必须存在 |
25
26
  | `--resources-json` | 多参考图或程序化构造 | 同 `--resource`,但用 JSON 数组表达 |
26
27
 
@@ -60,8 +61,9 @@ lj-awb create image \
60
61
  - 参考图 source.value 取值优先级、"不要复用 myqcloud 完整 URL"、图片生图不使用 `reference_key` / `<<<key>>>` 等规则统一在 [`create-contract.md`](create-contract.md) §素材组织 + §Prompt 组装原则;多张参考图用资源顺序和自然语言指代映射(例如"图一中的白发女保持表情,在图二背景里坐秋千"),不要替用户编 key。
61
62
  - `ratio` / `quality` / `generate-num` 不确定时,先查 `model options`,不要猜一个模型不支持的值。
62
63
  - `fee` 和 `create --dry-run` 前必须确认缺失的 `ratio`、`quality`、`generate-num`;不要静默用默认值估价。用户说“按默认”后才继续。
64
+ - `generation_effort` 这类新增模型配置参数如果出现在 `model options.params[]`,先把可选值 / `defaultValue` 展示给用户;用户确认后用 `--model-param generation_effort=<value>` 或 `--model-params-json` 传入,不要等专用 CLI flag。
63
65
  - 正式提交必须带 `--yes`;如果需要看请求体,先用 `--dry-run`。
64
- - 批量 JSON/JSONL 每项只写 `prompt`、`ratio`、`quality`、`generate_num`、`resources`、`resource`、`customBizId`;模型组和项目组放命令行公共参数。
66
+ - 批量 JSON/JSONL 每项只写 `prompt`、`ratio`、`quality`、`generate_num`、`resources`、`resource`、`model_params`、`customBizId`,也可直接写模型配置下划线参数;模型组和项目组放命令行公共参数。
65
67
  - **批量是 best-effort**:`create-batch` 子任务**单条失败不会回滚整批**,已成功项依然扣分并产生 taskId。提交后必读响应里每项的 `status` / `taskId` / `error`,给用户汇总"成功 N / 失败 M",对失败项单独 fix + 重跑(不要全批重跑)。
66
68
  - **多镜头 / 多 prompt 时主动建议并行**:用户一次给出 ≥2 个同模型同参数的图片任务(典型场景:分镜、组图、多 prompt 候选)时,Agent 必须先告知"这批可以用 `create image-batch --concurrency N` 并行执行(n 个任务,预计耗时 / 单次估价 × n)",并询问用户是否要并行。用户同意 → 走 batch;用户希望逐条审稿 / 调 prompt → 继续单条 create。**不要默认一条一条串行还不告知**,这种沉默会浪费用户时间。
67
69
  - 等待超时只代表本轮轮询结束,不能对用户说任务失败。