@lark-apaas/openclaw-scripts-diagnose-cli 0.1.14-alpha.7 → 0.1.14-alpha.8

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 (2) hide show
  1. package/dist/index.cjs +747 -226
  2. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -52,7 +52,7 @@ node_assert = __toESM(node_assert);
52
52
  * it terse and parseable.
53
53
  */
54
54
  function getVersion() {
55
- return "0.1.14-alpha.7";
55
+ return "0.1.14-alpha.8";
56
56
  }
57
57
  //#endregion
58
58
  //#region src/rule-engine/base.ts
@@ -3347,7 +3347,6 @@ function resolveUpgradeDirection(installed, ocCur, recommendedOc, isLegacy) {
3347
3347
  /** 提取公共前置上下文;任何前置条件不满足时返回 null(规则 pass)。 */
3348
3348
  function resolveCompatContext(ctx) {
3349
3349
  const recommendedOc = ctx.vars.recommendedOpenclawTag;
3350
- if (!recommendedOc) return null;
3351
3350
  const ocCur = getOcVersion();
3352
3351
  if (!ocCur) return null;
3353
3352
  const installed = getInstalledPlugin(ctx);
@@ -3370,6 +3369,7 @@ let FeishuPluginOpenclawUpgradeRule = class FeishuPluginOpenclawUpgradeRule exte
3370
3369
  if (!cc) return { pass: true };
3371
3370
  const { ocCur, recommendedOc, installed, isLegacy } = cc;
3372
3371
  if (isForkPlugin(installed)) return validateForkPlugin(installed, ocCur, recommendedOc);
3372
+ if (!recommendedOc) return { pass: true };
3373
3373
  if (resolveUpgradeDirection(installed, ocCur, recommendedOc, isLegacy) !== "openclaw") return { pass: true };
3374
3374
  return {
3375
3375
  pass: false,
@@ -3397,6 +3397,14 @@ let FeishuPluginLarkUpgradeRule = class FeishuPluginLarkUpgradeRule extends Diag
3397
3397
  if (!cc) return { pass: true };
3398
3398
  const { ocCur, recommendedOc, installed, isLegacy } = cc;
3399
3399
  if (isForkPlugin(installed)) return { pass: true };
3400
+ if (!recommendedOc) {
3401
+ if (isLegacy || !isVersionCompatible(installed, ocCur)) return {
3402
+ pass: false,
3403
+ action: "upgrade_lark",
3404
+ message: `${buildCompatPrefix(installed, ocCur, isLegacy)};建议升级飞书插件至兼容版本`
3405
+ };
3406
+ return { pass: true };
3407
+ }
3400
3408
  if (resolveUpgradeDirection(installed, ocCur, recommendedOc, isLegacy) !== "lark") return { pass: true };
3401
3409
  return {
3402
3410
  pass: false,
@@ -3451,14 +3459,16 @@ function describeCompatConstraint(entry, pluginVersion) {
3451
3459
  /**
3452
3460
  * @lark-apaas/openclaw-lark 豁免 VERSION_COMPAT_MAP,但仍要求 openclaw ≥ FORK_LARK_PLUGIN_MIN_OC_VERSION。
3453
3461
  * 其他 @lark-apaas scope 的 fork 插件继续无条件 pass。
3462
+ * recommendedOc 可为 undefined(doctor 模式),此时只检测最低版本要求,不指定目标升级版本。
3454
3463
  */
3455
3464
  function validateForkPlugin(installed, ocCur, recommendedOc) {
3456
3465
  if (installed.fullName !== FORK_LARK_PLUGIN_FULL_NAME) return { pass: true };
3457
3466
  if (compareCalVer(ocCur, FORK_LARK_PLUGIN_MIN_OC_VERSION) >= 0) return { pass: true };
3467
+ const recommendation = recommendedOc ? `;将 openclaw 升级到 ${recommendedOc} 即可满足` : `;请升级 openclaw 至 ${FORK_LARK_PLUGIN_MIN_OC_VERSION} 或更高版本`;
3458
3468
  return {
3459
3469
  pass: false,
3460
3470
  action: "upgrade_openclaw",
3461
- message: `飞书插件 ${describePlugin(installed)}(fork 版)要求 openclaw ≥ ${FORK_LARK_PLUGIN_MIN_OC_VERSION},当前 openclaw@${ocCur} 低于此要求;将 openclaw 升级到 ${recommendedOc} 即可满足`
3471
+ message: `飞书插件 ${describePlugin(installed)}(fork 版)要求 openclaw ≥ ${FORK_LARK_PLUGIN_MIN_OC_VERSION},当前 openclaw@${ocCur} 低于此要求${recommendation}`
3462
3472
  };
3463
3473
  }
3464
3474
  function describePlugin(p) {
@@ -3505,6 +3515,181 @@ function extractScopedNameFromSpec$1(spec) {
3505
3515
  const at = spec.indexOf("@", 1);
3506
3516
  return at === -1 ? spec : spec.slice(0, at);
3507
3517
  }
3518
+ /**
3519
+ * Returns true if the installed feishu plugin is version-incompatible with
3520
+ * the current openclaw (or is a legacy plugin that must be replaced).
3521
+ * Used by the upgrade_lark_needed rule and the upgrade-lark pre-check gate.
3522
+ */
3523
+ function needsLarkUpgrade(ctx) {
3524
+ const cc = resolveCompatContext(ctx);
3525
+ if (!cc) return false;
3526
+ const { ocCur, recommendedOc, installed, isLegacy } = cc;
3527
+ if (isForkPlugin(installed)) {
3528
+ if (recommendedOc) return false;
3529
+ if (installed.fullName === FORK_LARK_PLUGIN_FULL_NAME) return compareCalVer(ocCur, FORK_LARK_PLUGIN_MIN_OC_VERSION) < 0;
3530
+ return false;
3531
+ }
3532
+ if (recommendedOc) return resolveUpgradeDirection(installed, ocCur, recommendedOc, isLegacy) === "lark";
3533
+ return isLegacy || !isVersionCompatible(installed, ocCur);
3534
+ }
3535
+ //#endregion
3536
+ //#region src/channels-probe.ts
3537
+ const FEISHU_INVALID_CONFIG_MSG = "channels.feishu: invalid config: must NOT have additional properties";
3538
+ const CHANNEL_LINE_RE = /^-\s+Feishu\s+([^:]+):\s+(.+)$/;
3539
+ /**
3540
+ * Port of Python `_account_is_working` from the feishu-channel-success-rate skill.
3541
+ *
3542
+ * Strips colon-prefixed key:value bits (dm:, bot:, in:, out:, token:, allow:,
3543
+ * intents:, groups:, health:) and evaluates the canonical health formula.
3544
+ */
3545
+ function accountIsWorking(bits) {
3546
+ const bitTokens = /* @__PURE__ */ new Set();
3547
+ let hasError = false;
3548
+ let hasProbeFailed = false;
3549
+ for (const raw of bits) {
3550
+ const b = raw.trim();
3551
+ if (!b) continue;
3552
+ if (b.startsWith("error:")) {
3553
+ hasError = true;
3554
+ continue;
3555
+ }
3556
+ if (b === "probe failed") {
3557
+ hasProbeFailed = true;
3558
+ continue;
3559
+ }
3560
+ bitTokens.add(b.split(":")[0]);
3561
+ }
3562
+ if (!bitTokens.has("enabled") || !bitTokens.has("configured")) return false;
3563
+ if (bitTokens.has("works")) return true;
3564
+ if (bitTokens.has("running") && !hasError && !hasProbeFailed) return true;
3565
+ return false;
3566
+ }
3567
+ /**
3568
+ * Parse the raw stdout of `openclaw channels status --probe`.
3569
+ * Port of Python `extract_channels_probe` from the feishu-channel-success-rate skill.
3570
+ */
3571
+ function parseChannelsProbeOutput(text) {
3572
+ const gatewayReachable = text.includes("Gateway reachable");
3573
+ const feishuConfigInvalid = text.includes(FEISHU_INVALID_CONFIG_MSG);
3574
+ const accounts = [];
3575
+ let anyAccountWorking = false;
3576
+ for (const line of text.split("\n")) {
3577
+ const m = CHANNEL_LINE_RE.exec(line.trim());
3578
+ if (!m) continue;
3579
+ const [, acct, rest] = m;
3580
+ const bits = rest.split(",").map((b) => b.trim());
3581
+ const isWorking = accountIsWorking(bits);
3582
+ if (isWorking) anyAccountWorking = true;
3583
+ accounts.push({
3584
+ id: acct.trim(),
3585
+ bits,
3586
+ isWorking,
3587
+ raw: line.trim()
3588
+ });
3589
+ }
3590
+ return {
3591
+ gatewayReachable,
3592
+ feishuConfigInvalid,
3593
+ accounts,
3594
+ anyAccountWorking
3595
+ };
3596
+ }
3597
+ /**
3598
+ * Run `openclaw channels status --probe` and return a structured result.
3599
+ *
3600
+ * The command may exit non-zero when some bot accounts fail their probe — that
3601
+ * is still useful output. We therefore try to parse stdout even when the
3602
+ * process exits with a non-zero code, falling back to an unavailable result
3603
+ * only when there is genuinely no output to parse.
3604
+ *
3605
+ * @param timeoutMs Maximum wait time. Default is 60 s because v2026.4.x
3606
+ * lacks a per-request HTTP timeout and can block indefinitely.
3607
+ */
3608
+ function runChannelsProbe(timeoutMs = 6e4) {
3609
+ let stdout = "";
3610
+ let execError;
3611
+ try {
3612
+ stdout = (0, node_child_process.execSync)("openclaw channels status --probe", {
3613
+ encoding: "utf-8",
3614
+ timeout: timeoutMs,
3615
+ stdio: [
3616
+ "ignore",
3617
+ "pipe",
3618
+ "pipe"
3619
+ ]
3620
+ });
3621
+ } catch (e) {
3622
+ const err = e;
3623
+ const stdoutRaw = err.stdout;
3624
+ stdout = typeof stdoutRaw === "string" ? stdoutRaw : stdoutRaw?.toString("utf-8") ?? "";
3625
+ execError = err.message;
3626
+ const stderrRaw = err.stderr;
3627
+ const stderr = (typeof stderrRaw === "string" ? stderrRaw : stderrRaw?.toString("utf-8") ?? "").trim();
3628
+ if (stderr) console.error(`channels-probe: stderr from CLI: ${stderr}`);
3629
+ }
3630
+ if (stdout.trim()) return {
3631
+ available: true,
3632
+ ...parseChannelsProbeOutput(stdout)
3633
+ };
3634
+ return {
3635
+ available: false,
3636
+ gatewayReachable: false,
3637
+ feishuConfigInvalid: false,
3638
+ accounts: [],
3639
+ anyAccountWorking: false,
3640
+ error: execError ?? "no output from openclaw channels status --probe"
3641
+ };
3642
+ }
3643
+ //#endregion
3644
+ //#region src/rules/upgrade-lark-needed.ts
3645
+ /**
3646
+ * Detects the condition that warrants running `upgrade-lark`:
3647
+ * - feishu plugin version incompatible with current openclaw, OR
3648
+ * - openclaw channels status --probe reports feishu channel config invalid; AND
3649
+ * - channels are not working.
3650
+ *
3651
+ * Both conditions must be true simultaneously. If version is compatible and
3652
+ * feishu config is valid, or channels are working, the rule passes (no action needed).
3653
+ *
3654
+ * feishuConfigInvalid is read from the channels probe output rather than running a
3655
+ * separate `openclaw status` call, since only `openclaw channels status --probe`
3656
+ * reliably surfaces the schema validation error.
3657
+ *
3658
+ * profile: experimental — runs only in full sweep mode, not in standard doctor.
3659
+ * level: silent — telemetry/sweep-only, does not trigger page-level repair UI.
3660
+ */
3661
+ let UpgradeLarkNeededRule = class UpgradeLarkNeededRule extends DiagnoseRule {
3662
+ validate(ctx) {
3663
+ let versionIncompatible = false;
3664
+ try {
3665
+ versionIncompatible = needsLarkUpgrade(ctx);
3666
+ } catch {
3667
+ versionIncompatible = true;
3668
+ }
3669
+ let probeResult;
3670
+ try {
3671
+ probeResult = runChannelsProbe(3e4);
3672
+ } catch {
3673
+ return { pass: true };
3674
+ }
3675
+ const feishuConfigInvalid = probeResult.feishuConfigInvalid;
3676
+ if (!(versionIncompatible || feishuConfigInvalid)) return { pass: true };
3677
+ if (probeResult.anyAccountWorking) return { pass: true };
3678
+ return {
3679
+ pass: false,
3680
+ action: "upgrade_lark",
3681
+ message: `飞书插件需要升级且 channels 不可用(版本不兼容=${versionIncompatible}, feishu配置无效=${feishuConfigInvalid}),建议执行 upgrade-lark 命令升级飞书插件`
3682
+ };
3683
+ }
3684
+ };
3685
+ UpgradeLarkNeededRule = __decorate([Rule({
3686
+ key: "upgrade_lark_needed",
3687
+ description: "检测飞书插件版本不兼容且 channels 不可用,判断是否需要执行 upgrade-lark 升级",
3688
+ repairMode: "check-only",
3689
+ level: "silent",
3690
+ profile: "experimental",
3691
+ usesVars: ["recommendedOpenclawTag"]
3692
+ })], UpgradeLarkNeededRule);
3508
3693
  //#endregion
3509
3694
  //#region src/rules/cleanup-install-backup-dirs.ts
3510
3695
  const DIR_PREFIX = ".openclaw-install-";
@@ -3650,117 +3835,6 @@ LarkCliMissingForInstalledLarkPluginRule = __decorate([Rule({
3650
3835
  usesVars: ["recommendedOpenclawTag"]
3651
3836
  })], LarkCliMissingForInstalledLarkPluginRule);
3652
3837
  //#endregion
3653
- //#region src/rules/feishu-bot-channel-config.ts
3654
- /**
3655
- * Ensures each bot account's channel config is correct:
3656
- * 1. `allowFrom` contains its own `creatorOpenID` from larkApps
3657
- * 2. `appSecret` is either the canonical provider-ref or matches larkApps plaintext
3658
- *
3659
- * Covers both multi-account (channels.feishu.accounts) and single-account
3660
- * (channels.feishu.appId + allowFrom at top level) layouts.
3661
- */
3662
- let FeishuBotChannelConfigRule = class FeishuBotChannelConfigRule extends DiagnoseRule {
3663
- validate(ctx) {
3664
- const larkApps = ctx.vars.larkApps;
3665
- if (!larkApps || larkApps.length === 0) return { pass: true };
3666
- const feishu = asRecord(getNestedMap(ctx.config, "channels", "feishu"));
3667
- if (!feishu) return { pass: true };
3668
- const issues = [];
3669
- const accounts = asRecord(feishu.accounts);
3670
- if (accounts) for (const [accountId, account] of Object.entries(accounts)) {
3671
- const bot = asRecord(account);
3672
- if (!bot) continue;
3673
- const appId = bot.appId;
3674
- if (typeof appId !== "string" || !appId.startsWith("cli_")) continue;
3675
- const larkApp = larkApps.find((e) => e.larkAppID === appId);
3676
- if (!larkApp) continue;
3677
- this.checkBot(accountId, bot, larkApp, issues);
3678
- }
3679
- const singleAppId = feishu.appId;
3680
- if (typeof singleAppId === "string" && singleAppId.startsWith("cli_") && !accounts) {
3681
- const larkApp = larkApps.find((e) => e.larkAppID === singleAppId);
3682
- if (larkApp) this.checkBot("feishu", feishu, larkApp, issues);
3683
- }
3684
- if (issues.length === 0) return { pass: true };
3685
- return {
3686
- pass: false,
3687
- message: issues.join("; ")
3688
- };
3689
- }
3690
- /** Check a single bot entry (either an account object or the feishu channel itself).
3691
- * appSecret is validated based on its current type:
3692
- * - object → must match canonical provider-ref
3693
- * - string → must match larkApps plaintext
3694
- */
3695
- checkBot(label, bot, larkApp, issues) {
3696
- const creatorOpenID = larkApp.creatorOpenID;
3697
- const allowFrom = Array.isArray(bot.allowFrom) ? bot.allowFrom : [];
3698
- if (typeof creatorOpenID === "string" && creatorOpenID !== "") {
3699
- if (!allowFrom.includes(creatorOpenID)) issues.push(`${label} allowFrom missing creatorOpenID ${creatorOpenID.length > 8 ? creatorOpenID.slice(0, 4) + "***" + creatorOpenID.slice(-4) : "***"}`);
3700
- } else if (allowFrom.length === 0) issues.push(`${label} allowFrom is empty (creatorOpenID unavailable, cannot auto-fix)`);
3701
- const secret = bot.appSecret;
3702
- if (typeof secret === "object" && secret !== null && !Array.isArray(secret)) {
3703
- if (!matchMap(secret, DEFAULT_FEISHU_APP_SECRET)) issues.push(`${label} appSecret is a provider-ref but not the canonical one`);
3704
- } else if (typeof secret === "string") {
3705
- if (secret !== larkApp.appSecret) issues.push(`${label} appSecret plaintext mismatch`);
3706
- } else issues.push(`${label} appSecret has unexpected type ${typeof secret}`);
3707
- }
3708
- repair(ctx) {
3709
- const larkApps = ctx.vars.larkApps;
3710
- if (!larkApps || larkApps.length === 0) return;
3711
- const feishu = asRecord(getNestedMap(ctx.config, "channels", "feishu"));
3712
- if (!feishu) return;
3713
- const accounts = asRecord(feishu.accounts);
3714
- if (accounts) for (const [, account] of Object.entries(accounts)) {
3715
- const bot = asRecord(account);
3716
- if (!bot) continue;
3717
- const appId = bot.appId;
3718
- if (typeof appId !== "string" || !appId.startsWith("cli_")) continue;
3719
- const larkApp = larkApps.find((e) => e.larkAppID === appId);
3720
- if (!larkApp) continue;
3721
- this.fixBot(bot, larkApp);
3722
- }
3723
- const singleAppId = feishu.appId;
3724
- if (typeof singleAppId === "string" && singleAppId.startsWith("cli_") && !accounts) {
3725
- const larkApp = larkApps.find((e) => e.larkAppID === singleAppId);
3726
- if (larkApp) this.fixBot(feishu, larkApp);
3727
- }
3728
- }
3729
- /** Fix a single bot entry in-place.
3730
- * appSecret is repaired based on its current type:
3731
- * - object → fix to canonical provider-ref
3732
- * - string → fix to larkApps plaintext
3733
- */
3734
- fixBot(bot, larkApp) {
3735
- const creatorOpenID = larkApp.creatorOpenID;
3736
- if (typeof creatorOpenID === "string" && creatorOpenID !== "") {
3737
- const allowFrom = Array.isArray(bot.allowFrom) ? [...bot.allowFrom] : [];
3738
- if (!allowFrom.includes(creatorOpenID)) {
3739
- allowFrom.push(creatorOpenID);
3740
- bot.allowFrom = allowFrom;
3741
- }
3742
- }
3743
- const secret = bot.appSecret;
3744
- if (typeof secret === "object" && secret !== null && !Array.isArray(secret)) {
3745
- if (!matchMap(secret, DEFAULT_FEISHU_APP_SECRET)) bot.appSecret = { ...DEFAULT_FEISHU_APP_SECRET };
3746
- } else if (typeof secret === "string") {
3747
- if (secret !== larkApp.appSecret) bot.appSecret = larkApp.appSecret;
3748
- } else bot.appSecret = { ...DEFAULT_FEISHU_APP_SECRET };
3749
- }
3750
- };
3751
- FeishuBotChannelConfigRule = __decorate([Rule({
3752
- key: "feishu_bot_channel_config",
3753
- description: "确保飞书配置中 bot 账号的 allowFrom 包含其创建者 openID 且 appSecret 值正确",
3754
- dependsOn: [
3755
- "config_syntax_check",
3756
- "feishu_default_account",
3757
- "feishu_bot_id"
3758
- ],
3759
- repairMode: "standard",
3760
- usesVars: ["larkApps"],
3761
- level: "critical"
3762
- })], FeishuBotChannelConfigRule);
3763
- //#endregion
3764
3838
  //#region src/check.ts
3765
3839
  /** Telemetry-aware entry: returns both the legacy CheckResult (for stdout)
3766
3840
  * AND a DoctorReport-shape payload (for `openclaw.report_cli_run`). The
@@ -4224,6 +4298,9 @@ const PROVIDER_FILE_PATH = "/home/gem/workspace/.force/openclaw/miaoda-provider-
4224
4298
  const SECRETS_FILE_PATH = "/home/gem/workspace/.force/openclaw/miaoda-openclaw-secrets.json";
4225
4299
  /** Absolute path to the openclaw config JSON. */
4226
4300
  const CONFIG_PATH = `${WORKSPACE_DIR}/openclaw.json`;
4301
+ function upgradeLarkLogFile(runId) {
4302
+ return `${DIAGNOSE_DIR}/upgrade-lark-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 19).replace(/:/g, "-")}-${runId.slice(0, 8)}.log`;
4303
+ }
4227
4304
  //#endregion
4228
4305
  //#region src/run-log.ts
4229
4306
  let currentRunContext;
@@ -4360,10 +4437,9 @@ function makeLogger(logFile) {
4360
4437
  /**
4361
4438
  * Start an async reset task: spawn a detached child process and return the taskId.
4362
4439
  *
4363
- * The child process runs: node cli.js reset --worker --task-id=xxx
4364
- * The worker fetches ctx from innerApi itself — no --ctx passthrough.
4440
+ * The child process runs: node cli.js reset --worker --task-id=xxx --ctx=base64
4365
4441
  */
4366
- function startAsyncReset() {
4442
+ function startAsyncReset(ctxBase64) {
4367
4443
  const taskId = (0, node_crypto.randomUUID)();
4368
4444
  const resultFile = resetResultFile(taskId);
4369
4445
  const log = makeLogger(resetLogFile(taskId));
@@ -4387,7 +4463,8 @@ function startAsyncReset() {
4387
4463
  process.argv[1],
4388
4464
  "reset",
4389
4465
  "--worker",
4390
- `--task-id=${taskId}`
4466
+ `--task-id=${taskId}`,
4467
+ `--ctx=${ctxBase64}`
4391
4468
  ], {
4392
4469
  detached: true,
4393
4470
  stdio: "ignore",
@@ -6901,60 +6978,6 @@ function mergeCoreBackupAndOrigins(configPath, vars, resetData, log) {
6901
6978
  log(`allowedOrigins: added ${added.length} (${JSON.stringify(added)}), total now ${mergedOrigins.length}`);
6902
6979
  }
6903
6980
  /**
6904
- * Fix bot account allowFrom and appSecret using larkApps from innerApi.
6905
- *
6906
- * For each bot account (key starts with `bot-cli_`):
6907
- * - allowFrom must contain the bot's own creatorOpenID from larkApps
6908
- * - appSecret must be either the canonical provider-ref or match larkApps plaintext
6909
- *
6910
- * Runs after mergeCoreBackupAndOrigins so it operates on the final config state.
6911
- */
6912
- function fixBotChannelConfig(configPath, larkApps, log) {
6913
- if (!larkApps || larkApps.length === 0) {
6914
- log("no larkApps data, skip bot channel config fix");
6915
- return;
6916
- }
6917
- const config = loadJSON5().parse(node_fs.default.readFileSync(configPath, "utf-8"));
6918
- const accounts = asRecord(getNestedMap(config, "channels", "feishu")?.accounts);
6919
- if (!accounts) {
6920
- log("no feishu accounts in config, skip bot channel config fix");
6921
- return;
6922
- }
6923
- let fixCount = 0;
6924
- for (const [, account] of Object.entries(accounts)) {
6925
- const bot = asRecord(account);
6926
- if (!bot) continue;
6927
- const appId = bot.appId;
6928
- if (typeof appId !== "string" || !appId.startsWith("cli_")) continue;
6929
- const larkApp = larkApps.find((e) => e.larkAppID === appId);
6930
- if (!larkApp) continue;
6931
- const creatorOpenID = larkApp.creatorOpenID;
6932
- if (typeof creatorOpenID === "string" && creatorOpenID !== "") {
6933
- const allowFrom = Array.isArray(bot.allowFrom) ? [...bot.allowFrom] : [];
6934
- if (!allowFrom.includes(creatorOpenID)) {
6935
- allowFrom.push(creatorOpenID);
6936
- bot.allowFrom = allowFrom;
6937
- fixCount++;
6938
- }
6939
- }
6940
- const secret = bot.appSecret;
6941
- let needsFix = false;
6942
- if (typeof secret === "object" && secret !== null && !Array.isArray(secret)) {
6943
- if (!matchMap(secret, DEFAULT_FEISHU_APP_SECRET)) needsFix = true;
6944
- } else if (typeof secret === "string") {
6945
- if (secret !== larkApp.appSecret) needsFix = true;
6946
- } else needsFix = true;
6947
- if (needsFix) {
6948
- bot.appSecret = { ...DEFAULT_FEISHU_APP_SECRET };
6949
- fixCount++;
6950
- }
6951
- }
6952
- if (fixCount > 0) {
6953
- node_fs.default.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8");
6954
- log(`fixed ${fixCount} bot channel config issue(s) (allowFrom/appSecret)`);
6955
- } else log("bot channel config ok, no fixes needed");
6956
- }
6957
- /**
6958
6981
  * Step 7: Verify startup scripts landed in configDir/scripts/.
6959
6982
  *
6960
6983
  * Scripts are extracted directly to configDir/scripts/ during stageTemplate —
@@ -7099,7 +7122,6 @@ async function runReset(input, taskId, resultFile) {
7099
7122
  await step5InstallOpenclaw(openclawTag, ossFileMap, log);
7100
7123
  step(6);
7101
7124
  mergeCoreBackupAndOrigins(configPath, vars, resetData, log);
7102
- fixBotChannelConfig(configPath, vars.larkApps, log);
7103
7125
  step(7);
7104
7126
  verifyStartupScripts(configDir, log);
7105
7127
  step(8);
@@ -7898,8 +7920,7 @@ function normalizeCtx(raw) {
7898
7920
  reset: {
7899
7921
  templateVars: r.reset.templateVars ?? {},
7900
7922
  coreBackup: r.reset.coreBackup
7901
- },
7902
- larkApps: Array.isArray(r.larkApps) ? r.larkApps : []
7923
+ }
7903
7924
  };
7904
7925
  }
7905
7926
  const vars = r.vars ?? {};
@@ -7924,8 +7945,7 @@ function normalizeCtx(raw) {
7924
7945
  reset: {
7925
7946
  templateVars: resetData.templateVars ?? {},
7926
7947
  coreBackup: resetData.coreBackup
7927
- },
7928
- larkApps: Array.isArray(r.larkApps) ? r.larkApps : []
7948
+ }
7929
7949
  };
7930
7950
  }
7931
7951
  function fillApp(src) {
@@ -7990,8 +8010,7 @@ function buildCheckInput(raw, configPathOverride) {
7990
8010
  providerFilePath: PROVIDER_FILE_PATH,
7991
8011
  secretsFilePath: SECRETS_FILE_PATH,
7992
8012
  templateVars: ctx.app.templateVars,
7993
- recommendedOpenclawTag: ctx.app.recommendedOpenclawTag,
7994
- larkApps: ctx.larkApps
8013
+ recommendedOpenclawTag: ctx.app.recommendedOpenclawTag
7995
8014
  },
7996
8015
  templateVars: ctx.app.templateVars
7997
8016
  };
@@ -8023,8 +8042,7 @@ function buildRepairInput(raw, configPathOverride) {
8023
8042
  providerFilePath: PROVIDER_FILE_PATH,
8024
8043
  secretsFilePath: SECRETS_FILE_PATH,
8025
8044
  templateVars: ctx.app.templateVars,
8026
- recommendedOpenclawTag: ctx.app.recommendedOpenclawTag,
8027
- larkApps: ctx.larkApps
8045
+ recommendedOpenclawTag: ctx.app.recommendedOpenclawTag
8028
8046
  },
8029
8047
  repairData: {
8030
8048
  secretsContent: ctx.secrets.secretsContent,
@@ -8060,8 +8078,7 @@ function buildResetInput(raw, configPathOverride) {
8060
8078
  providerFilePath: PROVIDER_FILE_PATH,
8061
8079
  secretsFilePath: SECRETS_FILE_PATH,
8062
8080
  templateVars: ctx.app.templateVars,
8063
- recommendedOpenclawTag: ctx.app.recommendedOpenclawTag,
8064
- larkApps: ctx.larkApps
8081
+ recommendedOpenclawTag: ctx.app.recommendedOpenclawTag
8065
8082
  },
8066
8083
  resetData: {
8067
8084
  templateVars: ctx.reset.templateVars,
@@ -10371,7 +10388,7 @@ async function reportCliRun(opts) {
10371
10388
  //#region src/help.ts
10372
10389
  const BIN = "mclaw-diagnose";
10373
10390
  function versionBanner() {
10374
- return `v0.1.14-alpha.7`;
10391
+ return `v0.1.14-alpha.8`;
10375
10392
  }
10376
10393
  const COMMANDS = [
10377
10394
  {
@@ -10475,12 +10492,16 @@ EXIT CODES
10475
10492
  hidden: true,
10476
10493
  summary: "Run rule-engine check only",
10477
10494
  help: `USAGE
10478
- ${BIN} check
10495
+ ${BIN} check [--ctx=<base64>]
10479
10496
 
10480
10497
  DESCRIPTION
10481
10498
  Runs the rule engine against the sandbox's current openclaw config and
10482
- returns { failedRules }. Ctx is fetched from innerapi automatically.
10483
- End-users should prefer \`doctor\`.
10499
+ returns { failedRules }. Used by sandbox_console's push-style callers
10500
+ that already own the ctx — end-users should prefer \`doctor\`.
10501
+
10502
+ OPTIONS
10503
+ --ctx=<base64> Opaque ctx JSON (base64). When absent, fetched from
10504
+ innerapi (same path as doctor).
10484
10505
  `
10485
10506
  },
10486
10507
  {
@@ -10488,11 +10509,16 @@ DESCRIPTION
10488
10509
  hidden: true,
10489
10510
  summary: "Apply standard-mode repairs",
10490
10511
  help: `USAGE
10491
- ${BIN} repair
10512
+ ${BIN} repair [--ctx=<base64>]
10492
10513
 
10493
10514
  DESCRIPTION
10494
- Runs repair for the failing rules. Ctx is fetched from innerapi
10495
- automatically. End-users should use \`doctor --fix\` instead.
10515
+ Runs repair for the failing rules listed inside the ctx's repairData.
10516
+ Intended for sandbox_console's push path — end-users should use
10517
+ \`doctor --fix\` instead.
10518
+
10519
+ OPTIONS
10520
+ --ctx=<base64> Opaque ctx JSON (base64). When absent, fetched from
10521
+ innerapi.
10496
10522
  `
10497
10523
  },
10498
10524
  {
@@ -10500,15 +10526,14 @@ DESCRIPTION
10500
10526
  hidden: true,
10501
10527
  summary: "Re-initialize sandbox via the 9-step reset pipeline",
10502
10528
  help: `USAGE
10503
- ${BIN} reset --async
10504
- ${BIN} reset --worker --task-id=<id>
10529
+ ${BIN} reset --async [--ctx=<base64>]
10530
+ ${BIN} reset --worker --task-id=<id> [--ctx=<base64>]
10505
10531
 
10506
10532
  DESCRIPTION
10507
10533
  Two-phase pipeline driven asynchronously: the --async invocation spawns
10508
10534
  a detached worker and returns { taskId } immediately; the --worker
10509
10535
  invocation (spawned by --async) runs the actual 9 steps and writes
10510
10536
  progress to /tmp/openclaw-diagnose/reset-<taskId>.json.
10511
- Ctx is fetched from innerapi automatically.
10512
10537
 
10513
10538
  Poll progress with \`${BIN} get_reset_task --task-id=<id>\`.
10514
10539
 
@@ -10516,6 +10541,7 @@ OPTIONS
10516
10541
  --async Start a detached worker and return taskId on stdout.
10517
10542
  --worker Internal — run the 9-step pipeline (launched by --async).
10518
10543
  --task-id=<id> Required with --worker; identifies the progress file.
10544
+ --ctx=<base64> Opaque ctx JSON; fetched from innerapi when absent.
10519
10545
  `
10520
10546
  },
10521
10547
  {
@@ -10538,7 +10564,7 @@ OPTIONS
10538
10564
  hidden: true,
10539
10565
  summary: "Download + install the openclaw tarball",
10540
10566
  help: `USAGE
10541
- ${BIN} install-openclaw <tag> [--oss_file_map=<base64>]
10567
+ ${BIN} install-openclaw <tag> [--ctx=<base64> | --oss_file_map=<base64>]
10542
10568
 
10543
10569
  DESCRIPTION
10544
10570
  Downloads the openclaw@<tag> tgz via the signed OSS URL found in the
@@ -10550,9 +10576,9 @@ ARGUMENTS
10550
10576
  <tag> Openclaw version tag, e.g. 2026.4.11.
10551
10577
 
10552
10578
  OPTIONS
10579
+ --ctx=<base64> Opaque ctx; ossFileMap is extracted from it.
10553
10580
  --oss_file_map=... Pre-built OSS URL map (base64 JSON); skips innerapi
10554
- entirely. When absent, ossFileMap is fetched from
10555
- innerapi automatically.
10581
+ entirely. Wins over --ctx when both provided.
10556
10582
  `
10557
10583
  },
10558
10584
  {
@@ -10578,7 +10604,8 @@ OPTIONS
10578
10604
  --home_base=<dir> Override the /home/gem base (tests).
10579
10605
  --config_path=<p> Override the openclaw.json path (tests).
10580
10606
  --skip-config-update Leave plugins.installs in openclaw.json untouched.
10581
- --oss_file_map=... Pre-built OSS URL map (base64 JSON); skips innerapi.
10607
+ --ctx=<base64> Opaque ctx; see install-openclaw for semantics.
10608
+ --oss_file_map=... Pre-built OSS URL map (base64 JSON).
10582
10609
  `
10583
10610
  },
10584
10611
  {
@@ -10605,6 +10632,7 @@ OPTIONS
10605
10632
  --cli=<name> CLI package to install by short name or scoped
10606
10633
  packageName (repeatable, at least one required).
10607
10634
  --home_base=<dir> Override the /home/gem base (tests).
10635
+ --ctx=<base64> Opaque ctx; ossFileMap is extracted from it.
10608
10636
  --oss_file_map=... Pre-built OSS URL map (base64 JSON); skips innerapi.
10609
10637
 
10610
10638
  EXAMPLES
@@ -10658,6 +10686,46 @@ OPTIONS
10658
10686
  EXIT CODES
10659
10687
  0 Success or skipped (prerequisites not met).
10660
10688
  1 Secret/path unresolvable, lark-cli failed, or config unreadable.
10689
+ `
10690
+ },
10691
+ {
10692
+ name: "upgrade-lark",
10693
+ hidden: false,
10694
+ summary: "Upgrade the Feishu/Lark plugin via @larksuite/openclaw-lark-tools",
10695
+ help: `USAGE
10696
+ ${BIN} upgrade-lark [--scene=<scene>] [--caller=<n>] [--trace-id=<id>]
10697
+
10698
+ DESCRIPTION
10699
+ Upgrades the Feishu/Lark plugin by running:
10700
+ npx -y @larksuite/openclaw-lark-tools update --use-existing
10701
+
10702
+ Before the upgrade, the following files are backed up:
10703
+ - openclaw.json
10704
+ - extensions/openclaw-lark/ (if present)
10705
+ - extensions/feishu-openclaw-plugin/ (if present)
10706
+ After the upgrade, the result is validated:
10707
+ - feishu.accounts bot count must not decrease
10708
+ - gateway config structure must remain valid (port/mode/bind/auth/trustedProxies)
10709
+ If the upgrade command fails, or validation fails, the backed-up files are
10710
+ restored to roll back the changes.
10711
+
10712
+ Execution is logged to /tmp/openclaw-diagnose/upgrade-lark-<runId>.log.
10713
+
10714
+ Output is a single JSON object on stdout:
10715
+ { "ok": true, "stdout": "...", "stderr": "...", "logFile": "..." }
10716
+ { "ok": false, "error": "...", "stderr": "...", "exitCode": 1,
10717
+ "rollbackOk": true, "validationError": "...", "logFile": "..." }
10718
+
10719
+ OPTIONS
10720
+ --scene=<scene> Telemetry label forwarded to Slardar only.
10721
+ Known values: PageUpgradeLark, etc. Custom strings accepted.
10722
+ --caller=<name> Optional metadata passed to innerapi.
10723
+ --trace-id=<id> Optional log-correlation id.
10724
+
10725
+ EXIT CODES
10726
+ 0 Success: upgrade ran and all validations passed.
10727
+ 1 Failure: npx error, validation failed, or git commit failed.
10728
+ File rollback was attempted (see rollbackOk in the JSON output).
10661
10729
  `
10662
10730
  },
10663
10731
  {
@@ -10691,6 +10759,41 @@ EXAMPLES
10691
10759
  ${BIN} rules # all rules
10692
10760
  ${BIN} rules --rule=gateway # single rule
10693
10761
  ${BIN} rules --rule=gateway --rule=feishu_channel # multiple rules
10762
+ `
10763
+ },
10764
+ {
10765
+ name: "channels-probe",
10766
+ hidden: true,
10767
+ summary: "Check feishu channel health via openclaw channels status --probe",
10768
+ help: `USAGE
10769
+ ${BIN} channels-probe [--timeout=<ms>]
10770
+
10771
+ DESCRIPTION
10772
+ Runs \`openclaw channels status --probe\` and returns a structured JSON
10773
+ summary of whether the current environment's feishu channels are
10774
+ configured and working correctly.
10775
+
10776
+ Output:
10777
+ {
10778
+ "available": true,
10779
+ "gatewayReachable": true,
10780
+ "accounts": [
10781
+ { "id": "default", "bits": ["enabled","configured","running","works"],
10782
+ "isWorking": true, "raw": "- Feishu default: ..." }
10783
+ ],
10784
+ "anyAccountWorking": true
10785
+ }
10786
+
10787
+ An account is considered working when:
10788
+ enabled ∧ configured ∧ ( works ∨ ( running ∧ no error: ∧ no probe failed ) )
10789
+
10790
+ "available": false means the CLI invocation itself failed (openclaw not
10791
+ found, gateway unreachable, or no parseable output returned).
10792
+
10793
+ OPTIONS
10794
+ --timeout=<ms> Max wait in milliseconds (default: 60000). The probe
10795
+ can hang indefinitely on openclaw v2026.4.x due to a
10796
+ missing per-request HTTP timeout — set this accordingly.
10694
10797
  `
10695
10798
  },
10696
10799
  {
@@ -10711,7 +10814,8 @@ OPTIONS
10711
10814
  --role=<role> Package role (e.g. template, config).
10712
10815
  --name=<name> Package name within the role.
10713
10816
  --dir=<dir> Target dir (defaults to dirname(pkg.installPath)).
10714
- --oss_file_map=... Pre-built OSS URL map (base64 JSON); skips innerapi.
10817
+ --ctx=<base64> Opaque ctx; ossFileMap is extracted from it.
10818
+ --oss_file_map=... Pre-built OSS URL map (base64 JSON).
10715
10819
  `
10716
10820
  }
10717
10821
  ];
@@ -10787,31 +10891,31 @@ function planVarsFields(opts = {}) {
10787
10891
  *
10788
10892
  * Per-command group needs:
10789
10893
  *
10790
- * doctor / check app + larkApps
10791
- * repair app + secrets + larkApps
10792
- * reset app + secrets + install + reset + larkApps
10894
+ * doctor / check app (rule-driven)
10895
+ * repair app + secrets (writes secretsContent / providerKeyContent)
10896
+ * reset app + secrets + install + reset (the works)
10793
10897
  * install-* install only
10794
10898
  *
10795
10899
  * Empty result (`{}`) means "no group needed" — the CLI can skip the
10796
10900
  * `fetchCtxViaInnerApi` call entirely and run with a synthetic empty ctx.
10901
+ * Happens e.g. when the user pinned `--rule=<key>` to a vars-free rule on
10902
+ * `doctor`.
10797
10903
  */
10798
10904
  function planCtxPopulate(opts) {
10799
10905
  if (opts.command === "install") return { install: true };
10800
10906
  const populate = {};
10801
- if (planVarsFields({
10907
+ const appFields = planVarsFields({
10802
10908
  disabled: opts.disabled,
10803
10909
  onlyRules: opts.onlyRules,
10804
10910
  profile: opts.profile
10805
- }).length > 0) populate.app = true;
10806
- if (opts.command === "repair") {
10807
- populate.secrets = true;
10808
- populate.larkApps = true;
10809
- } else if (opts.command === "reset") {
10911
+ });
10912
+ if (appFields.length > 0) populate.app = appFields;
10913
+ if (opts.command === "repair") populate.secrets = true;
10914
+ else if (opts.command === "reset") {
10810
10915
  populate.secrets = true;
10811
10916
  populate.install = true;
10812
10917
  populate.reset = true;
10813
- populate.larkApps = true;
10814
- } else if (opts.command === "doctor" || opts.command === "check") populate.larkApps = true;
10918
+ }
10815
10919
  return populate;
10816
10920
  }
10817
10921
  //#endregion
@@ -10865,11 +10969,372 @@ function reportDoctorRunToSlardar(opts) {
10865
10969
  }
10866
10970
  });
10867
10971
  }
10972
+ function readLogFile(filePath) {
10973
+ try {
10974
+ return node_fs.default.readFileSync(filePath, "utf-8");
10975
+ } catch {
10976
+ return "";
10977
+ }
10978
+ }
10979
+ function reportUpgradeLarkToSlardar(opts) {
10980
+ console.error(`[slardar] upgrade_lark_run scene=${opts.scene ?? ""} success=${opts.success} exitCode=${opts.exitCode ?? ""} rollbackOk=${opts.rollbackOk ?? ""}`);
10981
+ const logContent = readLogFile(opts.logFile);
10982
+ reportTask({
10983
+ eventName: "upgrade_lark_run",
10984
+ durationMs: opts.durationMs,
10985
+ status: opts.success ? "success" : "failed",
10986
+ extraCategories: {
10987
+ scene: opts.scene ?? "",
10988
+ exit_code: String(opts.exitCode ?? ""),
10989
+ rollback_ok: opts.rollbackOk != null ? String(opts.rollbackOk) : "",
10990
+ validation_error: opts.validationError ?? "",
10991
+ error_msg: opts.error ?? "",
10992
+ log_content: logContent
10993
+ }
10994
+ });
10995
+ }
10996
+ //#endregion
10997
+ //#region src/upgrade-lark.ts
10998
+ /** Plugin directories under extensions/ that are backed up before upgrade */
10999
+ const FEISHU_PLUGIN_DIRS = ["openclaw-lark", "feishu-openclaw-plugin"];
11000
+ function backupFiles(opts) {
11001
+ const { workspaceDir, configPath, backupDir, log } = opts;
11002
+ try {
11003
+ node_fs.default.mkdirSync(backupDir, { recursive: true });
11004
+ log(`backup dir: ${backupDir}`);
11005
+ if (node_fs.default.existsSync(configPath)) {
11006
+ const stat = node_fs.default.statSync(configPath);
11007
+ node_fs.default.copyFileSync(configPath, node_path.default.join(backupDir, "openclaw.json"));
11008
+ log(` backed up: openclaw.json (${stat.size} bytes)`);
11009
+ } else log(` skipped: openclaw.json (not found)`);
11010
+ const extSrc = node_path.default.join(workspaceDir, "extensions");
11011
+ for (const pluginDir of FEISHU_PLUGIN_DIRS) {
11012
+ const src = node_path.default.join(extSrc, pluginDir);
11013
+ if (node_fs.default.existsSync(src)) {
11014
+ const dst = node_path.default.join(backupDir, "extensions", pluginDir);
11015
+ node_fs.default.cpSync(src, dst, { recursive: true });
11016
+ const version = readPkgVersion(node_path.default.join(src, "package.json"));
11017
+ log(` backed up: extensions/${pluginDir}${version ? ` (version: ${version})` : ""}`);
11018
+ } else log(` skipped: extensions/${pluginDir} (not found)`);
11019
+ }
11020
+ return { ok: true };
11021
+ } catch (e) {
11022
+ return {
11023
+ ok: false,
11024
+ error: `backup failed: ${e.message}`
11025
+ };
11026
+ }
11027
+ }
11028
+ function restoreFiles(opts) {
11029
+ const { workspaceDir, configPath, backupDir, log } = opts;
11030
+ try {
11031
+ const configBackup = node_path.default.join(backupDir, "openclaw.json");
11032
+ if (node_fs.default.existsSync(configBackup)) {
11033
+ node_fs.default.copyFileSync(configBackup, configPath);
11034
+ log(` restored: openclaw.json`);
11035
+ }
11036
+ const extDst = node_path.default.join(workspaceDir, "extensions");
11037
+ for (const pluginDir of FEISHU_PLUGIN_DIRS) {
11038
+ const backupSrc = node_path.default.join(backupDir, "extensions", pluginDir);
11039
+ if (node_fs.default.existsSync(backupSrc)) {
11040
+ const dst = node_path.default.join(extDst, pluginDir);
11041
+ if (node_fs.default.existsSync(dst)) node_fs.default.rmSync(dst, {
11042
+ recursive: true,
11043
+ force: true
11044
+ });
11045
+ node_fs.default.cpSync(backupSrc, dst, { recursive: true });
11046
+ log(` restored: extensions/${pluginDir}`);
11047
+ }
11048
+ }
11049
+ return true;
11050
+ } catch (e) {
11051
+ log(` restore error: ${e.message}`);
11052
+ return false;
11053
+ }
11054
+ }
11055
+ function readPkgVersion(pkgPath) {
11056
+ try {
11057
+ const pkg = JSON.parse(node_fs.default.readFileSync(pkgPath, "utf-8"));
11058
+ return typeof pkg.version === "string" ? pkg.version : null;
11059
+ } catch {
11060
+ return null;
11061
+ }
11062
+ }
11063
+ function snapshotVersions(cwd, log) {
11064
+ const ocResult = (0, node_child_process.spawnSync)("openclaw", ["--version"], {
11065
+ cwd,
11066
+ encoding: "utf-8",
11067
+ stdio: [
11068
+ "ignore",
11069
+ "pipe",
11070
+ "pipe"
11071
+ ],
11072
+ timeout: 5e3
11073
+ });
11074
+ const ocRaw = (ocResult.stdout ?? "").trim() || (ocResult.stderr ?? "").trim();
11075
+ const extDir = node_path.default.join(cwd, "extensions");
11076
+ const larkPkg = node_path.default.join(extDir, "openclaw-lark", "package.json");
11077
+ const feishuPkg = node_path.default.join(extDir, "feishu-openclaw-plugin", "package.json");
11078
+ log(` version-check paths: ${larkPkg} [${node_fs.default.existsSync(larkPkg) ? "exists" : "missing"}]`);
11079
+ log(` version-check paths: ${feishuPkg} [${node_fs.default.existsSync(feishuPkg) ? "exists" : "missing"}]`);
11080
+ return {
11081
+ openclaw: ocRaw || null,
11082
+ openclawLark: readPkgVersion(larkPkg),
11083
+ feishuOpenclawPlugin: readPkgVersion(feishuPkg)
11084
+ };
11085
+ }
11086
+ function logVersionSnapshot(label, v, log) {
11087
+ log(`${label}: openclaw=${v.openclaw ?? "n/a"} openclaw-lark=${v.openclawLark ?? "n/a"} feishu-openclaw-plugin=${v.feishuOpenclawPlugin ?? "n/a"}`);
11088
+ }
11089
+ function countFeishuBots(configPath) {
11090
+ try {
11091
+ const raw = node_fs.default.readFileSync(configPath, "utf-8");
11092
+ const config = loadJSON5().parse(raw);
11093
+ const accounts = getNestedMap(config, "channels", "feishu", "accounts");
11094
+ if (accounts) return Object.keys(accounts).length;
11095
+ const feishu = getNestedMap(config, "channels", "feishu");
11096
+ return typeof feishu?.appId === "string" && feishu.appId ? 1 : 0;
11097
+ } catch {
11098
+ return 0;
11099
+ }
11100
+ }
11101
+ /** Run channels probe, log results, and return the result. Never throws. */
11102
+ function probeChannels(label, log, timeoutMs) {
11103
+ try {
11104
+ const r = runChannelsProbe(timeoutMs);
11105
+ log(` ${label} available=${r.available} anyAccountWorking=${r.anyAccountWorking}`);
11106
+ if (r.error) log(` ${label} error: ${r.error}`);
11107
+ if (r.gatewayReachable != null) log(` ${label} gatewayReachable: ${r.gatewayReachable}`);
11108
+ for (const acct of r.accounts ?? []) log(` ${label} account ${acct.id}: isWorking=${acct.isWorking} bits=[${acct.bits.join(",")}]`);
11109
+ return r;
11110
+ } catch (e) {
11111
+ log(` ${label} channels probe threw: ${e.message}`);
11112
+ return {
11113
+ available: false,
11114
+ gatewayReachable: false,
11115
+ feishuConfigInvalid: false,
11116
+ accounts: [],
11117
+ anyAccountWorking: false
11118
+ };
11119
+ }
11120
+ }
11121
+ function runUpgradeLark(opts) {
11122
+ const cwd = opts.cwd ?? "/home/gem/workspace/agent";
11123
+ const configPath = opts.configPath ?? CONFIG_PATH;
11124
+ const logFile = upgradeLarkLogFile(opts.runId);
11125
+ const log = makeLogger(logFile);
11126
+ const fsOpts = {
11127
+ workspaceDir: cwd,
11128
+ configPath,
11129
+ backupDir: node_path.default.join(opts.backupBaseDir ?? "/tmp/openclaw-diagnose", `upgrade-lark-backup-${opts.runId}`),
11130
+ log
11131
+ };
11132
+ const cliScript = opts.cliScript ?? process.argv[1];
11133
+ const statusCheckDelayMs = opts.statusCheckDelayMs ?? 5e3;
11134
+ log(`${"=".repeat(60)}`);
11135
+ log(`upgrade-lark started runId=${opts.runId}`);
11136
+ log(` cwd : ${cwd}`);
11137
+ log(` configPath : ${configPath}`);
11138
+ log(`${"=".repeat(60)}`);
11139
+ log("");
11140
+ log("── [Pre-check A] channels probe(升级前)────────────────");
11141
+ const beforeChannels = probeChannels("before", log, 3e4);
11142
+ log("");
11143
+ log("── [Pre-check B] 版本兼容预检 ───────────────────────────");
11144
+ let versionIncompatible = false;
11145
+ try {
11146
+ const rawConfig = node_fs.default.readFileSync(configPath, "utf-8");
11147
+ versionIncompatible = needsLarkUpgrade({
11148
+ config: loadJSON5().parse(rawConfig),
11149
+ configPath,
11150
+ vars: {},
11151
+ providerDeps: {
11152
+ usesMiaodaProvider: false,
11153
+ usesMiaodaSecretProvider: false
11154
+ }
11155
+ });
11156
+ log(` version-compat pre-check: ${versionIncompatible ? "NEEDS_UPGRADE" : "ok"}`);
11157
+ } catch (e) {
11158
+ log(` version-compat pre-check error: ${e.message} — treating as needs-upgrade`);
11159
+ versionIncompatible = true;
11160
+ }
11161
+ const feishuConfigInvalid = beforeChannels.feishuConfigInvalid;
11162
+ log(` feishu config invalid : ${feishuConfigInvalid}`);
11163
+ log("");
11164
+ log("── [Gate] 升级前置条件检查 ───────────────────────────────");
11165
+ log(` versionIncompatible : ${versionIncompatible}`);
11166
+ log(` feishuConfigInvalid : ${feishuConfigInvalid}`);
11167
+ log(` channels working before: ${beforeChannels.anyAccountWorking}`);
11168
+ if (!(versionIncompatible || feishuConfigInvalid)) {
11169
+ const reason = "version compatible and feishu channel config valid — upgrade not needed";
11170
+ log(` SKIP: ${reason}`);
11171
+ log(`${"=".repeat(60)}`);
11172
+ log("upgrade-lark skipped (pre-check gate)");
11173
+ log(`${"=".repeat(60)}`);
11174
+ return {
11175
+ ok: true,
11176
+ skipped: true,
11177
+ skipReason: reason,
11178
+ logFile
11179
+ };
11180
+ }
11181
+ if (beforeChannels.anyAccountWorking) {
11182
+ const reason = "channels are working — upgrade not needed (issue detected but system is functional)";
11183
+ log(` SKIP: ${reason}`);
11184
+ log(`${"=".repeat(60)}`);
11185
+ log("upgrade-lark skipped (pre-check gate)");
11186
+ log(`${"=".repeat(60)}`);
11187
+ return {
11188
+ ok: true,
11189
+ skipped: true,
11190
+ skipReason: reason,
11191
+ logFile
11192
+ };
11193
+ }
11194
+ log(` PROCEED: requiresLarkUpgrade=true (version=${versionIncompatible}, feishuConfig=${feishuConfigInvalid}) AND channels not working → running upgrade`);
11195
+ log("");
11196
+ log("── [1/6] 文件备份 ────────────────────────────────────────");
11197
+ log(`before-state: botCount=${countFeishuBots(configPath)}`);
11198
+ const backup = backupFiles(fsOpts);
11199
+ if (!backup.ok) {
11200
+ log(`ERROR: ${backup.error}`);
11201
+ return {
11202
+ ok: false,
11203
+ error: backup.error,
11204
+ logFile
11205
+ };
11206
+ }
11207
+ log("backup: ok");
11208
+ logVersionSnapshot("before-versions", snapshotVersions(cwd, log), log);
11209
+ log("");
11210
+ log("── [2/6] 清理本地 openclaw shim ─────────────────────────");
11211
+ const localOpenclawBin = node_path.default.join(cwd, "node_modules", ".bin", "openclaw");
11212
+ if (node_fs.default.existsSync(localOpenclawBin)) try {
11213
+ node_fs.default.rmSync(localOpenclawBin);
11214
+ log(` removed: ${localOpenclawBin}`);
11215
+ } catch (e) {
11216
+ log(` WARN: failed to remove ${localOpenclawBin}: ${e.message}`);
11217
+ }
11218
+ else log(` skipped: ${localOpenclawBin} (not found)`);
11219
+ log("");
11220
+ log("── [3/6] npx install (@larksuite/openclaw-lark-tools update) ──");
11221
+ const npxResult = (0, node_child_process.spawnSync)("npx", [
11222
+ "-y",
11223
+ "@larksuite/openclaw-lark-tools",
11224
+ "update"
11225
+ ], {
11226
+ cwd,
11227
+ encoding: "utf-8",
11228
+ stdio: [
11229
+ "ignore",
11230
+ "pipe",
11231
+ "pipe"
11232
+ ],
11233
+ timeout: 12e4
11234
+ });
11235
+ const npxStdout = npxResult.stdout?.trim() ?? "";
11236
+ const npxStderr = npxResult.stderr?.trim() ?? "";
11237
+ const npxExitCode = npxResult.status ?? 1;
11238
+ if (npxStdout) log(`npx stdout:\n${npxStdout}`);
11239
+ if (npxStderr) log(`npx stderr:\n${npxStderr}`);
11240
+ log(`npx exit: ${npxExitCode}${npxResult.error ? ` error: ${npxResult.error.message}` : ""}`);
11241
+ if (statusCheckDelayMs > 0) {
11242
+ log("");
11243
+ log(`── 等待 ${statusCheckDelayMs / 1e3}s(让 openclaw 服务完成重启) ─────────────`);
11244
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, statusCheckDelayMs);
11245
+ log("wait done");
11246
+ }
11247
+ const doRollback = (reason) => {
11248
+ log(`ERROR: ${reason}`);
11249
+ const rollbackOk = restoreFiles(fsOpts);
11250
+ log(`rollback: ${rollbackOk ? "ok" : "FAILED"}`);
11251
+ return {
11252
+ ok: false,
11253
+ error: reason,
11254
+ validationError: reason,
11255
+ stdout: npxStdout,
11256
+ stderr: npxStderr,
11257
+ exitCode: npxExitCode,
11258
+ rollbackOk,
11259
+ logFile
11260
+ };
11261
+ };
11262
+ log("");
11263
+ log("── [4/5] 安装后诊断校验 ─────────────────────────────────");
11264
+ logVersionSnapshot("after-versions", snapshotVersions(cwd, log), log);
11265
+ let afterVersionIncompatible = false;
11266
+ try {
11267
+ const rawConfig = node_fs.default.readFileSync(configPath, "utf-8");
11268
+ afterVersionIncompatible = needsLarkUpgrade({
11269
+ config: loadJSON5().parse(rawConfig),
11270
+ configPath,
11271
+ vars: {},
11272
+ providerDeps: {
11273
+ usesMiaodaProvider: false,
11274
+ usesMiaodaSecretProvider: false
11275
+ }
11276
+ });
11277
+ log(` version-compat post-check: ${afterVersionIncompatible ? "STILL_INCOMPATIBLE" : "ok"}`);
11278
+ } catch (e) {
11279
+ log(` version-compat post-check error: ${e.message} — treating as still-incompatible`);
11280
+ afterVersionIncompatible = true;
11281
+ }
11282
+ const afterChannels = probeChannels("after", log, 3e4);
11283
+ log(` feishu config invalid after: ${afterChannels.feishuConfigInvalid}`);
11284
+ const stillNeedsUpgrade = (afterVersionIncompatible || afterChannels.feishuConfigInvalid) && !afterChannels.anyAccountWorking;
11285
+ log(` post-check: stillNeedsUpgrade=${stillNeedsUpgrade} (version=${afterVersionIncompatible}, feishuConfig=${afterChannels.feishuConfigInvalid}, channelsWorking=${afterChannels.anyAccountWorking})`);
11286
+ if (stillNeedsUpgrade) return doRollback(`post-install diagnosis still shows anomaly: versionIncompatible=${afterVersionIncompatible}, feishuConfigInvalid=${afterChannels.feishuConfigInvalid}, anyAccountWorking=${afterChannels.anyAccountWorking}`);
11287
+ log(" post-install diagnosis: ok (upgrade conditions resolved)");
11288
+ log("");
11289
+ log("── [6/6] doctor --fix ────────────────────────────────────");
11290
+ const fixArgs = ["doctor", "--fix"];
11291
+ if (opts.scene) fixArgs.push(`--scene=${opts.scene}`);
11292
+ const fixResult = (0, node_child_process.spawnSync)(process.execPath, [cliScript, ...fixArgs], {
11293
+ cwd,
11294
+ encoding: "utf-8",
11295
+ stdio: [
11296
+ "ignore",
11297
+ "pipe",
11298
+ "pipe"
11299
+ ],
11300
+ timeout: 6e4,
11301
+ env: process.env
11302
+ });
11303
+ if (fixResult.stdout?.trim()) log(`doctor(fix) stdout:\n${fixResult.stdout.trim()}`);
11304
+ if (fixResult.stderr?.trim()) log(`doctor(fix) stderr:\n${fixResult.stderr.trim()}`);
11305
+ log(`doctor(fix) exit: ${fixResult.status ?? "null"}${fixResult.error ? ` error: ${fixResult.error.message}` : ""}`);
11306
+ log("");
11307
+ log(`${"=".repeat(60)}`);
11308
+ log("upgrade-lark completed successfully");
11309
+ log(`${"=".repeat(60)}`);
11310
+ return {
11311
+ ok: true,
11312
+ stdout: npxStdout,
11313
+ stderr: npxStderr,
11314
+ exitCode: npxExitCode,
11315
+ logFile
11316
+ };
11317
+ }
10868
11318
  //#endregion
10869
11319
  //#region src/index.ts
10870
11320
  const args = node_process.default.argv.slice(2);
10871
11321
  const mode = args.find((a) => !a.startsWith("-"));
10872
11322
  /**
11323
+ * Decode `--ctx=<base64>` into an opaque JSON object. Returns undefined when
11324
+ * the flag isn't present — the caller decides whether to fall back to the
11325
+ * innerapi or to error out.
11326
+ *
11327
+ * The object's shape is not enforced here; downstream code consumes it via
11328
+ * either `normalizeCtx()` (new path) or direct field access for the legacy
11329
+ * check/repair/reset contract still used by sandbox_console push.
11330
+ */
11331
+ function parseCtxFlag(args) {
11332
+ const ctxArg = args.find((a) => a.startsWith("--ctx="));
11333
+ if (!ctxArg) return void 0;
11334
+ const b64 = ctxArg.slice(6);
11335
+ return JSON.parse(Buffer.from(b64, "base64").toString("utf-8"));
11336
+ }
11337
+ /**
10873
11338
  * Pull the first non-flag positional after the mode name.
10874
11339
  * (The mode itself is args[0] in the filtered set, so we skip index 0.)
10875
11340
  */
@@ -10897,8 +11362,8 @@ function getMultiFlag(args, name) {
10897
11362
  * case but is no longer consulted.
10898
11363
  */
10899
11364
  async function reportRun(command, rc, _raw, invocation, durationMs, outcome, slardar = {
10900
- scene: void 0,
10901
- profile: "standard",
11365
+ scene,
11366
+ profile,
10902
11367
  fix: false
10903
11368
  }) {
10904
11369
  console.error(`${command}: telemetry calling report_cli_run`);
@@ -10962,7 +11427,7 @@ async function main() {
10962
11427
  console.error(`${mode}: begin argv=[${args.join(" ")}] version=${getVersion()} traceId=${traceId ?? "-"} caller=${caller ?? "-"} runIdGenerated=${rc.generated}`);
10963
11428
  switch (mode) {
10964
11429
  case "check": {
10965
- const raw = await fetchCtxViaInnerApi({
11430
+ const raw = parseCtxFlag(args) ?? await fetchCtxViaInnerApi({
10966
11431
  populate: planCtxPopulate({
10967
11432
  command: "check",
10968
11433
  profile
@@ -10987,7 +11452,7 @@ async function main() {
10987
11452
  break;
10988
11453
  }
10989
11454
  case "repair": {
10990
- const raw = await fetchCtxViaInnerApi({
11455
+ const raw = parseCtxFlag(args) ?? await fetchCtxViaInnerApi({
10991
11456
  populate: planCtxPopulate({
10992
11457
  command: "repair",
10993
11458
  profile
@@ -11058,15 +11523,27 @@ async function main() {
11058
11523
  break;
11059
11524
  }
11060
11525
  case "reset":
11061
- if (args.includes("--async")) console.log(JSON.stringify(startAsyncReset()));
11062
- else if (args.includes("--worker")) {
11526
+ if (args.includes("--async")) {
11527
+ const ctxArg = args.find((a) => a.startsWith("--ctx="));
11528
+ let ctxBase64;
11529
+ if (ctxArg) ctxBase64 = ctxArg.slice(6);
11530
+ else {
11531
+ const fetched = await fetchCtxViaInnerApi({
11532
+ populate: planCtxPopulate({ command: "reset" }),
11533
+ caller,
11534
+ traceId
11535
+ });
11536
+ ctxBase64 = Buffer.from(JSON.stringify(fetched), "utf-8").toString("base64");
11537
+ }
11538
+ console.log(JSON.stringify(startAsyncReset(ctxBase64)));
11539
+ } else if (args.includes("--worker")) {
11063
11540
  const taskId = args.find((a) => a.startsWith("--task-id="))?.slice(10);
11064
11541
  if (!taskId) {
11065
11542
  console.error("Error: --task-id=<id> is required for worker");
11066
11543
  node_process.default.exit(1);
11067
11544
  }
11068
11545
  const resultFile = resetResultFile(taskId);
11069
- const raw = await fetchCtxViaInnerApi({
11546
+ const raw = parseCtxFlag(args) ?? await fetchCtxViaInnerApi({
11070
11547
  populate: planCtxPopulate({ command: "reset" }),
11071
11548
  caller,
11072
11549
  traceId
@@ -11090,7 +11567,7 @@ async function main() {
11090
11567
  return;
11091
11568
  }
11092
11569
  } else {
11093
- console.error("Usage: reset --async | reset --worker --task-id=<id>");
11570
+ console.error("Usage: reset --async [--ctx=<base64>] | reset --worker --task-id=<id> [--ctx=<base64>]");
11094
11571
  node_process.default.exit(1);
11095
11572
  }
11096
11573
  break;
@@ -11106,14 +11583,14 @@ async function main() {
11106
11583
  case "install-openclaw": {
11107
11584
  const tag = getPositionalTag(args, "install-openclaw");
11108
11585
  if (!tag) {
11109
- console.error("Usage: install-openclaw <tag> [--oss_file_map=<base64>]");
11586
+ console.error("Usage: install-openclaw <tag> [--ctx=<base64> | --oss_file_map=<base64>]");
11110
11587
  node_process.default.exit(1);
11111
11588
  }
11112
11589
  const ossFileMapFlag = getFlag(args, "oss_file_map");
11113
11590
  let installOssFileMap;
11114
11591
  let rawForTelemetry;
11115
11592
  if (!ossFileMapFlag) {
11116
- rawForTelemetry = await fetchCtxViaInnerApi({
11593
+ rawForTelemetry = parseCtxFlag(args) ?? await fetchCtxViaInnerApi({
11117
11594
  populate: planCtxPopulate({ command: "install" }),
11118
11595
  caller,
11119
11596
  traceId
@@ -11148,7 +11625,7 @@ async function main() {
11148
11625
  case "install-extension": {
11149
11626
  const tag = getPositionalTag(args, "install-extension");
11150
11627
  if (!tag) {
11151
- console.error("Usage: install-extension <tag> (--all | --extension=<name>...) [--home_base=<dir>] [--config_path=<path>] [--skip-config-update] [--oss_file_map=<base64>]");
11628
+ console.error("Usage: install-extension <tag> (--all | --extension=<name>...) [--home_base=<dir>] [--config_path=<path>] [--skip-config-update] [--ctx=<base64> | --oss_file_map=<base64>]");
11152
11629
  node_process.default.exit(1);
11153
11630
  }
11154
11631
  const all = args.includes("--all");
@@ -11160,7 +11637,7 @@ async function main() {
11160
11637
  let installOssFileMap;
11161
11638
  let rawForTelemetry;
11162
11639
  if (!ossFileMapFlag) {
11163
- rawForTelemetry = await fetchCtxViaInnerApi({
11640
+ rawForTelemetry = parseCtxFlag(args) ?? await fetchCtxViaInnerApi({
11164
11641
  populate: planCtxPopulate({ command: "install" }),
11165
11642
  caller,
11166
11643
  traceId
@@ -11206,12 +11683,12 @@ async function main() {
11206
11683
  case "install-cli": {
11207
11684
  const tag = getPositionalTag(args, "install-cli");
11208
11685
  if (!tag) {
11209
- console.error("Usage: install-cli <tag> --cli=<name>... [--home_base=<dir>] [--oss_file_map=<base64>]");
11686
+ console.error("Usage: install-cli <tag> --cli=<name>... [--home_base=<dir>] [--ctx=<base64> | --oss_file_map=<base64>]");
11210
11687
  node_process.default.exit(1);
11211
11688
  }
11212
11689
  const names = getMultiFlag(args, "cli");
11213
11690
  if (names.length === 0) {
11214
- console.error("Usage: install-cli <tag> --cli=<name>... [--home_base=<dir>] [--oss_file_map=<base64>]");
11691
+ console.error("Usage: install-cli <tag> --cli=<name>... [--home_base=<dir>] [--ctx=<base64> | --oss_file_map=<base64>]");
11215
11692
  node_process.default.exit(1);
11216
11693
  }
11217
11694
  const homeBase = getFlag(args, "home_base");
@@ -11219,7 +11696,7 @@ async function main() {
11219
11696
  let installOssFileMap;
11220
11697
  let rawForTelemetry;
11221
11698
  if (!ossFileMapFlag) {
11222
- rawForTelemetry = await fetchCtxViaInnerApi({
11699
+ rawForTelemetry = parseCtxFlag(args) ?? await fetchCtxViaInnerApi({
11223
11700
  populate: planCtxPopulate({ command: "install" }),
11224
11701
  caller,
11225
11702
  traceId
@@ -11267,7 +11744,7 @@ async function main() {
11267
11744
  case "download-resource": {
11268
11745
  const tag = getPositionalTag(args, "download-resource");
11269
11746
  if (!tag) {
11270
- console.error("Usage: download-resource <tag> --role=<role> --name=<name> [--dir=<dir>] [--oss_file_map=<base64>]");
11747
+ console.error("Usage: download-resource <tag> --role=<role> --name=<name> [--dir=<dir>] [--ctx=<base64> | --oss_file_map=<base64>]");
11271
11748
  node_process.default.exit(1);
11272
11749
  }
11273
11750
  const role = getFlag(args, "role");
@@ -11281,7 +11758,7 @@ async function main() {
11281
11758
  let installOssFileMap;
11282
11759
  let rawForTelemetry;
11283
11760
  if (!ossFileMapFlag) {
11284
- rawForTelemetry = await fetchCtxViaInnerApi({
11761
+ rawForTelemetry = parseCtxFlag(args) ?? await fetchCtxViaInnerApi({
11285
11762
  populate: planCtxPopulate({ command: "install" }),
11286
11763
  caller,
11287
11764
  traceId
@@ -11355,6 +11832,50 @@ async function main() {
11355
11832
  if (!result.ok) node_process.default.exit(1);
11356
11833
  break;
11357
11834
  }
11835
+ case "upgrade-lark": {
11836
+ const result = runUpgradeLark({
11837
+ runId: rc.runId,
11838
+ scene
11839
+ });
11840
+ const upgradeDurationMs = Date.now() - t0;
11841
+ console.log(JSON.stringify(result));
11842
+ reportUpgradeLarkToSlardar({
11843
+ scene,
11844
+ durationMs: upgradeDurationMs,
11845
+ success: result.ok,
11846
+ logFile: result.logFile,
11847
+ exitCode: result.exitCode,
11848
+ rollbackOk: result.rollbackOk,
11849
+ validationError: result.validationError,
11850
+ error: result.error
11851
+ });
11852
+ try {
11853
+ await reportCliRun({
11854
+ command: "upgrade-lark",
11855
+ runId: rc.runId,
11856
+ version: getVersion(),
11857
+ invocation: args.join(" "),
11858
+ durationMs: upgradeDurationMs,
11859
+ caller: rc.caller,
11860
+ traceId: rc.traceId,
11861
+ success: result.ok,
11862
+ result,
11863
+ error: result.ok ? void 0 : { message: result.error ?? "upgrade-lark failed" }
11864
+ });
11865
+ } catch (e) {
11866
+ console.error(`[telemetry] reportCliRun failed: ${e.message}`);
11867
+ }
11868
+ if (!result.ok) {
11869
+ node_process.default.exitCode = 1;
11870
+ return;
11871
+ }
11872
+ break;
11873
+ }
11874
+ case "channels-probe": {
11875
+ const result = runChannelsProbe(getFlag(args, "timeout") ? Number(getFlag(args, "timeout")) : void 0);
11876
+ console.log(JSON.stringify(result));
11877
+ break;
11878
+ }
11358
11879
  default:
11359
11880
  node_process.default.stderr.write(`Unknown command: ${mode}\n\n`);
11360
11881
  node_process.default.stderr.write(formatTopLevelHelp(helpFlags.expert));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/openclaw-scripts-diagnose-cli",
3
- "version": "0.1.14-alpha.7",
3
+ "version": "0.1.14-alpha.8",
4
4
  "description": "CLI for OpenClaw config diagnose and repair with JSON5 support",
5
5
  "main": "dist/index.cjs",
6
6
  "bin": {