File size: 22,989 Bytes
fb4d8fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
import path from "node:path";
import type { RuntimeEnv } from "../../runtime.js";
import { resolveOpenClawAgentDir } from "../../agents/agent-paths.js";
import {
  resolveAgentDir,
  resolveAgentModelFallbacksOverride,
  resolveAgentModelPrimary,
} from "../../agents/agent-scope.js";
import {
  buildAuthHealthSummary,
  DEFAULT_OAUTH_WARN_MS,
  formatRemainingShort,
} from "../../agents/auth-health.js";
import {
  ensureAuthProfileStore,
  resolveAuthStorePathForDisplay,
  resolveProfileUnusableUntilForDisplay,
} from "../../agents/auth-profiles.js";
import { resolveEnvApiKey } from "../../agents/model-auth.js";
import {
  buildModelAliasIndex,
  parseModelRef,
  resolveConfiguredModelRef,
  resolveDefaultModelForAgent,
  resolveModelRefFromString,
} from "../../agents/model-selection.js";
import { formatCliCommand } from "../../cli/command-format.js";
import { withProgressTotals } from "../../cli/progress.js";
import { CONFIG_PATH, loadConfig } from "../../config/config.js";
import {
  formatUsageWindowSummary,
  loadProviderUsageSummary,
  resolveUsageProviderId,
  type UsageProviderId,
} from "../../infra/provider-usage.js";
import { getShellEnvAppliedKeys, shouldEnableShellEnvFallback } from "../../infra/shell-env.js";
import { renderTable } from "../../terminal/table.js";
import { colorize, theme } from "../../terminal/theme.js";
import { shortenHomePath } from "../../utils.js";
import { resolveProviderAuthOverview } from "./list.auth-overview.js";
import { isRich } from "./list.format.js";
import {
  describeProbeSummary,
  formatProbeLatency,
  runAuthProbes,
  sortProbeResults,
  type AuthProbeSummary,
} from "./list.probe.js";
import {
  DEFAULT_MODEL,
  DEFAULT_PROVIDER,
  ensureFlagCompatibility,
  resolveKnownAgentId,
} from "./shared.js";

export async function modelsStatusCommand(
  opts: {
    json?: boolean;
    plain?: boolean;
    check?: boolean;
    probe?: boolean;
    probeProvider?: string;
    probeProfile?: string | string[];
    probeTimeout?: string;
    probeConcurrency?: string;
    probeMaxTokens?: string;
    agent?: string;
  },
  runtime: RuntimeEnv,
) {
  ensureFlagCompatibility(opts);
  if (opts.plain && opts.probe) {
    throw new Error("--probe cannot be used with --plain output.");
  }
  const cfg = loadConfig();
  const agentId = resolveKnownAgentId({ cfg, rawAgentId: opts.agent });
  const agentDir = agentId ? resolveAgentDir(cfg, agentId) : resolveOpenClawAgentDir();
  const agentModelPrimary = agentId ? resolveAgentModelPrimary(cfg, agentId) : undefined;
  const agentFallbacksOverride = agentId
    ? resolveAgentModelFallbacksOverride(cfg, agentId)
    : undefined;
  const resolved = agentId
    ? resolveDefaultModelForAgent({ cfg, agentId })
    : resolveConfiguredModelRef({
        cfg,
        defaultProvider: DEFAULT_PROVIDER,
        defaultModel: DEFAULT_MODEL,
      });

  const modelConfig = cfg.agents?.defaults?.model as
    | { primary?: string; fallbacks?: string[] }
    | string
    | undefined;
  const imageConfig = cfg.agents?.defaults?.imageModel as
    | { primary?: string; fallbacks?: string[] }
    | string
    | undefined;
  const rawDefaultsModel =
    typeof modelConfig === "string" ? modelConfig.trim() : (modelConfig?.primary?.trim() ?? "");
  const rawModel = agentModelPrimary ?? rawDefaultsModel;
  const resolvedLabel = `${resolved.provider}/${resolved.model}`;
  const defaultLabel = rawModel || resolvedLabel;
  const defaultsFallbacks = typeof modelConfig === "object" ? (modelConfig?.fallbacks ?? []) : [];
  const fallbacks = agentFallbacksOverride ?? defaultsFallbacks;
  const imageModel =
    typeof imageConfig === "string" ? imageConfig.trim() : (imageConfig?.primary?.trim() ?? "");
  const imageFallbacks = typeof imageConfig === "object" ? (imageConfig?.fallbacks ?? []) : [];
  const aliases = Object.entries(cfg.agents?.defaults?.models ?? {}).reduce<Record<string, string>>(
    (acc, [key, entry]) => {
      const alias = entry?.alias?.trim();
      if (alias) {
        acc[alias] = key;
      }
      return acc;
    },
    {},
  );
  const allowed = Object.keys(cfg.agents?.defaults?.models ?? {});

  const store = ensureAuthProfileStore(agentDir);
  const modelsPath = path.join(agentDir, "models.json");

  const providersFromStore = new Set(
    Object.values(store.profiles)
      .map((profile) => profile.provider)
      .filter((p): p is string => Boolean(p)),
  );
  const providersFromConfig = new Set(
    Object.keys(cfg.models?.providers ?? {})
      .map((p) => p.trim())
      .filter(Boolean),
  );
  const providersFromModels = new Set<string>();
  const providersInUse = new Set<string>();
  for (const raw of [defaultLabel, ...fallbacks, imageModel, ...imageFallbacks, ...allowed]) {
    const parsed = parseModelRef(String(raw ?? ""), DEFAULT_PROVIDER);
    if (parsed?.provider) {
      providersFromModels.add(parsed.provider);
    }
  }
  for (const raw of [defaultLabel, ...fallbacks, imageModel, ...imageFallbacks]) {
    const parsed = parseModelRef(String(raw ?? ""), DEFAULT_PROVIDER);
    if (parsed?.provider) {
      providersInUse.add(parsed.provider);
    }
  }

  const providersFromEnv = new Set<string>();
  // Keep in sync with resolveEnvApiKey() mappings (we want visibility even when
  // a provider isn't currently selected in config/models).
  const envProbeProviders = [
    "anthropic",
    "github-copilot",
    "google-vertex",
    "openai",
    "google",
    "groq",
    "cerebras",
    "xai",
    "openrouter",
    "zai",
    "mistral",
    "synthetic",
  ];
  for (const provider of envProbeProviders) {
    if (resolveEnvApiKey(provider)) {
      providersFromEnv.add(provider);
    }
  }

  const providers = Array.from(
    new Set([
      ...providersFromStore,
      ...providersFromConfig,
      ...providersFromModels,
      ...providersFromEnv,
    ]),
  )
    .map((p) => p.trim())
    .filter(Boolean)
    .toSorted((a, b) => a.localeCompare(b));

  const applied = getShellEnvAppliedKeys();
  const shellFallbackEnabled =
    shouldEnableShellEnvFallback(process.env) || cfg.env?.shellEnv?.enabled === true;

  const providerAuth = providers
    .map((provider) => resolveProviderAuthOverview({ provider, cfg, store, modelsPath }))
    .filter((entry) => {
      const hasAny = entry.profiles.count > 0 || Boolean(entry.env) || Boolean(entry.modelsJson);
      return hasAny;
    });
  const providerAuthMap = new Map(providerAuth.map((entry) => [entry.provider, entry]));
  const missingProvidersInUse = Array.from(providersInUse)
    .filter((provider) => !providerAuthMap.has(provider))
    .toSorted((a, b) => a.localeCompare(b));

  const probeProfileIds = (() => {
    if (!opts.probeProfile) {
      return [];
    }
    const raw = Array.isArray(opts.probeProfile) ? opts.probeProfile : [opts.probeProfile];
    return raw
      .flatMap((value) => String(value ?? "").split(","))
      .map((value) => value.trim())
      .filter(Boolean);
  })();
  const probeTimeoutMs = opts.probeTimeout ? Number(opts.probeTimeout) : 8000;
  if (!Number.isFinite(probeTimeoutMs) || probeTimeoutMs <= 0) {
    throw new Error("--probe-timeout must be a positive number (ms).");
  }
  const probeConcurrency = opts.probeConcurrency ? Number(opts.probeConcurrency) : 2;
  if (!Number.isFinite(probeConcurrency) || probeConcurrency <= 0) {
    throw new Error("--probe-concurrency must be > 0.");
  }
  const probeMaxTokens = opts.probeMaxTokens ? Number(opts.probeMaxTokens) : 8;
  if (!Number.isFinite(probeMaxTokens) || probeMaxTokens <= 0) {
    throw new Error("--probe-max-tokens must be > 0.");
  }

  const aliasIndex = buildModelAliasIndex({ cfg, defaultProvider: DEFAULT_PROVIDER });
  const rawCandidates = [
    rawModel || resolvedLabel,
    ...fallbacks,
    imageModel,
    ...imageFallbacks,
    ...allowed,
  ].filter(Boolean);
  const resolvedCandidates = rawCandidates
    .map(
      (raw) =>
        resolveModelRefFromString({
          raw: String(raw ?? ""),
          defaultProvider: DEFAULT_PROVIDER,
          aliasIndex,
        })?.ref,
    )
    .filter((ref): ref is { provider: string; model: string } => Boolean(ref));
  const modelCandidates = resolvedCandidates.map((ref) => `${ref.provider}/${ref.model}`);

  let probeSummary: AuthProbeSummary | undefined;
  if (opts.probe) {
    probeSummary = await withProgressTotals(
      { label: "Probing auth profiles…", total: 1 },
      async (update) => {
        return await runAuthProbes({
          cfg,
          providers,
          modelCandidates,
          options: {
            provider: opts.probeProvider,
            profileIds: probeProfileIds,
            timeoutMs: probeTimeoutMs,
            concurrency: probeConcurrency,
            maxTokens: probeMaxTokens,
          },
          onProgress: update,
        });
      },
    );
  }

  const providersWithOauth = providerAuth
    .filter(
      (entry) =>
        entry.profiles.oauth > 0 || entry.profiles.token > 0 || entry.env?.value === "OAuth (env)",
    )
    .map((entry) => {
      const count =
        entry.profiles.oauth + entry.profiles.token + (entry.env?.value === "OAuth (env)" ? 1 : 0);
      return `${entry.provider} (${count})`;
    });

  const authHealth = buildAuthHealthSummary({
    store,
    cfg,
    warnAfterMs: DEFAULT_OAUTH_WARN_MS,
    providers,
  });
  const oauthProfiles = authHealth.profiles.filter(
    (profile) => profile.type === "oauth" || profile.type === "token",
  );

  const unusableProfiles = (() => {
    const now = Date.now();
    const out: Array<{
      profileId: string;
      provider?: string;
      kind: "cooldown" | "disabled";
      reason?: string;
      until: number;
      remainingMs: number;
    }> = [];
    for (const profileId of Object.keys(store.usageStats ?? {})) {
      const unusableUntil = resolveProfileUnusableUntilForDisplay(store, profileId);
      if (!unusableUntil || now >= unusableUntil) {
        continue;
      }
      const stats = store.usageStats?.[profileId];
      const kind =
        typeof stats?.disabledUntil === "number" && now < stats.disabledUntil
          ? "disabled"
          : "cooldown";
      out.push({
        profileId,
        provider: store.profiles[profileId]?.provider,
        kind,
        reason: stats?.disabledReason,
        until: unusableUntil,
        remainingMs: unusableUntil - now,
      });
    }
    return out.toSorted((a, b) => a.remainingMs - b.remainingMs);
  })();

  const checkStatus = (() => {
    const hasExpiredOrMissing =
      oauthProfiles.some((profile) => ["expired", "missing"].includes(profile.status)) ||
      missingProvidersInUse.length > 0;
    const hasExpiring = oauthProfiles.some((profile) => profile.status === "expiring");
    if (hasExpiredOrMissing) {
      return 1;
    }
    if (hasExpiring) {
      return 2;
    }
    return 0;
  })();

  if (opts.json) {
    runtime.log(
      JSON.stringify(
        {
          configPath: CONFIG_PATH,
          ...(agentId ? { agentId } : {}),
          agentDir,
          defaultModel: defaultLabel,
          resolvedDefault: resolvedLabel,
          fallbacks,
          imageModel: imageModel || null,
          imageFallbacks,
          ...(agentId
            ? {
                modelConfig: {
                  defaultSource: agentModelPrimary ? "agent" : "defaults",
                  fallbacksSource: agentFallbacksOverride !== undefined ? "agent" : "defaults",
                },
              }
            : {}),
          aliases,
          allowed,
          auth: {
            storePath: resolveAuthStorePathForDisplay(agentDir),
            shellEnvFallback: {
              enabled: shellFallbackEnabled,
              appliedKeys: applied,
            },
            providersWithOAuth: providersWithOauth,
            missingProvidersInUse,
            providers: providerAuth,
            unusableProfiles,
            oauth: {
              warnAfterMs: authHealth.warnAfterMs,
              profiles: authHealth.profiles,
              providers: authHealth.providers,
            },
            probes: probeSummary,
          },
        },
        null,
        2,
      ),
    );
    if (opts.check) {
      runtime.exit(checkStatus);
    }
    return;
  }

  if (opts.plain) {
    runtime.log(resolvedLabel);
    if (opts.check) {
      runtime.exit(checkStatus);
    }
    return;
  }

  const rich = isRich(opts);
  type ModelConfigSource = "agent" | "defaults";
  const label = (value: string) => colorize(rich, theme.accent, value.padEnd(14));
  const labelWithSource = (value: string, source?: ModelConfigSource) =>
    label(source ? `${value} (${source})` : value);
  const displayDefault =
    rawModel && rawModel !== resolvedLabel ? `${resolvedLabel} (from ${rawModel})` : resolvedLabel;

  runtime.log(
    `${label("Config")}${colorize(rich, theme.muted, ":")} ${colorize(rich, theme.info, shortenHomePath(CONFIG_PATH))}`,
  );
  runtime.log(
    `${label("Agent dir")}${colorize(rich, theme.muted, ":")} ${colorize(
      rich,
      theme.info,
      shortenHomePath(agentDir),
    )}`,
  );
  runtime.log(
    `${labelWithSource("Default", agentId ? (agentModelPrimary ? "agent" : "defaults") : undefined)}${colorize(
      rich,
      theme.muted,
      ":",
    )} ${colorize(rich, theme.success, displayDefault)}`,
  );
  runtime.log(
    `${labelWithSource(
      `Fallbacks (${fallbacks.length || 0})`,
      agentId ? (agentFallbacksOverride !== undefined ? "agent" : "defaults") : undefined,
    )}${colorize(rich, theme.muted, ":")} ${colorize(
      rich,
      fallbacks.length ? theme.warn : theme.muted,
      fallbacks.length ? fallbacks.join(", ") : "-",
    )}`,
  );
  runtime.log(
    `${labelWithSource("Image model", agentId ? "defaults" : undefined)}${colorize(
      rich,
      theme.muted,
      ":",
    )} ${colorize(rich, imageModel ? theme.accentBright : theme.muted, imageModel || "-")}`,
  );
  runtime.log(
    `${labelWithSource(
      `Image fallbacks (${imageFallbacks.length || 0})`,
      agentId ? "defaults" : undefined,
    )}${colorize(rich, theme.muted, ":")} ${colorize(
      rich,
      imageFallbacks.length ? theme.accentBright : theme.muted,
      imageFallbacks.length ? imageFallbacks.join(", ") : "-",
    )}`,
  );
  runtime.log(
    `${label(`Aliases (${Object.keys(aliases).length || 0})`)}${colorize(rich, theme.muted, ":")} ${colorize(
      rich,
      Object.keys(aliases).length ? theme.accent : theme.muted,
      Object.keys(aliases).length
        ? Object.entries(aliases)
            .map(([alias, target]) =>
              rich
                ? `${theme.accentDim(alias)} ${theme.muted("->")} ${theme.info(target)}`
                : `${alias} -> ${target}`,
            )
            .join(", ")
        : "-",
    )}`,
  );
  runtime.log(
    `${label(`Configured models (${allowed.length || 0})`)}${colorize(rich, theme.muted, ":")} ${colorize(
      rich,
      allowed.length ? theme.info : theme.muted,
      allowed.length ? allowed.join(", ") : "all",
    )}`,
  );

  runtime.log("");
  runtime.log(colorize(rich, theme.heading, "Auth overview"));
  runtime.log(
    `${label("Auth store")}${colorize(rich, theme.muted, ":")} ${colorize(
      rich,
      theme.info,
      shortenHomePath(resolveAuthStorePathForDisplay(agentDir)),
    )}`,
  );
  runtime.log(
    `${label("Shell env")}${colorize(rich, theme.muted, ":")} ${colorize(
      rich,
      shellFallbackEnabled ? theme.success : theme.muted,
      shellFallbackEnabled ? "on" : "off",
    )}${applied.length ? colorize(rich, theme.muted, ` (applied: ${applied.join(", ")})`) : ""}`,
  );
  runtime.log(
    `${label(`Providers w/ OAuth/tokens (${providersWithOauth.length || 0})`)}${colorize(
      rich,
      theme.muted,
      ":",
    )} ${colorize(
      rich,
      providersWithOauth.length ? theme.info : theme.muted,
      providersWithOauth.length ? providersWithOauth.join(", ") : "-",
    )}`,
  );

  const formatKey = (key: string) => colorize(rich, theme.warn, key);
  const formatKeyValue = (key: string, value: string) =>
    `${formatKey(key)}=${colorize(rich, theme.info, value)}`;
  const formatSeparator = () => colorize(rich, theme.muted, " | ");

  for (const entry of providerAuth) {
    const separator = formatSeparator();
    const bits: string[] = [];
    bits.push(
      formatKeyValue(
        "effective",
        `${colorize(rich, theme.accentBright, entry.effective.kind)}:${colorize(
          rich,
          theme.muted,
          entry.effective.detail,
        )}`,
      ),
    );
    if (entry.profiles.count > 0) {
      bits.push(
        formatKeyValue(
          "profiles",
          `${entry.profiles.count} (oauth=${entry.profiles.oauth}, token=${entry.profiles.token}, api_key=${entry.profiles.apiKey})`,
        ),
      );
      if (entry.profiles.labels.length > 0) {
        bits.push(colorize(rich, theme.info, entry.profiles.labels.join(", ")));
      }
    }
    if (entry.env) {
      bits.push(
        formatKeyValue(
          "env",
          `${entry.env.value}${separator}${formatKeyValue("source", entry.env.source)}`,
        ),
      );
    }
    if (entry.modelsJson) {
      bits.push(
        formatKeyValue(
          "models.json",
          `${entry.modelsJson.value}${separator}${formatKeyValue("source", entry.modelsJson.source)}`,
        ),
      );
    }
    runtime.log(`- ${theme.heading(entry.provider)} ${bits.join(separator)}`);
  }

  if (missingProvidersInUse.length > 0) {
    runtime.log("");
    runtime.log(colorize(rich, theme.heading, "Missing auth"));
    for (const provider of missingProvidersInUse) {
      const hint =
        provider === "anthropic"
          ? `Run \`claude setup-token\`, then \`${formatCliCommand("openclaw models auth setup-token")}\` or \`${formatCliCommand("openclaw configure")}\`.`
          : `Run \`${formatCliCommand("openclaw configure")}\` or set an API key env var.`;
      runtime.log(`- ${theme.heading(provider)} ${hint}`);
    }
  }

  runtime.log("");
  runtime.log(colorize(rich, theme.heading, "OAuth/token status"));
  if (oauthProfiles.length === 0) {
    runtime.log(colorize(rich, theme.muted, "- none"));
  } else {
    const usageByProvider = new Map<string, string>();
    const usageProviders = Array.from(
      new Set(
        oauthProfiles
          .map((profile) => resolveUsageProviderId(profile.provider))
          .filter((provider): provider is UsageProviderId => Boolean(provider)),
      ),
    );
    if (usageProviders.length > 0) {
      try {
        const usageSummary = await loadProviderUsageSummary({
          providers: usageProviders,
          agentDir,
          timeoutMs: 3500,
        });
        for (const snapshot of usageSummary.providers) {
          const formatted = formatUsageWindowSummary(snapshot, {
            now: Date.now(),
            maxWindows: 2,
            includeResets: true,
          });
          if (formatted) {
            usageByProvider.set(snapshot.provider, formatted);
          }
        }
      } catch {
        // ignore usage failures
      }
    }

    const formatStatus = (status: string) => {
      if (status === "ok") {
        return colorize(rich, theme.success, "ok");
      }
      if (status === "static") {
        return colorize(rich, theme.muted, "static");
      }
      if (status === "expiring") {
        return colorize(rich, theme.warn, "expiring");
      }
      if (status === "missing") {
        return colorize(rich, theme.warn, "unknown");
      }
      return colorize(rich, theme.error, "expired");
    };

    const profilesByProvider = new Map<string, typeof oauthProfiles>();
    for (const profile of oauthProfiles) {
      const current = profilesByProvider.get(profile.provider);
      if (current) {
        current.push(profile);
      } else {
        profilesByProvider.set(profile.provider, [profile]);
      }
    }

    for (const [provider, profiles] of profilesByProvider) {
      const usageKey = resolveUsageProviderId(provider);
      const usage = usageKey ? usageByProvider.get(usageKey) : undefined;
      const usageSuffix = usage ? colorize(rich, theme.muted, ` usage: ${usage}`) : "";
      runtime.log(`- ${colorize(rich, theme.heading, provider)}${usageSuffix}`);
      for (const profile of profiles) {
        const labelText = profile.label || profile.profileId;
        const label = colorize(rich, theme.accent, labelText);
        const status = formatStatus(profile.status);
        const expiry =
          profile.status === "static"
            ? ""
            : profile.expiresAt
              ? ` expires in ${formatRemainingShort(profile.remainingMs)}`
              : " expires unknown";
        runtime.log(`  - ${label} ${status}${expiry}`);
      }
    }
  }

  if (probeSummary) {
    runtime.log("");
    runtime.log(colorize(rich, theme.heading, "Auth probes"));
    if (probeSummary.results.length === 0) {
      runtime.log(colorize(rich, theme.muted, "- none"));
    } else {
      const tableWidth = Math.max(60, (process.stdout.columns ?? 120) - 1);
      const sorted = sortProbeResults(probeSummary.results);
      const statusColor = (status: string) => {
        if (status === "ok") {
          return theme.success;
        }
        if (status === "rate_limit") {
          return theme.warn;
        }
        if (status === "timeout" || status === "billing") {
          return theme.warn;
        }
        if (status === "auth" || status === "format") {
          return theme.error;
        }
        if (status === "no_model") {
          return theme.muted;
        }
        return theme.muted;
      };
      const rows = sorted.map((result) => {
        const status = colorize(rich, statusColor(result.status), result.status);
        const latency = formatProbeLatency(result.latencyMs);
        const modelLabel = result.model ?? `${result.provider}/-`;
        const modeLabel = result.mode ? ` ${colorize(rich, theme.muted, `(${result.mode})`)}` : "";
        const profile = `${colorize(rich, theme.accent, result.label)}${modeLabel}`;
        const detail = result.error?.trim();
        const detailLabel = detail ? `\n${colorize(rich, theme.muted, `↳ ${detail}`)}` : "";
        const statusLabel = `${status}${colorize(rich, theme.muted, ` · ${latency}`)}${detailLabel}`;
        return {
          Model: colorize(rich, theme.heading, modelLabel),
          Profile: profile,
          Status: statusLabel,
        };
      });
      runtime.log(
        renderTable({
          width: tableWidth,
          columns: [
            { key: "Model", header: "Model", minWidth: 18 },
            { key: "Profile", header: "Profile", minWidth: 24 },
            { key: "Status", header: "Status", minWidth: 12 },
          ],
          rows,
        }).trimEnd(),
      );
      runtime.log(colorize(rich, theme.muted, describeProbeSummary(probeSummary)));
    }
  }

  if (opts.check) {
    runtime.exit(checkStatus);
  }
}