π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(cli): add `lh doctor` to diagnose the whole chain in one command (#19626)
Arvin Xu8b7a674d22fa
diff --git a/apps/cli/man/man1/lh.1 b/apps/cli/man/man1/lh.1index d99fea2bff9..2be22d58da6 100644--- a/apps/cli/man/man1/lh.1+++ b/apps/cli/man/man1/lh.1@@ -53,6 +53,9 @@ Manage connected devices.B statusCheck if gateway connection can be established.TP+.B doctor+Diagnose this machine: runtime, endpoints, credentials, scope, device and agent readiness+.TP.B docManage documents.TPdiff --git a/apps/cli/src/api/client.ts b/apps/cli/src/api/client.tsindex 768266dea29..f7214e8b96a 100644--- a/apps/cli/src/api/client.ts+++ b/apps/cli/src/api/client.ts@@ -5,7 +5,8 @@ import type { LambdaRouter } from '@/server/routers/lambda';import type { ToolsRouter } from '@/server/routers/tools';import { getValidToken } from '../auth/refresh';-import { CLI_API_KEY_ENV, readCliApiKeyEnv } from '../constants/auth';+import { pickAuthSource } from '../auth/source';+import { CLI_API_KEY_ENV } from '../constants/auth';import { CLI_PRIMARY_BIN } from '../constants/identity';import { cliPackageName } from '../pkg';import { resolveServerUrl } from '../settings';@@ -23,25 +24,27 @@ async function getAuthAndServer(): Promise<{headers: () => Record<string, string>;serverUrl: string;}> {+ // Precedence lives in `pickAuthSource`, shared with `resolveToken` and+ // `lh doctor` so all three agree on which credential wins.+ const source = pickAuthSource();+// LOBEHUB_JWT + LOBEHUB_SERVER env vars (used by server-side sandbox execution)- const envJwt = process.env.LOBEHUB_JWT;- if (envJwt) {+ if (source.kind === 'env-jwt') {const serverUrl = resolveServerUrl();return {// Read per request: `hetero exec` renews its operation token in place, and// its clients live for the whole run.- headers: () => ({ 'Oidc-Auth': process.env.LOBEHUB_JWT || envJwt }),+ headers: () => ({ 'Oidc-Auth': process.env.LOBEHUB_JWT || source.token! }),serverUrl,};}- const envApiKey = readCliApiKeyEnv();- if (envApiKey) {+ if (source.kind === 'env-api-key') {const serverUrl = resolveServerUrl();return {- headers: () => ({ 'X-API-Key': envApiKey }),+ headers: () => ({ 'X-API-Key': source.token! }),serverUrl,};}diff --git a/apps/cli/src/auth/resolveToken.ts b/apps/cli/src/auth/resolveToken.tsindex 2222a5de8c6..a105f380e28 100644--- a/apps/cli/src/auth/resolveToken.ts+++ b/apps/cli/src/auth/resolveToken.ts@@ -1,9 +1,10 @@-import { CLI_API_KEY_ENV, readCliApiKeyEnv } from '../constants/auth';+import { CLI_API_KEY_ENV } from '../constants/auth';import { CLI_PRIMARY_BIN } from '../constants/identity';import { resolveServerUrl } from '../settings';import { log } from '../utils/logger';import { getUserIdFromApiKey } from './apiKey';import { getValidToken } from './refresh';+import { pickAuthSource } from './source';interface ResolveTokenOptions {serviceToken?: string;@@ -33,59 +34,63 @@ export function parseJwtSub(token: string): string | undefined {/*** Resolve an access token from explicit options, environment variables, or stored credentials.* Exits the process if no token can be resolved.+ *+ * The precedence itself lives in `pickAuthSource` so `lh doctor` can report the+ * winning credential without logging in as it.*/export async function resolveToken(options: ResolveTokenOptions): Promise<ResolvedAuth> {- // LOBEHUB_JWT env var takes highest priority (used by server-side sandbox execution)- const envJwt = process.env.LOBEHUB_JWT;- if (envJwt) {- const serverUrl = resolveServerUrl();- const userId = parseJwtSub(envJwt);- if (!userId) {- log.error('Could not extract userId from LOBEHUB_JWT.');- process.exit(1);+ const source = pickAuthSource(options);++ switch (source.kind) {+ // Used by server-side sandbox execution.+ case 'env-jwt': {+ const serverUrl = resolveServerUrl();+ const userId = parseJwtSub(source.token!);+ if (!userId) {+ log.error('Could not extract userId from LOBEHUB_JWT.');+ process.exit(1);+ }+ log.debug('Using LOBEHUB_JWT from environment');+ return { serverUrl, token: source.token!, tokenType: 'jwt', userId };}- log.debug('Using LOBEHUB_JWT from environment');- return { serverUrl, token: envJwt, tokenType: 'jwt', userId };- }- // Explicit token takes priority- if (options.token) {- const userId = parseJwtSub(options.token);- if (!userId) {- log.error('Could not extract userId from token. Provide --user-id explicitly.');- process.exit(1);+ case 'option-token': {+ const userId = parseJwtSub(source.token!);+ if (!userId) {+ log.error('Could not extract userId from token. Provide --user-id explicitly.');+ process.exit(1);+ }+ return { serverUrl: resolveServerUrl(), token: source.token!, tokenType: 'jwt', userId };}- return { serverUrl: resolveServerUrl(), token: options.token, tokenType: 'jwt', userId };- }- if (options.serviceToken) {- if (!options.userId) {- log.error('--user-id is required when using --service-token');- process.exit(1);+ case 'option-service-token': {+ if (!options.userId) {+ log.error('--user-id is required when using --service-token');+ process.exit(1);+ }+ return {+ serverUrl: resolveServerUrl(),+ token: source.token!,+ tokenType: 'serviceToken',+ userId: options.userId!,+ };}- return {- serverUrl: resolveServerUrl(),- token: options.serviceToken,- tokenType: 'serviceToken',- userId: options.userId,- };- }- const envApiKey = readCliApiKeyEnv();- if (envApiKey) {- try {- const serverUrl = resolveServerUrl();- const userId = await getUserIdFromApiKey(envApiKey, serverUrl);- log.debug(`Using ${CLI_API_KEY_ENV} from environment`);- return { serverUrl, token: envApiKey, tokenType: 'apiKey', userId };- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- log.error(`Failed to validate ${CLI_API_KEY_ENV}: ${message}`);- process.exit(1);+ case 'env-api-key': {+ try {+ const serverUrl = resolveServerUrl();+ const userId = await getUserIdFromApiKey(source.token!, serverUrl);+ log.debug(`Using ${source.origin} from environment`);+ return { serverUrl, token: source.token!, tokenType: 'apiKey', userId };+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log.error(`Failed to validate ${source.origin}: ${message}`);+ process.exit(1);+ }}}- // Try stored credentials+ // Stored credentials, refreshed when the access token is close to expiry.const result = await getValidToken();if (result) {log.debug('Using stored credentials');diff --git a/apps/cli/src/auth/source.ts b/apps/cli/src/auth/source.tsnew file mode 100644index 00000000000..bb825e77d4e--- /dev/null+++ b/apps/cli/src/auth/source.ts@@ -0,0 +1,89 @@+import os from 'node:os';+import path from 'node:path';++import { readCliApiKeyEnvSource, resolveCliDirName } from '../constants/identity';+import { loadCredentials } from './credentials';++export type AuthSourceKind =+ 'env-jwt' | 'option-token' | 'option-service-token' | 'env-api-key' | 'stored';++export interface AuthSource {+ kind: AuthSourceKind;+ /** Where the credential came from, phrased the way a user would recognise it. */+ origin: string;+ /**+ * The raw credential, when one exists. Empty for `stored` when nothing has+ * been logged in β the fallback kind is returned regardless so callers keep+ * their existing "try the stored login, then complain" flow.+ */+ token?: string;+ tokenType: 'apiKey' | 'jwt' | 'serviceToken';+}++/**+ * Decide WHICH credential a command authenticates with, in one place.+ *+ * The precedence β `LOBEHUB_JWT` (server-dispatched runs) > explicit flags >+ * `LOBEHUB_CLI_API_KEY` > the stored login β was previously spelled out+ * separately in `resolveToken` and in the tRPC client's `getAuthAndServer`.+ * `lh doctor` needs to report the winner without performing the login, which+ * would have made a third copy; two copies had already drifted apart on which+ * env var names they accept.+ *+ * Deliberately does not refresh or validate anything: `stored` yields the+ * token as written on disk, and callers that need a live token still go+ * through `getValidToken()`.+ */+export function pickAuthSource(+ options: { serviceToken?: string; token?: string } = {},+): AuthSource {+ const envJwt = process.env.LOBEHUB_JWT;+ if (envJwt) return { kind: 'env-jwt', origin: 'LOBEHUB_JWT', token: envJwt, tokenType: 'jwt' };++ if (options.token)+ return { kind: 'option-token', origin: '--token', token: options.token, tokenType: 'jwt' };++ if (options.serviceToken)+ return {+ kind: 'option-service-token',+ origin: '--service-token',+ token: options.serviceToken,+ tokenType: 'serviceToken',+ };++ const apiKey = readCliApiKeyEnvSource();+ if (apiKey)+ return { kind: 'env-api-key', origin: apiKey.name, token: apiKey.value, tokenType: 'apiKey' };++ return {+ kind: 'stored',+ origin: `stored login (${credentialsPath()})`,+ token: loadCredentials()?.accessToken,+ tokenType: 'jwt',+ };+}++/** Path of the credentials file, for diagnostics that name it. */+export function credentialsPath(): string {+ return path.join(os.homedir(), resolveCliDirName(), 'credentials.json');+}++/** Last 4 characters of a secret, everything else elided. */+export function maskSecret(token: string | undefined): string {+ if (!token) return 'none';+ return token.length <= 4 ? '****' : `β¦${token.slice(-4)}`;+}++/** Parse a JWT's payload without verifying the signature. */+export function parseJwtPayload(token: string): Record<string, unknown> | undefined {+ try {+ const payload: unknown = JSON.parse(+ Buffer.from(token.split('.')[1], 'base64url').toString('utf8'),+ );+ return payload && typeof payload === 'object'+ ? (payload as Record<string, unknown>)+ : undefined;+ } catch {+ return undefined;+ }+}diff --git a/apps/cli/src/commands/doctor.test.ts b/apps/cli/src/commands/doctor.test.tsnew file mode 100644index 00000000000..ef570261eae--- /dev/null+++ b/apps/cli/src/commands/doctor.test.ts@@ -0,0 +1,140 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { registerDoctorCommand } from './doctor';++const runDoctor = vi.hoisted(() => vi.fn());+const report = vi.hoisted(() => ({+ value: {+ checks: [],+ cli: { bin: 'lh', version: '0.0.55' },+ generatedAt: '2026-09-16T00:00:00.000Z',+ profile: 'core',+ status: 'ok',+ summary: { fail: 0, ok: 1, skip: 0, warn: 0 },+ } as any,+}));++vi.mock('../doctor', () => ({+ ALL_CHECKS: [],+ exitCodeFor: (r: any, strict: boolean) =>+ r.status === 'fail' || (strict && r.status === 'warn') ? 1 : 0,+ renderReport: () => 'rendered',+ runDoctor: (checks: unknown, options: unknown) => runDoctor(checks, options),+}));++describe('doctor command', () => {+ let exitSpy: ReturnType<typeof vi.spyOn>;+ let logSpy: ReturnType<typeof vi.spyOn>;+ let writeSpy: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ runDoctor.mockResolvedValue(report.value);+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});+ // The command exits from a stdout write callback; drain synchronously so+ // that callback runs while process.exit is still mocked.+ writeSpy = vi.spyOn(process.stdout, 'write').mockImplementation(((+ _chunk: unknown,+ callback?: () => void,+ ) => {+ callback?.();+ return true;+ }) as any);+ });++ afterEach(() => {+ process.exitCode = 0;+ report.value.status = 'ok';+ exitSpy.mockRestore();+ logSpy.mockRestore();+ writeSpy.mockRestore();+ vi.clearAllMocks();+ });++ const run = async (...args: string[]) => {+ const program = new Command();+ registerDoctorCommand(program);+ await program.parseAsync(['doctor', ...args], { from: 'user' });+ return runDoctor.mock.calls.at(-1)?.[1];+ };++ it('defaults to the core profile with a 10s budget', async () => {+ expect(await run()).toMatchObject({+ deep: false,+ fix: false,+ offline: false,+ profile: 'core',+ strict: false,+ timeoutMs: 10_000,+ });+ });++ it('parses the flags into options', async () => {+ expect(+ await run(+ '--profile',+ 'connect',+ '--offline',+ '--deep',+ '--fix',+ '--strict',+ '--agent',+ 'inbox',+ '--timeout',+ '2500',+ ),+ ).toMatchObject({+ agent: 'inbox',+ deep: true,+ fix: true,+ offline: true,+ profile: 'connect',+ strict: true,+ timeoutMs: 2500,+ });+ });++ it('splits --hetero into a list', async () => {+ expect((await run('--hetero', 'claude-code, codex'))?.hetero).toEqual(['claude-code', 'codex']);+ });++ it('falls back to the default budget for a nonsense --timeout', async () => {+ expect((await run('--timeout', 'soon'))?.timeoutMs).toBe(10_000);+ });++ it('rejects an unknown profile before running anything', async () => {+ const program = new Command();+ registerDoctorCommand(program);+ await program.parseAsync(['doctor', '--profile', 'everything'], { from: 'user' });++ expect(runDoctor).not.toHaveBeenCalled();+ expect(exitSpy).toHaveBeenCalledWith(1);+ });++ it('prints the report as JSON when asked', async () => {+ await run('--json');++ expect(logSpy.mock.calls.at(-1)?.[0]).toContain('"profile": "core"');+ });++ it('exits with the contract code only after stdout has drained', async () => {+ // Exiting before the drain truncates a piped report; waiting for the event+ // loop instead lets an abandoned request hold the process open.+ const order: string[] = [];+ writeSpy.mockImplementation(((_chunk: unknown, callback?: () => void) => {+ order.push('drained');+ callback?.();+ return true;+ }) as any);+ exitSpy.mockImplementation(((code: number) => {+ order.push(`exit ${code}`);+ }) as any);++ await run();+ report.value.status = 'fail';+ await run();++ expect(order).toEqual(['drained', 'exit 0', 'drained', 'exit 1']);+ });+});diff --git a/apps/cli/src/commands/doctor.ts b/apps/cli/src/commands/doctor.tsnew file mode 100644index 00000000000..47eb417c8d5--- /dev/null+++ b/apps/cli/src/commands/doctor.ts@@ -0,0 +1,83 @@+import type { Command } from 'commander';++import { ALL_CHECKS, exitCodeFor, renderReport, runDoctor } from '../doctor';+import type { DoctorOptions, DoctorProfile } from '../doctor/types';+import { DOCTOR_PROFILES } from '../doctor/types';+import { outputJson } from '../utils/format';+import { log, setVerbose } from '../utils/logger';++interface DoctorCommandOptions {+ agent?: string;+ deep?: boolean;+ fix?: boolean;+ hetero?: string;+ json?: string | boolean;+ offline?: boolean;+ profile?: string;+ strict?: boolean;+ timeout?: string;+ verbose?: boolean;+}++export function registerDoctorCommand(program: Command) {+ program+ .command('doctor')+ .description(+ 'Diagnose this machine: runtime, endpoints, credentials, scope, device and agent readiness',+ )+ .option('--profile <name>', `Which layers to check (${DOCTOR_PROFILES.join(', ')})`, 'core')+ .option('--json [fields]', 'Output the report as JSON, optionally picking fields')+ .option('--offline', 'Skip every check that would touch the network')+ .option('--deep', 'Include the slow, costly checks (starts a real agent run)')+ .option('--fix', 'Apply the repairs the failing checks know how to apply')+ .option('--strict', 'Exit non-zero on warnings too')+ .option('--agent <idOrSlug>', 'Agent to check execution readiness against')+ .option(+ '--hetero <types>',+ 'Comma-separated external agent types to probe (e.g. claude-code,codex)',+ )+ .option('--timeout <ms>', 'Per-check budget for anything on the network', '10000')+ .option('-v, --verbose', 'Show the evidence behind each check')+ .action(async (options: DoctorCommandOptions) => {+ if (options.verbose) setVerbose(true);++ const profile = (options.profile ?? 'core') as DoctorProfile;+ if (!DOCTOR_PROFILES.includes(profile)) {+ log.error(`Unknown profile "${profile}". Use one of: ${DOCTOR_PROFILES.join(', ')}.`);+ process.exit(1);+ return;+ }++ const parsedTimeout = Number.parseInt(options.timeout ?? '10000', 10);+ const doctorOptions: DoctorOptions = {+ agent: options.agent,+ deep: Boolean(options.deep),+ fix: Boolean(options.fix),+ hetero: options.hetero+ ?.split(',')+ .map((type) => type.trim())+ .filter(Boolean),+ offline: Boolean(options.offline),+ profile,+ strict: Boolean(options.strict),+ timeoutMs: Number.isFinite(parsedTimeout) && parsedTimeout > 0 ? parsedTimeout : 10_000,+ };++ const report = await runDoctor(ALL_CHECKS, doctorOptions);++ if (options.json !== undefined) {+ outputJson(report, typeof options.json === 'string' ? options.json : undefined);+ } else {+ console.log(renderReport(report, { verbose: options.verbose }));+ }++ // Exit once stdout has drained, not before and not whenever the event loop+ // happens to empty. `process.exit()` right after a large write truncates a+ // piped JSON report; waiting for the loop instead lets a request abandoned+ // by a check timeout (a stalled token refresh, a trickling response) keep+ // the process alive long after the report is done. A write callback fires+ // only after everything queued before it has been flushed.+ const code = exitCodeFor(report, doctorOptions.strict);+ process.stdout.write('', () => process.exit(code));+ });+}diff --git a/apps/cli/src/commands/status.test.ts b/apps/cli/src/commands/status.test.tsindex 53b6050ad7f..53bd58b98b0 100644--- a/apps/cli/src/commands/status.test.ts+++ b/apps/cli/src/commands/status.test.ts@@ -26,7 +26,9 @@ let connectCalled = false;let clientOptions: any = {};vi.mock('@lobechat/device-gateway-client', () => ({- GatewayClient: vi.fn().mockImplementation((opts: any) => {+ // A plain function, not an arrow: the command calls `new GatewayClient(...)`,+ // and an arrow implementation is not constructible.+ GatewayClient: vi.fn().mockImplementation(function (opts: any) {clientOptions = opts;clientEventHandlers = {};connectCalled = false;@@ -131,6 +133,19 @@ describe('status command', () => {expect(exitSpy).toHaveBeenCalledWith(0);});+ it('should point a failed handshake at doctor', async () => {+ const program = createProgram();+ const parsePromise = program.parseAsync(['node', 'test', 'status']);+ await vi.advanceTimersByTimeAsync(0);++ clientEventHandlers['auth_failed']?.('signature verification failed');++ await parsePromise;+ expect(log.error).toHaveBeenCalledWith(+ "Run 'lh doctor --profile connect' for a full diagnosis.",+ );+ });+it('should log FAILED on disconnected', async () => {const program = createProgram();const parsePromise = program.parseAsync(['node', 'test', 'status']);diff --git a/apps/cli/src/commands/status.ts b/apps/cli/src/commands/status.tsindex 985ced5a5a0..9f33f959691 100644--- a/apps/cli/src/commands/status.ts+++ b/apps/cli/src/commands/status.ts@@ -2,10 +2,18 @@ import { GatewayClient } from '@lobechat/device-gateway-client';import type { Command } from 'commander';import { resolveToken } from '../auth/resolveToken';+import { CLI_PRIMARY_BIN } from '../constants/identity';import { OFFICIAL_GATEWAY_URL } from '../constants/urls';import { loadSettings, normalizeUrl, saveSettings } from '../settings';import { log, setVerbose } from '../utils/logger';+/**+ * `status` answers one question β does the gateway accept this machine. When it+ * says no, the cause is usually a layer below it (wrong gateway URL, expired+ * login, a clock that drifted), which is what `doctor` walks through.+ */+const DIAGNOSE_HINT = `Run '${CLI_PRIMARY_BIN} doctor --profile connect' for a full diagnosis.`;+interface StatusOptions {gateway?: string;serviceToken?: string;@@ -58,6 +66,7 @@ export function registerStatusCommand(program: Command) {const timer = setTimeout(() => {log.error('FAILED - Connection timed out');+ log.error(DIAGNOSE_HINT);client.disconnect();process.exit(1);}, timeout);@@ -72,18 +81,21 @@ export function registerStatusCommand(program: Command) {client.on('disconnected', () => {clearTimeout(timer);log.error('FAILED - Connection closed by server');+ log.error(DIAGNOSE_HINT);process.exit(1);});client.on('auth_failed', (reason) => {clearTimeout(timer);log.error(`FAILED - Authentication failed: ${reason}`);+ log.error(DIAGNOSE_HINT);process.exit(1);});client.on('auth_expired', () => {clearTimeout(timer);log.error('FAILED - Authentication expired');+ log.error(DIAGNOSE_HINT);client.disconnect();process.exit(1);});diff --git a/apps/cli/src/commands/update.ts b/apps/cli/src/commands/update.tsindex d299894240c..a4e2d2af860 100644--- a/apps/cli/src/commands/update.ts+++ b/apps/cli/src/commands/update.ts@@ -84,7 +84,8 @@ export function isNewerVersion(latest: string, current: string): boolean {return semver.gt(latestParsed, currentParsed);}-async function fetchLatestVersion(name: string, tag: string): Promise<string> {+/** Published version behind an npm dist-tag. Also used by `lh doctor`. */+export async function fetchLatestVersion(name: string, tag: string): Promise<string> {const url = `https://registry.npmjs.org/${name}/${encodeURIComponent(tag)}`;const res = await fetch(url, { headers: { accept: 'application/json' } });diff --git a/apps/cli/src/constants/identity.ts b/apps/cli/src/constants/identity.tsindex 0b9f18f88a4..9a6e7fabf4a 100644--- a/apps/cli/src/constants/identity.ts+++ b/apps/cli/src/constants/identity.ts@@ -72,17 +72,27 @@ export const CLI_CONNECT_SERVICE_NAME = 'lobehub-connect.service';export const CLI_API_KEY_ENV_NAMES: readonly string[] = ['LOBEHUB_CLI_API_KEY'];export const CLI_HOME_ENV_NAMES: readonly string[] = ['LOBEHUB_CLI_HOME'];-const firstEnvValue = (names: readonly string[]): string | undefined => {+const firstEnvEntry = (names: readonly string[]): { name: string; value: string } | undefined => {for (const name of names) {const value = process.env[name]?.trim();- if (value) return value;+ if (value) return { name, value };}return undefined;};+const firstEnvValue = (names: readonly string[]): string | undefined => firstEnvEntry(names)?.value;+/** API key from the environment, honouring every accepted variable name. */export const readCliApiKeyEnv = (): string | undefined => firstEnvValue(CLI_API_KEY_ENV_NAMES);+/**+ * Same lookup as {@link readCliApiKeyEnv}, but keeps the variable name that+ * actually matched. `lh doctor` reports which env var a credential came from,+ * and "LOBEHUB_CLI_API_KEY" is the wrong answer when an older alias won.+ */+export const readCliApiKeyEnvSource = (): { name: string; value: string } | undefined =>+ firstEnvEntry(CLI_API_KEY_ENV_NAMES);+/** Config directory name, overridable per-install by the home env var. */export const resolveCliDirName = (): string =>firstEnvValue(CLI_HOME_ENV_NAMES) ?? CLI_CONFIG_DIR_NAME;diff --git a/apps/cli/src/doctor/checks/context.test.ts b/apps/cli/src/doctor/checks/context.test.tsnew file mode 100644index 00000000000..db7e79b06d4--- /dev/null+++ b/apps/cli/src/doctor/checks/context.test.ts@@ -0,0 +1,30 @@+import { beforeEach, describe, expect, it } from 'vitest';++import { runCheck } from '../testUtils';+import { contextChecks } from './context';++describe('context.inherited', () => {+ beforeEach(() => {+ delete process.env.LOBEHUB_TOPIC_ID;+ delete process.env.LOBEHUB_OPERATION_ID;+ delete process.env.LOBEHUB_AGENT_ID;+ delete process.env.LOBEHUB_ASSISTANT_MESSAGE_ID;+ });++ it('passes in a clean shell', async () => {+ const outcome = await runCheck(contextChecks, 'context.inherited');++ expect(outcome.status).toBe('ok');+ });++ it('warns about inherited ids and shows how to strip them', async () => {+ process.env.LOBEHUB_TOPIC_ID = 'tpc_1';+ process.env.LOBEHUB_OPERATION_ID = 'op_1';++ const outcome = await runCheck(contextChecks, 'context.inherited');++ expect(outcome.status).toBe('warn');+ expect(outcome.fix).toContain('env -u LOBEHUB_TOPIC_ID -u LOBEHUB_OPERATION_ID lh <command>');+ expect(outcome.evidence).toEqual({ LOBEHUB_OPERATION_ID: 'op_1', LOBEHUB_TOPIC_ID: 'tpc_1' });+ });+});diff --git a/apps/cli/src/doctor/checks/context.ts b/apps/cli/src/doctor/checks/context.tsnew file mode 100644index 00000000000..bb1fc10e8a7--- /dev/null+++ b/apps/cli/src/doctor/checks/context.ts@@ -0,0 +1,44 @@+import type { CheckOutcome, DoctorCheck } from '../types';++/**+ * Variables that redirect where a command's output lands, rather than whether+ * it works.+ *+ * Inside a LobeHub conversation these are injected on purpose. Inherited into+ * an unrelated shell β a terminal opened from an agent run, a script started by+ * one β they quietly reattach new work to an old topic or operation, which is+ * invisible until someone wonders why a fresh acceptance became "round 7" of a+ * different one.+ */+const REDIRECTING_ENV: { name: string; what: string }[] = [+ { name: 'LOBEHUB_TOPIC_ID', what: 'new messages attach to this topic' },+ { name: 'LOBEHUB_OPERATION_ID', what: 'ingested events attach to this operation' },+ { name: 'LOBEHUB_AGENT_ID', what: 'work is attributed to this agent' },+ { name: 'LOBEHUB_ASSISTANT_MESSAGE_ID', what: 'output attaches to this message' },+];++const inheritedContext: DoctorCheck = {+ group: 'context',+ id: 'context.inherited',+ profiles: ['core'],+ run: (): CheckOutcome => {+ const present = REDIRECTING_ENV.filter(({ name }) => Boolean(process.env[name]?.trim()));+ const evidence = Object.fromEntries(present.map(({ name }) => [name, process.env[name]]));++ if (present.length === 0)+ return {+ detail: 'No inherited run context; commands write where you point them.',+ status: 'ok',+ };++ return {+ detail: `${present.length} inherited variable(s): ${present.map((entry) => `${entry.name} β ${entry.what}`).join('; ')}.`,+ evidence,+ fix: `Expected inside an agent run. In a plain shell, strip them: env ${present.map((entry) => `-u ${entry.name}`).join(' ')} lh <command>`,+ status: 'warn',+ };+ },+ title: 'inherited run context',+};++export const contextChecks: readonly DoctorCheck[] = [inheritedContext];diff --git a/apps/cli/src/doctor/checks/credentials.test.ts b/apps/cli/src/doctor/checks/credentials.test.tsnew file mode 100644index 00000000000..b3862c622f2--- /dev/null+++ b/apps/cli/src/doctor/checks/credentials.test.ts@@ -0,0 +1,124 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { runCheck } from '../testUtils';+import { credentialChecks } from './credentials';++const source = vi.hoisted(() => ({ value: {} as any }));+const credential = vi.hoisted(() => ({ value: {} as any }));+const serverVersion = vi.hoisted(() => ({ value: {} as any }));++vi.mock('../../auth/source', () => ({+ maskSecret: (token?: string) => (token ? `β¦${token.slice(-4)}` : 'none'),+ pickAuthSource: () => source.value,+}));++vi.mock('../probes', () => ({+ probeCredential: async () => credential.value,+ probeServerVersion: async () => serverVersion.value,+}));++describe('credentials.source', () => {+ beforeEach(() => {+ source.value = { kind: 'stored', origin: 'stored login', token: 'abcd1234', tokenType: 'jwt' };+ });++ it('fails when nothing is available to authenticate with', async () => {+ source.value = { kind: 'stored', origin: 'stored login', tokenType: 'jwt' };++ const outcome = await runCheck(credentialChecks, 'credentials.source');++ expect(outcome.status).toBe('fail');+ expect(outcome.fix).toContain('login');+ });++ it('warns that an inherited LOBEHUB_JWT outranks the stored login', async () => {+ source.value = { kind: 'env-jwt', origin: 'LOBEHUB_JWT', token: 'x.y.zzzz', tokenType: 'jwt' };++ const outcome = await runCheck(credentialChecks, 'credentials.source');++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('not with the stored login');+ });++ it('never prints the credential itself', async () => {+ const outcome = await runCheck(credentialChecks, 'credentials.source');++ expect(outcome.detail).not.toContain('abcd1234');+ expect(JSON.stringify(outcome.evidence)).not.toContain('abcd1234');+ });+});++describe('credentials.validity', () => {+ it('reports why an API key was rejected', async () => {+ credential.value = {+ error: 'Request failed with status 401.',+ kind: 'env-api-key',+ origin: 'LOBEHUB_CLI_API_KEY',+ tokenType: 'apiKey',+ };++ const outcome = await runCheck(credentialChecks, 'credentials.validity');++ expect(outcome.status).toBe('fail');+ expect(outcome.fix).toContain('LOBEHUB_CLI_API_KEY');+ });++ it('fails an expired token that could not refresh', async () => {+ credential.value = {+ expiresAt: Math.floor(Date.now() / 1000) - 600,+ kind: 'stored',+ origin: 'stored login',+ tokenType: 'jwt',+ userId: 'user_1',+ };++ const outcome = await runCheck(credentialChecks, 'credentials.validity');++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('expired');+ });++ it('warns when the token is about to expire mid-command', async () => {+ credential.value = {+ expiresAt: Math.floor(Date.now() / 1000) + 120,+ kind: 'stored',+ origin: 'stored login',+ tokenType: 'jwt',+ userId: 'user_1',+ };++ const outcome = await runCheck(credentialChecks, 'credentials.validity');++ expect(outcome.status).toBe('warn');+ });++ it('accepts an API key that carries no subject', async () => {+ credential.value = { kind: 'env-api-key', origin: 'LOBEHUB_CLI_API_KEY', tokenType: 'apiKey' };++ const outcome = await runCheck(credentialChecks, 'credentials.validity');++ expect(outcome.status).toBe('ok');+ });+});++describe('credentials.clock', () => {+ it('fails on skew large enough to break token validation', async () => {+ serverVersion.value = {+ dateHeader: new Date(Date.now() - 600_000).toUTCString(),+ latencyMs: 20,+ };++ const outcome = await runCheck(credentialChecks, 'credentials.clock');++ expect(outcome.status).toBe('fail');+ expect(outcome.fix).toContain('time sync');+ });++ it('passes when the clocks agree', async () => {+ serverVersion.value = { dateHeader: new Date().toUTCString(), latencyMs: 20 };++ const outcome = await runCheck(credentialChecks, 'credentials.clock');++ expect(outcome.status).toBe('ok');+ });+});diff --git a/apps/cli/src/doctor/checks/credentials.ts b/apps/cli/src/doctor/checks/credentials.tsnew file mode 100644index 00000000000..8695f09dd38--- /dev/null+++ b/apps/cli/src/doctor/checks/credentials.ts@@ -0,0 +1,173 @@+import { maskSecret, pickAuthSource } from '../../auth/source';+import { CLI_API_KEY_ENV } from '../../constants/auth';+import { CLI_PRIMARY_BIN } from '../../constants/identity';+import { probeCredential, probeServerVersion } from '../probes';+import type { CheckOutcome, DoctorCheck } from '../types';++/**+ * Which credential wins β asked and answered before anything tries to use it.+ *+ * A `LOBEHUB_JWT` inherited from a parent agent run silently outranks the login+ * the user is thinking of, and that mismatch reads downstream as "the server+ * lost my data" rather than "you are a different principal than you assume".+ */+const credentialSource: DoctorCheck = {+ group: 'credentials',+ id: 'credentials.source',+ profiles: ['core'],+ run: (): CheckOutcome => {+ const source = pickAuthSource();+ const evidence = {+ kind: source.kind,+ origin: source.origin,+ token: maskSecret(source.token),+ tokenType: source.tokenType,+ };++ if (!source.token)+ return {+ detail: 'No credential anywhere: no login on disk, no API key in the environment.',+ evidence,+ fix: `Run '${CLI_PRIMARY_BIN} login', or set ${CLI_API_KEY_ENV}.`,+ status: 'fail',+ };++ if (source.kind === 'env-jwt')+ return {+ detail: `Authenticating with the LOBEHUB_JWT in this environment (${maskSecret(source.token)}), not with the stored login.`,+ evidence,+ fix: 'Expected? This is how server-dispatched runs authenticate. If not, unset LOBEHUB_JWT.',+ status: 'warn',+ };++ return {+ detail: `Using ${source.origin} (${maskSecret(source.token)}).`,+ evidence,+ status: 'ok',+ };+ },+ title: 'credential source',+};++const credentialValidity: DoctorCheck = {+ dependsOn: ['credentials.source', 'endpoints.reachable'],+ group: 'credentials',+ id: 'credentials.validity',+ network: true,+ profiles: ['core'],+ run: async (ctx): Promise<CheckOutcome> => {+ const credential = await probeCredential(ctx);+ const expiresInSeconds = credential.expiresAt+ ? credential.expiresAt - Date.now() / 1000+ : undefined;+ const evidence = {+ expiresAt: credential.expiresAt+ ? new Date(credential.expiresAt * 1000).toISOString()+ : undefined,+ kind: credential.kind,+ tokenType: credential.tokenType,+ userId: credential.userId,+ };++ if (credential.error)+ return {+ detail: `${credential.origin} cannot be used: ${credential.error}.`,+ evidence,+ fix:+ credential.kind === 'env-api-key'+ ? `Issue a fresh key and re-export ${CLI_API_KEY_ENV}.`+ : `Run '${CLI_PRIMARY_BIN} login' again.`,+ status: 'fail',+ };++ if (!credential.userId)+ return {+ detail: `${credential.origin} carries no readable subject, so no account can be derived from it.`,+ evidence,+ fix:+ credential.tokenType === 'apiKey'+ ? 'Expected for API keys; set LOBEHUB_WORKSPACE_ID explicitly if you need workspace scope.'+ : `Run '${CLI_PRIMARY_BIN} login' again.`,+ status: credential.tokenType === 'apiKey' ? 'ok' : 'fail',+ };++ if (expiresInSeconds !== undefined && expiresInSeconds < 0)+ return {+ detail: `The token for ${credential.userId} expired ${Math.round(-expiresInSeconds / 60)} minutes ago and did not refresh.`,+ evidence,+ fix: `Run '${CLI_PRIMARY_BIN} login' again.`,+ status: 'fail',+ };++ if (expiresInSeconds !== undefined && expiresInSeconds < 300)+ return {+ detail: `Valid for ${credential.userId}, but expires in ${Math.round(expiresInSeconds / 60)} minutes.`,+ evidence,+ fix: 'A long-running command may outlive it; refresh now with a fresh login.',+ status: 'warn',+ };++ return {+ detail: `Valid for ${credential.userId} via ${credential.origin}.`,+ evidence,+ status: 'ok',+ };+ },+ title: 'credential validity',+};++/**+ * Clock skew breaks token validation with errors that name neither the clock+ * nor the token β they come back as plain 401s from JWKS verification.+ */+const clockSkew: DoctorCheck = {+ dependsOn: ['endpoints.reachable'],+ group: 'credentials',+ id: 'credentials.clock',+ network: true,+ profiles: ['core'],+ run: async (ctx): Promise<CheckOutcome> => {+ const probe = await probeServerVersion(ctx);+ if (!probe.dateHeader)+ return { detail: 'The server did not send a Date header; skew is unknown.', status: 'ok' };++ // The header is stamped when the response leaves; half the round trip is+ // the fairest correction available without a dedicated time endpoint.+ const serverTime = new Date(probe.dateHeader).getTime();+ const skewMs = Math.abs(Date.now() - probe.latencyMs / 2 - serverTime);+ const evidence = {+ latencyMs: probe.latencyMs,+ serverTime: probe.dateHeader,+ skewSeconds: Math.round(skewMs / 1000),+ };++ if (skewMs > 300_000)+ return {+ detail: `This machine's clock is ${Math.round(skewMs / 1000)}s away from the server's.`,+ evidence,+ fix: 'Enable network time sync β token validation fails as a plain 401 at this much skew.',+ status: 'fail',+ };++ if (skewMs > 60_000)+ return {+ detail: `Clock differs from the server by ${Math.round(skewMs / 1000)}s.`,+ evidence,+ fix: 'Enable network time sync before it grows.',+ status: 'warn',+ };++ return {+ detail: `Clock is within ${Math.round(skewMs / 1000)}s of the server.`,+ evidence,+ status: 'ok',+ };+ },+ title: 'clock skew',+};++export const credentialChecks: readonly DoctorCheck[] = [+ credentialSource,+ credentialValidity,+ clockSkew,+];diff --git a/apps/cli/src/doctor/checks/device.test.ts b/apps/cli/src/doctor/checks/device.test.tsnew file mode 100644index 00000000000..da314a806c7--- /dev/null+++ b/apps/cli/src/doctor/checks/device.test.ts@@ -0,0 +1,150 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { makeContext, runCheck } from '../testUtils';+import { deviceChecks } from './device';++const state = vi.hoisted(() => ({+ daemonPid: null as number | null,+ daemonStatus: null as any,+ devices: [] as any[],+ localDeviceId: undefined as string | undefined,+}));++const removePid = vi.hoisted(() => vi.fn());+const removeStatus = vi.hoisted(() => vi.fn());++vi.mock('../../daemon/manager', () => ({+ getRunningDaemonPid: () => state.daemonPid,+ readStatus: () => state.daemonStatus,+ removePid,+ removeStatus,+}));++vi.mock('../../service/connect', () => ({+ readConnectServiceStatus: () => {+ throw new Error('not systemd');+ },+}));++vi.mock('../../utils/device', () => ({ resolveLocalDeviceId: () => state.localDeviceId }));++vi.mock('../probes', () => ({+ probeCredential: async () => ({+ serverUrl: 'https://app.lobehub.com',+ token: 't',+ tokenType: 'jwt',+ userId: 'u',+ }),+ probeDevices: async () => state.devices,+}));++describe('device.daemon', () => {+ beforeEach(() => {+ state.daemonPid = null;+ state.daemonStatus = null;+ });++ it('survives a platform without the connect service', async () => {+ const outcome = await runCheck(deviceChecks, 'device.daemon');++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('No connect daemon');+ });++ it('flags a status file with no daemon behind it', async () => {+ state.daemonStatus = {+ connectionStatus: 'connected',+ deviceId: 'dev_1',+ gatewayUrl: 'wss://gw',+ pid: 4,+ startedAt: '',+ };++ const outcome = await runCheck(deviceChecks, 'device.daemon');++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('left over');+ });++ it('does not call a live daemon connected without its own report', async () => {+ state.daemonPid = 42;+ state.daemonStatus = null;++ const outcome = await runCheck(deviceChecks, 'device.daemon');++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('has not reported a connection state');+ });++ it('reports a healthy daemon', async () => {+ state.daemonPid = 42;+ state.daemonStatus = {+ connectionStatus: 'connected',+ deviceId: 'dev_1',+ gatewayUrl: 'wss://gw',+ pid: 42,+ startedAt: '',+ };++ const outcome = await runCheck(deviceChecks, 'device.daemon');++ expect(outcome.status).toBe('ok');+ expect(outcome.detail).toContain('dev_1');+ });++ it('flags a daemon whose last known state was not connected', async () => {+ state.daemonPid = 42;+ state.daemonStatus = {+ connectionStatus: 'reconnecting',+ deviceId: 'dev_1',+ gatewayUrl: 'wss://gw',+ pid: 42,+ startedAt: '',+ };++ const outcome = await runCheck(deviceChecks, 'device.daemon');++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('reconnecting');+ });+});++describe('device.registration', () => {+ beforeEach(() => {+ state.devices = [];+ state.localDeviceId = undefined;+ });++ it('fails when this machine has never connected and nothing else is online', async () => {+ const outcome = await runCheck(deviceChecks, 'device.registration', makeContext());++ expect(outcome.status).toBe('fail');+ });++ it('only warns when other devices are online', async () => {+ state.devices = [{ deviceId: 'dev_other', online: true }];++ const outcome = await runCheck(deviceChecks, 'device.registration', makeContext());++ expect(outcome.status).toBe('warn');+ });++ it('fails when the local device is registered but offline', async () => {+ state.localDeviceId = 'dev_local';+ state.devices = [{ deviceId: 'dev_local', online: false }];++ const outcome = await runCheck(deviceChecks, 'device.registration', makeContext());++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('offline');+ });++ it('passes when the local device is online', async () => {+ state.localDeviceId = 'dev_local';+ state.devices = [{ deviceId: 'dev_local', online: true }];++ const outcome = await runCheck(deviceChecks, 'device.registration', makeContext());++ expect(outcome.status).toBe('ok');+ });+});diff --git a/apps/cli/src/doctor/checks/device.ts b/apps/cli/src/doctor/checks/device.tsnew file mode 100644index 00000000000..9bc17086a06--- /dev/null+++ b/apps/cli/src/doctor/checks/device.ts@@ -0,0 +1,255 @@+import { GatewayClient } from '@lobechat/device-gateway-client';++import { CLI_PRIMARY_BIN } from '../../constants/identity';+import { getRunningDaemonPid, readStatus, removePid, removeStatus } from '../../daemon/manager';+import { readConnectServiceStatus } from '../../service/connect';+import { resolveLocalDeviceId } from '../../utils/device';+import { probeCredential, probeDevices } from '../probes';+import { redactUrlCredentials, redactUrlsInMessage } from '../redact';+import type { CheckOutcome, DoctorCheck } from '../types';+import { resolveEndpoints } from './endpoints';++/**+ * Is there a `lh connect` daemon on this machine, and is the state it left+ * behind still true?+ */+const daemon: DoctorCheck = {+ group: 'device',+ id: 'device.daemon',+ profiles: ['connect'],+ repair: (_ctx, result) => {+ // Only the leftover-files case is repairable. A daemon that is merely+ // reconnecting is still a live process: deleting its pid file would orphan+ // it where `connect stop` can never find it, and the next `connect` would+ // start a second one alongside it.+ if (result.evidence?.repairable !== 'stale-files')+ throw new Error('the daemon process is still running, so its pid file is not stale');++ removePid();+ removeStatus();+ return 'removed the stale daemon pid/status files';+ },+ run: (): CheckOutcome => {+ // Also self-heals: a pid file whose process is gone (or was recycled by the+ // OS) is deleted as a side effect of asking.+ const pid = getRunningDaemonPid();+ const status = readStatus();+ const service = readServiceStatus();+ const evidence = {+ connectionStatus: status?.connectionStatus,+ deviceId: status?.deviceId,+ gatewayUrl: status?.gatewayUrl,+ pid,+ service,+ };++ if (!pid) {+ if (status)+ return {+ detail: 'A daemon status file is left over, but no daemon is running.',+ evidence: { ...evidence, repairable: 'stale-files' },+ fix: `Run '${CLI_PRIMARY_BIN} connect --daemon', or re-run with --fix to clear the leftovers.`,+ status: 'warn',+ };++ return {+ detail: 'No connect daemon on this machine.',+ evidence,+ fix: `Run '${CLI_PRIMARY_BIN} connect --daemon' if this machine should be reachable as a device.`,+ status: 'warn',+ };+ }++ // A live process is not a connection: success needs the daemon's own report.+ if (!status?.connectionStatus)+ return {+ detail: `Daemon ${pid} is running but has not reported a connection state.`,+ evidence,+ fix: `Check the daemon log: ${CLI_PRIMARY_BIN} connect logs`,+ status: 'warn',+ };++ if (status.connectionStatus !== 'connected')+ return {+ detail: `Daemon ${pid} is running but its last known state is "${status.connectionStatus}".`,+ evidence,+ fix: `Check the daemon log: ${CLI_PRIMARY_BIN} connect logs`,+ status: 'warn',+ };++ return {+ detail: `Daemon ${pid} connected as device ${status.deviceId ?? 'unknown'}.`,+ evidence,+ status: 'ok',+ };+ },+ title: 'connect daemon',+};++function readServiceStatus(): unknown {+ try {+ return readConnectServiceStatus();+ } catch {+ // Not installed, or not a systemd platform β neither is a finding.+ return undefined;+ }+}++/**+ * Can this machine authenticate to the device gateway at all β separating+ * "wrong URL", "rejected token" and "nothing answers", which all present as a+ * bare DEVICE_OFFLINE to whoever called the tool.+ */+const gatewayHandshake: DoctorCheck = {+ dependsOn: ['credentials.validity', 'endpoints.resolution'],+ group: 'device',+ id: 'device.gateway',+ network: true,+ profiles: ['connect'],+ run: async (ctx): Promise<CheckOutcome> => {+ const credential = await probeCredential(ctx);+ if (!credential.token || !credential.userId)+ return {+ detail: 'No usable credential to authenticate the gateway with.',+ fix: `Run '${CLI_PRIMARY_BIN} login'.`,+ status: 'fail',+ };++ const { gatewayUrl } = resolveEndpoints();+ // The URL is used verbatim to connect and redacted everywhere it is shown.+ const shownUrl = redactUrlCredentials(gatewayUrl);+ const evidence = { gatewayUrl: shownUrl, tokenType: credential.tokenType };++ const outcome = await new Promise<CheckOutcome>((resolve) => {+ const client = new GatewayClient({+ autoReconnect: false,+ gatewayUrl,+ serverUrl: credential.serverUrl,+ token: credential.token!,+ tokenType: credential.tokenType,+ userId: credential.userId!,+ });++ const settle = (result: CheckOutcome) => {+ clearTimeout(timer);+ client.disconnect();+ resolve(result);+ };++ const timer = setTimeout(+ () =>+ settle({+ detail: `${shownUrl} did not complete a handshake within ${ctx.options.timeoutMs}ms.`,+ evidence,+ fix: 'Check egress to the gateway host (WebSocket upgrades are what proxies drop first).',+ status: 'fail',+ }),+ ctx.options.timeoutMs,+ );++ // An EventEmitter throws on an unhandled `error`, and a socket failure+ // (DNS, refused, TLS) arrives there β not through `connect()`'s promise.+ // Without this listener a network problem crashes the whole report.+ client.on('error', (error: Error) =>+ settle({+ detail: `Could not reach ${shownUrl}: ${redactUrlsInMessage(error.message)}.`,+ evidence,+ fix: 'Check the gateway URL and this machineβs egress.',+ status: 'fail',+ }),+ );+ client.on('connected', () =>+ settle({ detail: `Authenticated to ${shownUrl}.`, evidence, status: 'ok' }),+ );+ client.on('auth_failed', (reason: string) =>+ settle({+ detail: `${shownUrl} rejected the credential: ${reason}.`,+ evidence,+ fix: 'The gateway and the server must trust the same issuer β check the gateway URL matches this server.',+ status: 'fail',+ }),+ );+ client.on('auth_expired', () =>+ settle({+ detail: `${shownUrl} reports the credential expired.`,+ evidence,+ fix: `Run '${CLI_PRIMARY_BIN} login' again.`,+ status: 'fail',+ }),+ );+ client.on('disconnected', () =>+ settle({+ detail: `${shownUrl} closed the connection before it was established.`,+ evidence,+ fix: 'Usually a gateway URL that belongs to a different deployment than the server.',+ status: 'fail',+ }),+ );++ void client.connect().catch((error: unknown) =>+ settle({+ detail: `Could not reach ${shownUrl}: ${redactUrlsInMessage(error instanceof Error ? error.message : String(error))}.`,+ evidence,+ fix: 'Check the gateway URL and this machineβs egress.',+ status: 'fail',+ }),+ );+ });++ return outcome;+ },+ title: 'gateway handshake',+};++/** Whether the server agrees this machine is an online device right now. */+const registration: DoctorCheck = {+ dependsOn: ['server.identity'],+ group: 'device',+ id: 'device.registration',+ network: true,+ profiles: ['connect'],+ run: async (ctx): Promise<CheckOutcome> => {+ const devices = await probeDevices(ctx);+ const localDeviceId = resolveLocalDeviceId();+ const online = devices.filter((device) => device?.online);+ const evidence = {+ localDeviceId,+ online: online.map((device) => device.deviceId),+ total: devices.length,+ };++ if (!localDeviceId)+ return {+ detail: `${online.length} device(s) online for this account, but this machine is not one of them.`,+ evidence,+ fix: `Run '${CLI_PRIMARY_BIN} connect' here to make it reachable.`,+ status: online.length > 0 ? 'warn' : 'fail',+ };++ const local = devices.find((device) => device?.deviceId === localDeviceId);+ if (!local)+ return {+ detail: `This machine's device id ${localDeviceId} is not registered on the server.`,+ evidence,+ fix: `Reconnect with '${CLI_PRIMARY_BIN} connect'.`,+ status: 'fail',+ };++ if (!local.online)+ return {+ detail: `Device ${localDeviceId} is registered but offline.`,+ evidence,+ fix: `Reconnect with '${CLI_PRIMARY_BIN} connect'.`,+ status: 'fail',+ };++ return {+ detail: `Device ${localDeviceId} is online (${online.length} online in total).`,+ evidence,+ status: 'ok',+ };+ },+ title: 'device registration',+};++export const deviceChecks: readonly DoctorCheck[] = [daemon, gatewayHandshake, registration];diff --git a/apps/cli/src/doctor/checks/endpoints.test.ts b/apps/cli/src/doctor/checks/endpoints.test.tsnew file mode 100644index 00000000000..4810e55bff3--- /dev/null+++ b/apps/cli/src/doctor/checks/endpoints.test.ts@@ -0,0 +1,132 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { makeContext, runCheck } from '../testUtils';+import { endpointChecks } from './endpoints';++const settings = vi.hoisted(() => ({ value: null as any }));++vi.mock('../../settings', () => ({+ loadSettings: () => settings.value,+ normalizeUrl: (url?: string) => (url ? url.replace(/\/$/, '') : undefined),+ resolveAgentGatewayUrl: () => process.env.AGENT_GATEWAY_URL || 'wss://agent-gateway.lobehub.com',+ resolveServerUrl: () => process.env.LOBEHUB_SERVER || 'https://app.lobehub.com',+}));++vi.mock('../../constants/urls', () => ({+ OFFICIAL_AGENT_GATEWAY_URL: 'wss://agent-gateway.lobehub.com',+ OFFICIAL_GATEWAY_URL: 'wss://gateway.lobehub.com',+ OFFICIAL_SERVER_URL: 'https://app.lobehub.com',+}));++describe('endpoints.resolution', () => {+ beforeEach(() => {+ settings.value = null;+ delete process.env.LOBEHUB_SERVER;+ delete process.env.AGENT_GATEWAY_URL;+ });++ it('reports each URL with the source it came from', async () => {+ const outcome = await runCheck(endpointChecks, 'endpoints.resolution');++ expect(outcome.status).toBe('ok');+ expect(outcome.evidence).toMatchObject({+ gatewaySource: 'built-in default',+ serverSource: 'built-in default',+ serverUrl: 'https://app.lobehub.com',+ });+ });++ it('warns β never fails β about a self-hosted server on the official device gateway', async () => {+ process.env.LOBEHUB_SERVER = 'https://lobe.internal';++ const outcome = await runCheck(endpointChecks, 'endpoints.resolution');++ // A failure here would skip every server-side check through the dependency+ // chain, leaving an API-only installation undiagnosable.+ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('device gateway is still the official');+ });++ it('warns when the gateway is on localhost but the server is not', async () => {+ settings.value = { gatewayUrl: 'http://127.0.0.1:8788' };++ const outcome = await runCheck(endpointChecks, 'endpoints.resolution');++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('not on the same side of localhost');+ });++ it('warns when a self-hosted server still streams agents from the official gateway', async () => {+ process.env.LOBEHUB_SERVER = 'https://lobe.internal';+ settings.value = { gatewayUrl: 'wss://gateway.internal' };++ const outcome = await runCheck(endpointChecks, 'endpoints.resolution');++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('agent streaming');+ });+});++describe('endpoints.tls', () => {+ beforeEach(() => {+ delete process.env.NODE_EXTRA_CA_CERTS;+ delete process.env.HTTPS_PROXY;+ });++ it('fails when NODE_EXTRA_CA_CERTS points at a missing file', async () => {+ process.env.NODE_EXTRA_CA_CERTS = '/nope/missing-ca.pem';++ const outcome = await runCheck(endpointChecks, 'endpoints.tls');++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('does not exist');+ });++ it('reports a proxy without treating it as a problem', async () => {+ process.env.HTTPS_PROXY = 'http://proxy.internal:3128';++ const outcome = await runCheck(endpointChecks, 'endpoints.tls');++ expect(outcome.status).toBe('ok');+ expect(outcome.detail).toContain('proxy via HTTPS_PROXY');+ });++ it('strips the credentials out of an authenticated proxy URL', async () => {+ process.env.HTTPS_PROXY = 'http://alice:[email protected]:3128';++ const outcome = await runCheck(endpointChecks, 'endpoints.tls');+ const serialized = JSON.stringify(outcome.evidence);++ expect(serialized).not.toContain('hunter2');+ expect(serialized).not.toContain('alice');+ expect(serialized).toContain('proxy.internal:3128');+ });+});++describe('endpoints.reachable', () => {+ it('turns a DNS failure into a DNS-specific next step', async () => {+ const fetchSpy = vi+ .spyOn(globalThis, 'fetch')+ .mockRejectedValue(new Error('getaddrinfo ENOTFOUND lobe.internal'));++ const outcome = await runCheck(endpointChecks, 'endpoints.reachable', makeContext());++ expect(outcome.status).toBe('fail');+ expect(outcome.fix).toContain('DNS');+ fetchSpy.mockRestore();+ });++ it('flags a 5xx as a server problem rather than a CLI one', async () => {+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({+ headers: new Headers(),+ json: async () => ({}),+ status: 503,+ } as unknown as Response);++ const outcome = await runCheck(endpointChecks, 'endpoints.reachable', makeContext());++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('503');+ fetchSpy.mockRestore();+ });+});diff --git a/apps/cli/src/doctor/checks/endpoints.ts b/apps/cli/src/doctor/checks/endpoints.tsnew file mode 100644index 00000000000..8dc7ceeb65e--- /dev/null+++ b/apps/cli/src/doctor/checks/endpoints.ts@@ -0,0 +1,248 @@+import fs from 'node:fs';++import {+ OFFICIAL_AGENT_GATEWAY_URL,+ OFFICIAL_GATEWAY_URL,+ OFFICIAL_SERVER_URL,+} from '../../constants/urls';+import {+ loadSettings,+ normalizeUrl,+ resolveAgentGatewayUrl,+ resolveServerUrl,+} from '../../settings';+import { probeServerVersion } from '../probes';+import { redactUrlCredentials } from '../redact';+import type { CheckOutcome, DoctorCheck } from '../types';++export interface ResolvedEndpoints {+ agentGatewaySource: string;+ agentGatewayUrl?: string;+ gatewaySource: string;+ gatewayUrl: string;+ serverSource: string;+ serverUrl: string;+}++/**+ * The three URLs the CLI talks to, each with the reason it has that value.+ *+ * They do not share a resolution rule β `LOBEHUB_SERVER` and+ * `AGENT_GATEWAY_URL` exist but there is no env var for the device gateway,+ * and `settings.json` is deleted whenever every URL is back to default. So+ * "my config looks right but the CLI behaves like it isn't" has three separate+ * causes, and printing the winner plus its source is what tells them apart.+ */+export function resolveEndpoints(): ResolvedEndpoints {+ const settings = loadSettings();+ const serverUrl = resolveServerUrl();+ const agentGatewayUrl = resolveAgentGatewayUrl();++ return {+ agentGatewaySource: process.env.AGENT_GATEWAY_URL+ ? 'AGENT_GATEWAY_URL'+ : settings?.agentGatewayUrl+ ? 'settings.json'+ : 'built-in default',+ agentGatewayUrl,+ gatewaySource: settings?.gatewayUrl ? 'settings.json' : 'built-in default',+ gatewayUrl: normalizeUrl(settings?.gatewayUrl) || OFFICIAL_GATEWAY_URL,+ serverSource: process.env.LOBEHUB_SERVER+ ? 'LOBEHUB_SERVER'+ : settings?.serverUrl+ ? 'settings.json'+ : 'built-in default',+ serverUrl,+ };+}++const endpointResolution: DoctorCheck = {+ group: 'endpoints',+ id: 'endpoints.resolution',+ profiles: ['core'],+ run: (): CheckOutcome => {+ const endpoints = resolveEndpoints();+ // Everything below this line goes into the report, so it carries the+ // redacted forms; `resolveEndpoints()` keeps returning the real URLs for+ // the checks that connect with them.+ const shown = {+ agentGatewayUrl: redactUrlCredentials(endpoints.agentGatewayUrl),+ gatewayUrl: redactUrlCredentials(endpoints.gatewayUrl),+ serverUrl: redactUrlCredentials(endpoints.serverUrl),+ };+ const evidence = { ...endpoints, ...shown };+ const selfHosted = endpoints.serverUrl !== OFFICIAL_SERVER_URL;++ // A self-hosted server with the official device gateway is the trap: only+ // `lh status` complains today, while every other device command connects to+ // a gateway that has never heard of that server.+ //+ // A warning, not a failure: an installation that only uses the HTTP API+ // never needs a device gateway, and failing here would skip every check+ // below through the dependency chain β leaving doctor unable to say+ // anything at all about an otherwise healthy server. The device profile's+ // own handshake check is what fails concretely when it matters.+ if (selfHosted && endpoints.gatewaySource === 'built-in default')+ return {+ detail: `Server is ${shown.serverUrl} but the device gateway is still the official ${OFFICIAL_GATEWAY_URL}, which has never heard of that server.`,+ evidence,+ fix: "Only matters for device commands: pass --gateway <url> to 'lh connect' (it is persisted).",+ status: 'warn',+ };++ // A gateway that only exists on this machine cannot be dispatched to by a+ // remote server (and vice versa). Left over from local gateway work, this+ // shows up later as an opaque "credential rejected" handshake failure.+ if (isLoopback(endpoints.gatewayUrl) !== isLoopback(endpoints.serverUrl))+ return {+ detail: `Server ${shown.serverUrl} and device gateway ${shown.gatewayUrl} are not on the same side of localhost.`,+ evidence,+ fix: isLoopback(endpoints.gatewayUrl)+ ? "Drop the local gateway: 'lh connect --gateway <the server's gateway>'."+ : 'Point --gateway at the gateway that belongs to this server.',+ status: 'warn',+ };++ if (selfHosted && endpoints.agentGatewayUrl === OFFICIAL_AGENT_GATEWAY_URL)+ return {+ detail: `Server is ${shown.serverUrl} but agent streaming still points at the official agent gateway.`,+ evidence,+ fix: 'Set AGENT_GATEWAY_URL to your own agent gateway, or run agent commands with --sse.',+ status: 'warn',+ };++ return {+ detail: `server ${shown.serverUrl} (${endpoints.serverSource}), device gateway ${shown.gatewayUrl} (${endpoints.gatewaySource}).`,+ evidence,+ status: 'ok',+ };+ },+ title: 'endpoint resolution',+};++/**+ * Nothing here is wrong on its own β but a proxy in front of the CLI, or a CA+ * bundle pointed at a file that doesn't exist, turns every later network check+ * into an unexplained TLS error.+ */+const tlsAndProxy: DoctorCheck = {+ group: 'endpoints',+ id: 'endpoints.tls',+ profiles: ['core'],+ run: (): CheckOutcome => {+ const caFile = process.env.NODE_EXTRA_CA_CERTS;+ const proxies = Object.fromEntries(+ (['HTTPS_PROXY', 'HTTP_PROXY', 'ALL_PROXY', 'NO_PROXY'] as const)+ .map(+ (name) =>+ [+ name,+ redactUrlCredentials(process.env[name] ?? process.env[name.toLowerCase()]),+ ] as const,+ )+ .filter(([, value]) => Boolean(value)),+ );+ const evidence = { caFile, proxies };++ if (caFile && !fs.existsSync(caFile))+ return {+ detail: `NODE_EXTRA_CA_CERTS points at ${caFile}, which does not exist.`,+ evidence,+ fix: 'Fix the path or unset NODE_EXTRA_CA_CERTS β node ignores it silently and every TLS handshake then fails on its own terms.',+ status: 'fail',+ };++ const notes = [+ caFile ? `extra CA ${caFile}` : undefined,+ Object.keys(proxies).length > 0 ? `proxy via ${Object.keys(proxies).join(', ')}` : undefined,+ ].filter(Boolean);++ return {+ detail: notes.length > 0 ? notes.join(', ') + '.' : 'No proxy or custom CA in play.',+ evidence,+ status: 'ok',+ };+ },+ title: 'tls & proxy',+};++const serverReachable: DoctorCheck = {+ dependsOn: ['endpoints.resolution'],+ group: 'endpoints',+ id: 'endpoints.reachable',+ network: true,+ profiles: ['core'],+ run: async (ctx): Promise<CheckOutcome> => {+ let probe;+ try {+ probe = await probeServerVersion(ctx);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ const serverUrl = redactUrlCredentials(resolveServerUrl());+ return {+ detail: `${serverUrl} is unreachable: ${message}.`,+ evidence: { error: message, serverUrl },+ fix: classifyNetworkError(message),+ status: 'fail',+ };+ }++ const evidence = {+ latencyMs: probe.latencyMs,+ serverUrl: probe.serverUrl,+ serverVersion: probe.version,+ statusCode: probe.statusCode,+ };++ if (probe.statusCode >= 500)+ return {+ detail: `${evidence.serverUrl} answered ${probe.statusCode}.`,+ evidence,+ fix: 'The server is up but unhealthy β check its logs before debugging the CLI.',+ status: 'fail',+ };++ if (probe.statusCode >= 400)+ return {+ detail: `${evidence.serverUrl}/api/version answered ${probe.statusCode}.`,+ evidence,+ fix: 'Something in front of the server (WAF, auth proxy) is intercepting requests.',+ status: 'warn',+ };++ return {+ detail: `${evidence.serverUrl} responded in ${probe.latencyMs}ms${probe.version ? `, running ${probe.version}` : ''}.`,+ evidence,+ status: 'ok',+ };+ },+ title: 'server reachable',+};++const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '::1', '0.0.0.0']);++function isLoopback(url: string): boolean {+ try {+ return LOOPBACK_HOSTS.has(new URL(url).hostname.replaceAll(/^\[|\]$/g, ''));+ } catch {+ return false;+ }+}++function classifyNetworkError(message: string): string {+ if (/ENOTFOUND|EAI_AGAIN|getaddrinfo/i.test(message))+ return 'DNS cannot resolve the host β check the server URL and your resolver.';+ if (/ECONNREFUSED/i.test(message))+ return 'Nothing is listening there β check the port and that the server is running.';+ if (/certificate|SSL|TLS|self.signed/i.test(message))+ return 'TLS failed β set NODE_EXTRA_CA_CERTS to the CA bundle your network requires.';+ if (/timed out|timeout|abort/i.test(message))+ return 'The request never came back β a firewall or egress allowlist is the usual cause.';+ return 'Check the server URL and this machineβs network access.';+}++export const endpointChecks: readonly DoctorCheck[] = [+ endpointResolution,+ tlsAndProxy,+ serverReachable,+];diff --git a/apps/cli/src/doctor/checks/execution.test.ts b/apps/cli/src/doctor/checks/execution.test.tsnew file mode 100644index 00000000000..35eecd7e7c9--- /dev/null+++ b/apps/cli/src/doctor/checks/execution.test.ts@@ -0,0 +1,311 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { makeContext, runCheck } from '../testUtils';+import { executionChecks } from './execution';++const state = vi.hoisted(() => ({+ agentConfig: {} as any,+ builtinAgent: null as any,+ globalConfig: {} as any,+ providerDetail: undefined as any,+ providerDetailThrows: false,+ providers: [] as any[],+ started: {} as any,+ statuses: [] as any[],+}));++const heteroDetect = vi.hoisted(() => vi.fn());++vi.mock('@lobechat/heterogeneous-agents/resolveCliCommand', () => ({+ DEFAULT_HETERO_COMMAND: { 'claude-code': 'claude', 'codex': 'codex' },+ detectHeterogeneousCliCommand: heteroDetect,+}));++vi.mock('../probes', () => ({+ probeClient: async () => ({+ agent: {+ getAgentConfigById: {+ query: async ({ agentId }: { agentId: string }) =>+ agentId === 'agt_known' ? state.agentConfig : null,+ },+ getBuiltinAgent: { query: async () => state.builtinAgent },+ },+ aiAgent: {+ execAgent: { mutate: async () => state.started },+ getOperationStatus: { query: async () => state.statuses.shift() ?? null },+ },+ aiProvider: {+ getAiProviderById: {+ query: async () => {+ if (state.providerDetailThrows) throw new Error('nope');+ return state.providerDetail;+ },+ },+ },+ }),+ probeGlobalConfig: async () => state.globalConfig,+ probeProviders: async () => state.providers,+}));++const deepContext = () => makeContext({ agent: 'agt_known', deep: true, timeoutMs: 1000 });++describe('execution.agent', () => {+ beforeEach(() => {+ state.agentConfig = { model: 'glm-5.3-flash', provider: 'lobehub', title: 'Architect' };+ state.builtinAgent = null;+ state.globalConfig = { serverConfig: { aiProvider: { lobehub: { enabled: true } } } };+ state.providers = [];+ state.providerDetail = { id: 'lobehub', keyVaults: { apiKey: 'stored-key' } };+ state.providerDetailThrows = false;+ });++ it('skips itself when no agent was named', async () => {+ const outcome = await runCheck(executionChecks, 'execution.agent', makeContext());++ expect(outcome.status).toBe('skip');+ expect(outcome.skippedBecause).toBe('--agent');+ });++ it('names the env var to set when the agentβs provider is not enabled anywhere', async () => {+ state.agentConfig = { model: 'kimi-k3', provider: 'fireworksai' };++ const outcome = await runCheck(+ executionChecks,+ 'execution.agent',+ makeContext({ agent: 'agt_known' }),+ );++ expect(outcome.status).toBe('fail');+ expect(outcome.fix).toContain('FIREWORKSAI_API_KEY');+ });++ it('passes when the provider has a key on the account', async () => {+ state.providers = [{ enabled: true, id: 'lobehub' }];+ state.globalConfig = { serverConfig: { aiProvider: {} } };++ const outcome = await runCheck(+ executionChecks,+ 'execution.agent',+ makeContext({ agent: 'agt_known' }),+ );++ expect(outcome.status).toBe('ok');+ expect(outcome.detail).toContain('key stored on the account');+ });++ it('fails a provider that is enabled but has an empty key vault', async () => {+ // `getAiProviderList` reports the toggle, not the key β enabling a provider+ // with no key is exactly what makes a run die with InvalidProviderAPIKey.+ state.providers = [{ enabled: true, id: 'lobehub' }];+ state.globalConfig = { serverConfig: { aiProvider: {} } };+ state.providerDetail = { id: 'lobehub', keyVaults: {} };++ const outcome = await runCheck(+ executionChecks,+ 'execution.agent',+ makeContext({ agent: 'agt_known' }),+ );++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('no key stored');+ });++ it('does not fail a local runtime configured with only an endpoint', async () => {+ // Ollama / LM Studio store a baseURL and no secret, and need none.+ state.providers = [{ enabled: true, id: 'lobehub' }];+ state.globalConfig = { serverConfig: { aiProvider: {} } };+ state.providerDetail = { id: 'lobehub', keyVaults: { baseURL: 'http://127.0.0.1:1234/v1' } };++ const outcome = await runCheck(+ executionChecks,+ 'execution.agent',+ makeContext({ agent: 'agt_known' }),+ );++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('endpoint and no key');+ });++ it('does not claim a key exists just because the server enables the provider', async () => {+ // `deepseek` is enabled unconditionally server-side, and server keys are+ // invisible to the CLI β so this may pass, but not as a key verification.+ state.providers = [];+ state.providerDetail = { id: 'lobehub', keyVaults: {} };++ const outcome = await runCheck(+ executionChecks,+ 'execution.agent',+ makeContext({ agent: 'agt_known' }),+ );++ expect(outcome.status).toBe('ok');+ expect(outcome.detail).toContain('reports as enabled');+ expect(outcome.detail).not.toContain('with a key');+ });++ it('says so instead of passing when the key vault cannot be read', async () => {+ // A restricted API key gets the provider back without its `keyVaults`.+ state.providers = [{ enabled: true, id: 'lobehub' }];+ state.globalConfig = { serverConfig: { aiProvider: {} } };+ state.providerDetail = { id: 'lobehub' };++ const outcome = await runCheck(+ executionChecks,+ 'execution.agent',+ makeContext({ agent: 'agt_known' }),+ );++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('not verified');+ });++ it('falls back to a slug lookup when the value is not an id', async () => {+ state.builtinAgent = { id: 'agt_known' };++ const outcome = await runCheck(+ executionChecks,+ 'execution.agent',+ makeContext({ agent: 'inbox' }),+ );++ expect(outcome.status).toBe('ok');+ });++ it('fails when nothing matches', async () => {+ const outcome = await runCheck(+ executionChecks,+ 'execution.agent',+ makeContext({ agent: 'nope' }),+ );++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('No agent matches');+ });++ it('warns when the agent has no model pinned', async () => {+ state.agentConfig = { title: 'Architect' };++ const outcome = await runCheck(+ executionChecks,+ 'execution.agent',+ makeContext({ agent: 'agt_known' }),+ );++ expect(outcome.status).toBe('warn');+ });+});++describe('execution.round-trip', () => {+ beforeEach(() => {+ state.started = { operationId: 'op_1', success: true, topicId: 'tpc_1' };+ state.statuses = [];+ });++ it('waits out the non-terminal states and reports tokens and cost', async () => {+ state.statuses = [+ { currentState: { status: 'idle' }, isCompleted: false },+ {+ currentState: { status: 'done', usage: { llm: { tokens: { total: 54_396 } } } },+ isCompleted: true,+ stats: { totalCost: 0.005_524, totalSteps: 1 },+ },+ ];++ const outcome = await runCheck(executionChecks, 'execution.round-trip', deepContext());++ expect(outcome.status).toBe('ok');+ expect(outcome.detail).toContain('54396 tokens');+ expect(outcome.detail).toContain('$0.0055');+ });++ it('reports the run error rather than the transport', async () => {+ state.statuses = [+ {+ hasError: true,+ recentEvents: [{ data: { errorType: 'InvalidProviderAPIKey' }, type: 'error' }],+ },+ ];++ const outcome = await runCheck(executionChecks, 'execution.round-trip', deepContext());++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('InvalidProviderAPIKey');+ });++ it('surfaces a headless run that still stopped for human input', async () => {+ state.statuses = [{ isCompleted: false, needsHumanInput: true }];++ const outcome = await runCheck(executionChecks, 'execution.round-trip', deepContext());++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('waiting for human input');+ });++ it('does not call a run that disappears mid-flight a success', async () => {+ // Null also means lost state (an expired key, a lost Redis entry), so only+ // `isCompleted` proves the round trip.+ state.statuses = [{ currentState: { status: 'idle' }, isCompleted: false }];++ const outcome = await runCheck(executionChecks, 'execution.round-trip', deepContext());++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('without reporting completion');+ });++ it('does not call a run that was never observed a success', async () => {+ // The server also returns null when there is no state yet; passing on that+ // would make this check incapable of failing.+ state.statuses = [];++ const outcome = await runCheck(executionChecks, 'execution.round-trip', deepContext());++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('nothing was observed to run');+ });++ it('reports the server refusing to start the run', async () => {+ state.started = { error: 'quota exhausted', success: false };++ const outcome = await runCheck(executionChecks, 'execution.round-trip', deepContext());++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('quota exhausted');+ });+});++describe('execution.hetero', () => {+ beforeEach(() => {+ heteroDetect.mockReset();+ });++ it('reports the resolved binaries', async () => {+ heteroDetect.mockImplementation(async (type: string) => ({+ available: true,+ path: `/usr/bin/${type}`,+ version: '1.2.3',+ }));++ const outcome = await runCheck(executionChecks, 'execution.hetero', makeContext());++ expect(outcome.status).toBe('ok');+ expect(outcome.detail).toContain('claude-code 1.2.3');+ });++ it('only fails on a missing agent the caller asked for', async () => {+ heteroDetect.mockImplementation(async (type: string) => ({+ available: type === 'codex',+ error: 'not found',+ path: '/usr/bin/codex',+ }));++ const ambient = await runCheck(executionChecks, 'execution.hetero', makeContext());+ const explicit = await runCheck(+ executionChecks,+ 'execution.hetero',+ makeContext({ hetero: ['claude-code', 'codex'] }),+ );++ expect(ambient.status).toBe('ok');+ expect(explicit.status).toBe('fail');+ });+});diff --git a/apps/cli/src/doctor/checks/execution.ts b/apps/cli/src/doctor/checks/execution.tsnew file mode 100644index 00000000000..381c1488eb4--- /dev/null+++ b/apps/cli/src/doctor/checks/execution.ts@@ -0,0 +1,449 @@+import {+ DEFAULT_HETERO_COMMAND,+ detectHeterogeneousCliCommand,+ type HeterogeneousCliAgentType,+} from '@lobechat/heterogeneous-agents/resolveCliCommand';++import { CLI_PRIMARY_BIN } from '../../constants/identity';+import { probeClient, probeGlobalConfig, probeProviders } from '../probes';+import type { CheckOutcome, DoctorCheck } from '../types';+import { enabledProviders } from './server';++/** External CLI agents worth probing unless the caller names others. */+const DEFAULT_HETERO_TYPES: HeterogeneousCliAgentType[] = ['claude-code', 'codex'];++/**+ * Everything `lh agent run` needs, checked in the order it would fail:+ * the agent exists, its model has a provider, that provider has a key.+ *+ * Without this, a missing key surfaces as `InvalidProviderAPIKey` from inside+ * the run β after the run has already been created, and with no indication+ * whether the key is missing on the account or on the server.+ */+const agentReadiness: DoctorCheck = {+ dependsOn: ['server.identity'],+ group: 'execution',+ id: 'execution.agent',+ network: true,+ profiles: ['agent'],+ run: async (ctx): Promise<CheckOutcome> => {+ const requested = ctx.options.agent;+ if (!requested)+ return {+ detail: 'No agent given; pass --agent <id|slug> to check one.',+ skippedBecause: '--agent',+ status: 'skip',+ };++ const client = await probeClient(ctx);+ const resolved = await resolveAgent(client, requested);+ if (!resolved)+ return {+ detail: `No agent matches "${requested}" in the current scope.`,+ evidence: { requested },+ fix: `List them with '${CLI_PRIMARY_BIN} agent list'.`,+ status: 'fail',+ };++ const { agentId, config } = resolved;+ const provider = config.provider as string | undefined;+ const model = config.model as string | undefined;+ const evidence = { agentId, model, provider, title: config.title ?? config.meta?.title };++ if (!provider || !model)+ return {+ detail: `Agent ${agentId} has no model pinned (provider=${provider ?? 'unset'}, model=${model ?? 'unset'}).`,+ evidence,+ fix: `Set one with '${CLI_PRIMARY_BIN} agent edit ${agentId} --model <model> --provider <provider>'.`,+ status: 'warn',+ };++ const [userProviders, globalConfig] = await Promise.all([+ probeProviders(ctx),+ probeGlobalConfig(ctx).catch(() => undefined),+ ]);+ const serverProviders = ((globalConfig as any)?.serverConfig?.aiProvider ?? {}) as Record<+ string,+ { enabled?: boolean }+ >;+ const enabled = enabledProviders(userProviders, serverProviders);++ // The env var name is the part people get wrong: the server upper-cases the+ // provider's internal id, not its display name.+ const addKey = `Add a key for "${provider}" on the account, or set ${provider.toUpperCase()}_API_KEY on the server.`;++ if (!enabled.includes(provider))+ return {+ detail: `Agent ${agentId} runs ${model} on "${provider}", which is not enabled anywhere.`,+ evidence: { ...evidence, enabled },+ fix: addKey,+ status: 'fail',+ };++ // Enabled is not the same as callable: a provider can be toggled on with an+ // empty key vault, and the run then dies with InvalidProviderAPIKey β the+ // exact failure this check exists to pre-empt. So read the key vault of+ // this one provider rather than trusting the toggle.+ const credential = await readProviderCredential(+ client,+ provider,+ Boolean(serverProviders[provider]?.enabled),+ );+ const withCredential = { ...evidence, credentialSource: credential.source };++ if (credential.source === 'none')+ return {+ detail: `Agent ${agentId} runs ${model} on "${provider}", which is enabled but has no key stored.`,+ evidence: withCredential,+ fix: addKey,+ status: 'fail',+ };++ if (credential.source === 'endpoint-only')+ return {+ detail: `Agent ${agentId} runs ${model} on ${provider}, configured with an endpoint and no key β normal for a local runtime, unverifiable from here.`,+ evidence: withCredential,+ fix: `If "${provider}" does need a key, add one; otherwise check the endpoint is reachable from the server.`,+ status: 'warn',+ };++ if (credential.source === 'unknown')+ return {+ detail: `Agent ${agentId} runs ${model} on ${provider}, which is enabled β but this credential cannot read key vaults, so the key itself was not verified.`,+ evidence: withCredential,+ fix: 'Re-run with a full-access login to confirm the provider key.',+ status: 'warn',+ };++ if (credential.source === 'server-enabled')+ return {+ // Deliberately not a claim that a key exists: server-side keys are+ // invisible here, and some providers are enabled regardless of one.+ detail: `Agent ${agentId} runs ${model} on ${provider}, which the server reports as enabled (server-side keys are not visible to the CLI).`,+ evidence: withCredential,+ status: 'ok',+ };++ return {+ detail: `Agent ${agentId} runs ${model} on ${provider}, with a key stored on the account.`,+ evidence: withCredential,+ status: 'ok',+ };+ },+ title: 'agent readiness',+};++interface ResolvedAgent {+ agentId: string;+ config: Record<string, any>;+}++/**+ * Accept whatever the user typed: agent ids carry more than one prefix in the+ * wild (`agt_β¦` from the id generator, `agent_β¦` for system agents), so the id+ * lookup is attempted first and a miss falls back to a slug.+ */+async function resolveAgent(client: any, requested: string): Promise<ResolvedAgent | undefined> {+ const direct = await readAgentConfig(client, requested);+ if (direct) return { agentId: requested, config: direct };++ const bySlug = await client.agent.getBuiltinAgent+ .query({ slug: requested })+ .catch(() => undefined);+ const agentId: string | undefined = bySlug?.id || bySlug?.agentId;+ if (!agentId) return undefined;++ const config = await readAgentConfig(client, agentId);+ return config ? { agentId, config } : undefined;+}++/** Key-vault fields that are an address rather than a credential. */+const NON_SECRET_VAULT_FIELDS = new Set(['baseURL', 'endpoint', 'apiVersion']);++export type CredentialSource = 'account' | 'endpoint-only' | 'server-enabled' | 'none' | 'unknown';++/**+ * Where a provider's credential comes from β without ever reading its value.+ *+ * Four answers, because the CLI genuinely cannot reach the same certainty in+ * every case:+ * - `account`: a secret is stored in this account's key vault.+ * - `endpoint-only`: a base URL and nothing else, which is the normal shape+ * for a local runtime (Ollama, LM Studio) that needs no key at all.+ * - `server-enabled`: the server reports the provider enabled. That is NOT+ * proof of a key β `deepseek` is enabled unconditionally in the server's+ * own config, and `ENABLED_OPENAI` / `ENABLED_OLLAMA` default to true β and+ * server-side keys are invisible to the CLI either way.+ * - `unknown`: a restricted API key gets the provider back with no key vault+ * at all, so nothing can be concluded.+ */+async function readProviderCredential(+ client: any,+ provider: string,+ enabledOnServer: boolean,+): Promise<{ source: CredentialSource }> {+ let detail: Record<string, any> | undefined;+ try {+ detail = (await client.aiProvider.getAiProviderById.query({ id: provider })) ?? undefined;+ } catch {+ return { source: enabledOnServer ? 'server-enabled' : 'unknown' };+ }++ const vault = (detail?.keyVaults ?? undefined) as Record<string, unknown> | undefined;+ if (vault) {+ const entries = Object.entries(vault).filter(+ ([, value]) => typeof value === 'string' && value.length > 0,+ );+ if (entries.some(([key]) => !NON_SECRET_VAULT_FIELDS.has(key))) return { source: 'account' };+ if (entries.length > 0) return { source: 'endpoint-only' };+ }++ if (enabledOnServer) return { source: 'server-enabled' };++ // A caller that could read the vault and found it empty knows there is no+ // key; a restricted one cannot tell that apart from not being allowed to look.+ return { source: vault ? 'none' : 'unknown' };+}++async function readAgentConfig(+ client: any,+ agentId: string,+): Promise<Record<string, any> | undefined> {+ try {+ const config = await client.agent.getAgentConfigById.query({ agentId });+ return config ?? undefined;+ } catch {+ return undefined;+ }+}++/**+ * External CLI agents (`lh hetero exec`) fail at spawn time with a bare ENOENT+ * when a global install is stale or a broken shim shadows PATH. The resolver+ * used here is the same one the spawn site uses, so a pass means the spawn+ * resolves to the same binary.+ */+const heteroBinaries: DoctorCheck = {+ group: 'execution',+ id: 'execution.hetero',+ profiles: ['hetero'],+ run: async (ctx): Promise<CheckOutcome> => {+ const requested = (+ ctx.options.hetero?.length ? ctx.options.hetero : DEFAULT_HETERO_TYPES+ ) as HeterogeneousCliAgentType[];+ const explicit = Boolean(ctx.options.hetero?.length);++ const statuses = await mapLimit(requested, 4, async (type) => {+ const command = DEFAULT_HETERO_COMMAND[type];+ if (!command) return { available: false, error: 'unknown agent type', type };+ const status = await detectHeterogeneousCliCommand(type, command);+ return {+ available: status.available,+ error: status.error,+ path: status.path,+ type,+ version: status.version,+ };+ });++ const available = statuses.filter((status) => status.available);+ const missing = statuses.filter((status) => !status.available);+ const evidence = Object.fromEntries(+ statuses.map((status) => [+ status.type,+ status.available+ ? `${status.version ?? 'installed'} at ${status.path}`+ : (status.error ?? 'not found'),+ ]),+ );++ if (available.length === 0)+ return {+ detail: `None of ${requested.join(', ')} resolve to a runnable binary.`,+ evidence,+ fix: 'Install at least one external agent CLI, or pass --command to point at yours.',+ status: explicit ? 'fail' : 'warn',+ };++ if (missing.length > 0)+ return {+ detail: `${available.map((status) => `${status.type} ${status.version ?? ''}`.trim()).join(', ')} available; ${missing.map((status) => status.type).join(', ')} missing.`,+ evidence,+ fix: explicit ? 'Install the missing ones, or drop them from --hetero.' : undefined,+ status: explicit ? 'fail' : 'ok',+ };++ return {+ detail: `${available.map((status) => `${status.type} ${status.version ?? ''}`.trim()).join(', ')} available.`,+ evidence,+ status: 'ok',+ };+ },+ title: 'external agent CLIs',+};++/**+ * The only check that proves the chain rather than inspecting it: start a real+ * run and wait for the server to finish it.+ *+ * Gated behind `--deep` and an explicit `--agent` because it costs tokens and+ * leaves a topic behind β a diagnostic must not spend money by default.+ */+/** A model needs minutes, not the ten seconds a health probe gets. */+const roundTripBudget = (options: { timeoutMs: number }): number =>+ Math.max(options.timeoutMs, 300_000);++const roundTrip: DoctorCheck = {+ budgetMs: roundTripBudget,+ deep: true,+ dependsOn: ['execution.agent'],+ group: 'execution',+ id: 'execution.round-trip',+ network: true,+ profiles: ['agent'],+ run: async (ctx): Promise<CheckOutcome> => {+ const requested = ctx.options.agent;+ if (!requested)+ return {+ detail: 'No agent given; pass --agent <id|slug>.',+ skippedBecause: '--agent',+ status: 'skip',+ };++ const client = await probeClient(ctx);+ const resolved = await resolveAgent(client, requested);+ if (!resolved) return { detail: `No agent matches "${requested}".`, status: 'fail' };+ const { agentId } = resolved;++ const startedAt = Date.now();+ const started = (await client.aiAgent.execAgent.mutate({+ agentId,+ prompt: 'Reply with exactly: DOCTOR_OK',+ trigger: 'cli',+ userInterventionConfig: { approvalMode: 'headless' },+ } as any)) as Record<string, any>;++ if (!started?.success || !started.operationId)+ return {+ detail: `The server refused to start a run: ${started?.error ?? started?.message ?? 'unknown error'}.`,+ evidence: { agentId },+ fix: 'This is the same call `lh agent run` makes; the error above is the serverβs own.',+ status: 'fail',+ };++ const operationId = started.operationId as string;+ // Leave the runner's own timeout a margin, so a slow run is reported by+ // this check (with the operation id to chase) instead of as a bare timeout.+ const deadline = Date.now() + roundTripBudget(ctx.options) - 5000;++ // Poll immediately, then every couple of seconds: a fast model can be done+ // before the first interval would have elapsed.+ let waitMs = 0;+ // "No longer tracked" only means finished if we saw it running first. On+ // the very first poll it means nothing was observed at all, and calling+ // that a pass would make this check unable to fail.+ let observedRunning = false;+ while (Date.now() < deadline) {+ if (waitMs) await delay(waitMs);+ waitMs = 2000;+ const state = (await client.aiAgent.getOperationStatus.query({+ operationId,+ } as any)) as Record<string, any> | null;+ const elapsedSeconds = Math.round((Date.now() - startedAt) / 1000);+ const evidence = {+ agentId,+ cost: state?.stats?.totalCost,+ elapsedMs: Date.now() - startedAt,+ operationId,+ steps: state?.stats?.totalSteps,+ tokens: state?.currentState?.usage?.llm?.tokens?.total,+ topicId: started.topicId,+ };++ if (!state) {+ // Null is not a completion signal: the server also answers null when+ // the run's state or metadata is gone (an expired key, a lost Redis+ // entry). Only `isCompleted` proves the round trip; a disappearance is+ // reported as inconclusive either way.+ return {+ detail: observedRunning+ ? `Run ${operationId} stopped being tracked after ${elapsedSeconds}s without reporting completion.`+ : `The server returned no state for run ${operationId}, so nothing was observed to run.`,+ evidence,+ fix: `Check it directly with '${CLI_PRIMARY_BIN} agent status ${operationId}'.`,+ status: 'warn',+ };+ }++ observedRunning = true;++ if (state.hasError)+ return {+ detail: `The run failed after ${elapsedSeconds}s: ${describeRunError(state)}.`,+ evidence,+ fix: `Inspect it with '${CLI_PRIMARY_BIN} trace op inspect ${operationId}'.`,+ status: 'fail',+ };++ if (state.needsHumanInput)+ return {+ detail: `The run is waiting for human input after ${elapsedSeconds}s, despite headless mode.`,+ evidence,+ fix: `Answer it in the app, or inspect it with '${CLI_PRIMARY_BIN} agent status ${operationId}'.`,+ status: 'warn',+ };++ if (state.isCompleted)+ return {+ detail: `Round trip completed in ${elapsedSeconds}s β ${evidence.tokens ?? 0} tokens, $${(evidence.cost ?? 0).toFixed(4)} (operation ${operationId}).`,+ evidence,+ status: 'ok',+ };+ }++ return {+ detail: `The run did not finish within the budget (operation ${operationId}).`,+ evidence: { agentId, operationId },+ fix: `It may still be running β check '${CLI_PRIMARY_BIN} agent status ${operationId}'. Raise --timeout for a slower model.`,+ status: 'warn',+ };+ },+ title: 'agent round trip',+};++function describeRunError(state: Record<string, any>): string {+ const event = (state.recentEvents as { data?: any; type?: string }[] | undefined)?.findLast(+ (candidate) => candidate?.type === 'error',+ );+ return (+ event?.data?.errorType ||+ event?.data?.error ||+ event?.data?.message ||+ state.currentState?.error ||+ 'no error detail reported'+ );+}++const delay = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));++/** Bounded fan-out: probing every known agent type at once spawns a process storm. */+async function mapLimit<T, R>(+ items: readonly T[],+ limit: number,+ run: (item: T) => Promise<R>,+): Promise<R[]> {+ const results: R[] = Array.from({ length: items.length });+ let cursor = 0;++ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {+ while (cursor < items.length) {+ const index = cursor++;+ results[index] = await run(items[index]);+ }+ });++ await Promise.all(workers);+ return results;+}++export const executionChecks: readonly DoctorCheck[] = [agentReadiness, heteroBinaries, roundTrip];diff --git a/apps/cli/src/doctor/checks/runtime.test.ts b/apps/cli/src/doctor/checks/runtime.test.tsnew file mode 100644index 00000000000..629ebccabe3--- /dev/null+++ b/apps/cli/src/doctor/checks/runtime.test.ts@@ -0,0 +1,178 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { findCheck, makeContext, runCheck } from '../testUtils';+import { runtimeChecks } from './runtime';++const home = vi.hoisted(() => ({ dir: '' }));+const pkg = vi.hoisted(() => ({ engine: '>=22.15' as string | undefined }));+const zlib = vi.hoisted(() => ({ hasZstd: true }));+const latest = vi.hoisted(() => ({ value: '0.0.55' as string | Error }));++vi.mock('node:os', async (importOriginal) => {+ const actual = await importOriginal<typeof os>();+ return { ...actual, default: { ...actual, homedir: () => home.dir }, homedir: () => home.dir };+});++// Getters, not values: the factory runs once, but each test flips `hasZstd`.+vi.mock('node:zlib', () => ({+ default: {+ get zstdDecompress() {+ return zlib.hasZstd ? () => {} : undefined;+ },+ },+}));++vi.mock('../../pkg', () => ({+ get cliNodeEngine() {+ return pkg.engine;+ },+ cliPackageName: '@lobehub/cli',+ cliVersion: '0.0.55',+}));++vi.mock('../../commands/update', () => ({+ detectPackageManager: () => 'npm',+ fetchLatestVersion: async () => {+ if (latest.value instanceof Error) throw latest.value;+ return latest.value;+ },+ isNewerVersion: (a: string, b: string) => a !== b,+}));++vi.mock('../../auth/source', () => ({+ credentialsPath: () => path.join(home.dir, '.lobehub', 'credentials.json'),+}));+vi.mock('../../constants/identity', () => ({ resolveCliDirName: () => '.lobehub' }));++describe('runtime.node', () => {+ beforeEach(() => {+ pkg.engine = '>=22.15';+ zlib.hasZstd = true;+ });++ it('fails a node older than the CLI can run on', async () => {+ pkg.engine = '>=999.0.0';++ const outcome = await runCheck(runtimeChecks, 'runtime.node');++ expect(outcome.status).toBe('fail');+ expect(outcome.fix).toContain('nvm install 22');+ });++ it('fails a node that satisfies the range but lacks the zlib API the CLI imports', async () => {+ zlib.hasZstd = false;++ const outcome = await runCheck(runtimeChecks, 'runtime.node');++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('zlib.zstdDecompress');+ });++ it('passes on a supported node', async () => {+ const outcome = await runCheck(runtimeChecks, 'runtime.node');++ expect(outcome.status).toBe('ok');+ expect(outcome.evidence).toMatchObject({ hasZstd: true });+ });+});++describe('runtime.home', () => {+ beforeEach(() => {+ home.dir = fs.mkdtempSync(path.join(os.tmpdir(), 'doctor-home-'));+ });++ afterEach(() => {+ fs.rmSync(home.dir, { force: true, recursive: true });+ });++ it('accepts a home that does not exist yet', async () => {+ const outcome = await runCheck(runtimeChecks, 'runtime.home');++ expect(outcome.status).toBe('ok');+ expect(outcome.detail).toContain('does not exist yet');+ });++ it('fails an unparseable settings.json and moves it aside under --fix', async () => {+ const dir = path.join(home.dir, '.lobehub');+ fs.mkdirSync(dir, { mode: 0o700 });+ fs.writeFileSync(path.join(dir, 'settings.json'), '{ not json', { mode: 0o600 });++ const check = findCheck(runtimeChecks, 'runtime.home');+ const outcome = await runCheck(runtimeChecks, 'runtime.home');+ expect(outcome.status).toBe('fail');++ await check.repair!(makeContext({ fix: true }), {+ ...outcome,+ durationMs: 0,+ group: 'runtime',+ id: 'runtime.home',+ title: '',+ });++ expect(fs.existsSync(path.join(dir, 'settings.json'))).toBe(false);+ expect(fs.existsSync(path.join(dir, 'settings.json.bak'))).toBe(true);+ });++ it('does not offer to move aside a settings file it merely cannot read', async () => {+ // Unreadable is not corrupt β the content may be perfectly valid.+ if (process.getuid?.() === 0) return; // root reads mode-000 files+ const dir = path.join(home.dir, '.lobehub');+ fs.mkdirSync(dir, { mode: 0o700 });+ fs.writeFileSync(path.join(dir, 'settings.json'), '{"serverUrl":"https://lobe.internal"}', {+ mode: 0o000,+ });++ const outcome = await runCheck(runtimeChecks, 'runtime.home');++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('cannot be read');+ expect(outcome.evidence?.repairable).toBeUndefined();+ fs.chmodSync(path.join(dir, 'settings.json'), 0o600);+ });++ it('warns about a world-readable config directory', async () => {+ fs.mkdirSync(path.join(home.dir, '.lobehub'), { mode: 0o755 });++ const outcome = await runCheck(runtimeChecks, 'runtime.home');++ expect(outcome.status).toBe('warn');+ expect(outcome.fix).toContain('chmod go-rwx');+ });+});++describe('runtime.latest budget', () => {+ it('always gives the runner more time than its own registry deadline', () => {+ // Otherwise a stalled registry becomes a runner failure instead of a warning.+ const check = findCheck(runtimeChecks, 'runtime.latest');+ for (const timeoutMs of [50, 1000, 300_000])+ expect(check.budgetMs!(makeContext({ timeoutMs }).options)).toBeGreaterThan(timeoutMs);+ });+});++describe('runtime.latest', () => {+ beforeEach(() => {+ home.dir = os.tmpdir();+ });++ it('warns about a newer published version without failing', async () => {+ latest.value = '0.0.99';++ const outcome = await runCheck(runtimeChecks, 'runtime.latest');++ expect(outcome.status).toBe('warn');+ expect(outcome.fix).toBe('lh update');+ });++ it('degrades to a warning when the registry is unreachable', async () => {+ latest.value = new Error('ENOTFOUND registry.npmjs.org');++ const outcome = await runCheck(runtimeChecks, 'runtime.latest');++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('Could not reach the npm registry');+ });+});diff --git a/apps/cli/src/doctor/checks/runtime.ts b/apps/cli/src/doctor/checks/runtime.tsnew file mode 100644index 00000000000..8972c03ec71--- /dev/null+++ b/apps/cli/src/doctor/checks/runtime.ts@@ -0,0 +1,387 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import zlib from 'node:zlib';++import semver from 'semver';+import { xSync } from 'tinyexec';++import { credentialsPath } from '../../auth/source';+import { detectPackageManager, fetchLatestVersion, isNewerVersion } from '../../commands/update';+import { resolveCliDirName } from '../../constants/identity';+import { cliNodeEngine, cliPackageName, cliVersion } from '../../pkg';+import type { CheckOutcome, DoctorCheck } from '../types';++const configDir = (): string => path.join(os.homedir(), resolveCliDirName());++const bytesToGb = (bytes: number): string => `${(bytes / 1024 ** 3).toFixed(1)} GB`;++/**+ * The runtime the CLI is actually running on.+ *+ * Known gap: this cannot fire for the case it most wants to catch. The bundle+ * imports `zstdDecompress` from `node:zlib` (node >= 22.15) and ESM resolves+ * every import before the first line runs, so on an older runtime `lh` dies+ * with "no export named 'zstdDecompress'" β pointing at node:zlib rather than+ * at the node it is running on β and no in-process check is ever reached.+ * Closing that needs a change to how the CLI is launched, which belongs in its+ * own change rather than riding along with a diagnostic command. Until then+ * this check covers the case where the bundle loads but the runtime is still+ * below the floor.+ */+const nodeVersion: DoctorCheck = {+ group: 'runtime',+ id: 'runtime.node',+ profiles: ['core'],+ run: (): CheckOutcome => {+ const required = cliNodeEngine ?? '>=22.15';+ const current = process.versions.node;+ const satisfied = semver.satisfies(current, required, { includePrerelease: true });+ const hasZstd = typeof (zlib as { zstdDecompress?: unknown }).zstdDecompress === 'function';+ const evidence = {+ hasZstd,+ nodeVersion: current,+ platform: `${process.platform}/${process.arch}`,+ required,+ };++ if (!satisfied)+ return {+ detail: `node v${current} is below the required ${required}.`,+ evidence,+ fix: 'Install node >= 22.15 (nvm install 22 / fnm install 22) and re-run.',+ status: 'fail',+ };++ if (!hasZstd)+ return {+ detail: `node v${current} satisfies ${required} but does not expose zlib.zstdDecompress.`,+ evidence,+ fix: 'Use an official node build β this runtime is missing APIs the CLI imports at startup.',+ status: 'fail',+ };++ return {+ detail: `node v${current} on ${process.platform}/${process.arch}.`,+ evidence,+ status: 'ok',+ };+ },+ title: 'node runtime',+};++/** Which `lh` is actually running, and whether another one shadows it. */+const cliInstall: DoctorCheck = {+ group: 'runtime',+ id: 'runtime.install',+ profiles: ['core'],+ run: (): CheckOutcome => {+ let entry = process.argv[1] ?? '';+ try {+ entry = fs.realpathSync(entry);+ } catch {+ // A bundled or virtual entry path is still worth reporting verbatim.+ }++ const installs = listInstalls();+ const packageManager = detectPackageManager();+ const evidence = { entry, installs, packageManager, version: cliVersion };++ if (installs.length > 1)+ return {+ // PATH order decides which one a bare `lh` runs, and they can be+ // different builds β an npm global next to a desktop-bundled copy.+ detail: `PATH resolves lh to ${installs[0]}, shadowing ${installs.length - 1} other install(s).`,+ evidence,+ fix: `Remove the ones you don't want: ${installs.slice(1).join(', ')}.`,+ status: 'warn',+ };++ return { detail: `${cliVersion} from ${entry} (${packageManager}).`, evidence, status: 'ok' };+ },+ title: 'cli install',+};++function listInstalls(): string[] {+ try {+ const { stdout } = xSync(+ process.platform === 'win32' ? 'where' : 'which',+ [...(process.platform === 'win32' ? [] : ['-a']), 'lh'],+ { nodeOptions: { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }, nodePath: false },+ );++ const resolved = stdout+ .split('\n')+ .map((line) => line.trim())+ .filter(Boolean)+ .map((candidate) => {+ try {+ return fs.realpathSync(candidate);+ } catch {+ return candidate;+ }+ });++ return [...new Set(resolved)];+ } catch {+ return [];+ }+}++/**+ * The CLI home holds credentials, the daemon's pid/status, the connection id+ * and the persisted workspace scope. An unwritable or world-readable one+ * degrades in ways that surface much later as "why did it forget my login".+ */+const cliHome: DoctorCheck = {+ group: 'runtime',+ id: 'runtime.home',+ profiles: ['core'],+ repair: (_ctx, result) => {+ // The check reports two different broken states; repair only the one it+ // actually found, or a loose-permission warning would silently move a+ // perfectly good settings.json aside.+ const repairable = result.evidence?.repairable;++ if (repairable === 'settings') {+ const settingsFile = path.join(configDir(), 'settings.json');+ // Re-confirm at repair time: only a file that reads and fails to parse+ // is moved aside.+ let stillCorrupt = false;+ try {+ JSON.parse(fs.readFileSync(settingsFile, 'utf8'));+ } catch (error) {+ stillCorrupt = error instanceof SyntaxError;+ }+ if (!stillCorrupt) throw new Error('settings.json is no longer unparseable; left in place');++ // Never clobber an earlier backup: the second corruption would destroy+ // the copy the first repair preserved, which nothing has diagnosed.+ let backup = `${settingsFile}.bak`;+ if (fs.existsSync(backup)) backup = `${settingsFile}.${Date.now()}.bak`;+ fs.renameSync(settingsFile, backup);+ return `moved the unparseable settings.json to ${backup}`;+ }++ if (repairable === 'permissions') {+ const targets = (result.evidence?.loosePermissions as string[] | undefined) ?? [];+ for (const target of targets)+ fs.chmodSync(target, fs.statSync(target).isDirectory() ? 0o700 : 0o600);+ return `tightened permissions on ${targets.length} path(s)`;+ }++ throw new Error('nothing to repair here');+ },+ run: (): CheckOutcome => {+ const dir = configDir();+ const settingsFile = path.join(dir, 'settings.json');+ const evidence: Record<string, unknown> = { dir };++ if (!fs.existsSync(dir)) {+ try {+ fs.accessSync(os.homedir(), fs.constants.W_OK);+ return {+ detail: `${dir} does not exist yet; it will be created on first write.`,+ evidence,+ status: 'ok',+ };+ } catch {+ return {+ detail: `${dir} does not exist and ${os.homedir()} is not writable.`,+ evidence,+ fix: 'Point the CLI at a writable home with LOBEHUB_CLI_HOME.',+ status: 'fail',+ };+ }+ }++ try {+ fs.accessSync(dir, fs.constants.W_OK);+ } catch {+ return {+ detail: `${dir} is not writable.`,+ evidence,+ fix: `chmod u+w ${dir}, or set LOBEHUB_CLI_HOME to a writable directory.`,+ status: 'fail',+ };+ }++ const loose = loosePermissions([dir, settingsFile, credentialsPath()]);+ evidence.loosePermissions = loose;++ if (fs.existsSync(settingsFile)) {+ let raw: string;+ try {+ raw = fs.readFileSync(settingsFile, 'utf8');+ } catch (error) {+ // Unreadable is not corrupt: the file may be perfectly valid, so it is+ // not offered to --fix, which would move it aside unparsed.+ return {+ detail: `${settingsFile} cannot be read: ${error instanceof Error ? error.message : String(error)}.`,+ evidence,+ fix: `chmod u+r ${settingsFile}`,+ status: 'fail',+ };+ }++ try {+ JSON.parse(raw);+ } catch {+ return {+ detail: `${settingsFile} is not valid JSON, so every custom URL in it is being ignored.`,+ evidence: { ...evidence, repairable: 'settings' },+ fix: `Delete it and run 'lh login' again, or re-run with --fix to move it aside.`,+ status: 'fail',+ };+ }+ }++ if (loose.length > 0)+ return {+ detail: `${dir} is usable, but ${loose.length} file(s) are readable by other users.`,+ evidence: { ...evidence, repairable: 'permissions' },+ fix: `chmod go-rwx ${loose.join(' ')}`,+ status: 'warn',+ };++ return { detail: `${dir} is writable and private.`, evidence, status: 'ok' };+ },+ title: 'cli home',+};++function loosePermissions(paths: string[]): string[] {+ if (process.platform === 'win32') return [];+ return paths.filter((target) => {+ try {+ return (fs.statSync(target).mode & 0o077) !== 0;+ } catch {+ return false;+ }+ });+}++/**+ * Disk, not because the CLI needs much, but because everything it drives does:+ * a full disk shows up as unrelated pull/extract failures much further down.+ */+const diskSpace: DoctorCheck = {+ group: 'runtime',+ id: 'runtime.disk',+ profiles: ['core'],+ run: (): CheckOutcome => {+ const tmp = os.tmpdir();+ const evidence: Record<string, unknown> = { tmp };++ try {+ const probe = path.join(tmp, `lh-doctor-${process.pid}`);+ fs.writeFileSync(probe, 'ok');+ fs.unlinkSync(probe);+ } catch (error) {+ return {+ detail: `${tmp} is not writable: ${error instanceof Error ? error.message : String(error)}.`,+ evidence,+ fix: 'Set TMPDIR to a writable directory.',+ status: 'fail',+ };+ }++ let free: number | undefined;+ try {+ const stats = fs.statfsSync(os.homedir());+ free = stats.bavail * stats.bsize;+ } catch {+ return {+ detail: `${tmp} is writable; free space is unknown on this platform.`,+ evidence,+ status: 'ok',+ };+ }++ evidence.freeBytes = free;++ if (free < 512 * 1024 ** 2)+ return {+ detail: `Only ${bytesToGb(free)} free on ${os.homedir()}.`,+ evidence,+ fix: 'Free up space β downloads, image pulls and log writes fail in confusing ways below ~0.5 GB.',+ status: 'fail',+ };++ if (free < 5 * 1024 ** 3)+ return {+ detail: `${bytesToGb(free)} free on ${os.homedir()}.`,+ evidence,+ fix: 'Consider freeing space before long runs.',+ status: 'warn',+ };++ return { detail: `${bytesToGb(free)} free, ${tmp} writable.`, evidence, status: 'ok' };+ },+ title: 'disk & tmp',+};++/** A newer published CLI is a warning, never a failure. */+const cliUpToDate: DoctorCheck = {+ // The runner's budget must outlast the internal deadline for every+ // `--timeout`, or a stalled registry surfaces as a runner failure instead+ // of the warning this check reports.+ budgetMs: (options) => options.timeoutMs + 1000,+ group: 'runtime',+ id: 'runtime.latest',+ network: true,+ profiles: ['core'],+ run: async (ctx): Promise<CheckOutcome> => {+ let latest: string;+ try {+ // Bound the request here rather than letting the runner's timeout fire:+ // that would surface as `fail` (and a non-zero exit) for what this check+ // has decided is only ever a warning.+ let timer: NodeJS.Timeout | undefined;+ try {+ latest = await Promise.race([+ fetchLatestVersion(cliPackageName, 'latest'),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () =>+ reject(+ new Error(`the npm registry did not answer within ${ctx.options.timeoutMs}ms`),+ ),+ ctx.options.timeoutMs,+ );+ }),+ ]);+ } finally {+ clearTimeout(timer);+ }+ } catch (error) {+ return {+ detail: `Could not reach the npm registry: ${error instanceof Error ? error.message : String(error)}.`,+ fix: 'Only affects the update check; ignore it on an air-gapped machine.',+ status: 'warn',+ };+ }++ if (isNewerVersion(latest, cliVersion))+ return {+ detail: `${cliVersion} installed, ${latest} published.`,+ evidence: { installed: cliVersion, latest },+ fix: 'lh update',+ status: 'warn',+ };++ return {+ detail: `${cliVersion} is the latest published version.`,+ evidence: { installed: cliVersion, latest },+ status: 'ok',+ };+ },+ title: 'cli version',+};++export const runtimeChecks: readonly DoctorCheck[] = [+ nodeVersion,+ cliInstall,+ cliHome,+ diskSpace,+ cliUpToDate,+];diff --git a/apps/cli/src/doctor/checks/scope.test.ts b/apps/cli/src/doctor/checks/scope.test.tsnew file mode 100644index 00000000000..b3bbc743d21--- /dev/null+++ b/apps/cli/src/doctor/checks/scope.test.ts@@ -0,0 +1,136 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { findCheck, makeContext, runCheck } from '../testUtils';+import { scopeChecks } from './scope';++const state = vi.hoisted(() => ({+ identity: undefined as string | undefined,+ stored: null as any,+}));+const saveActiveWorkspace = vi.hoisted(() => vi.fn());++vi.mock('../../settings', () => ({+ loadActiveWorkspace: () => state.stored,+ resolveServerUrl: () => state.serverUrl,+ saveActiveWorkspace,+}));++vi.mock('../../auth/identity', () => ({ resolveIdentityFingerprint: () => state.identity }));++describe('scope.workspace', () => {+ beforeEach(() => {+ state.serverUrl = 'https://app.lobehub.com';+ state.stored = null;+ state.identity = 'user:me';+ delete process.env.LOBEHUB_WORKSPACE_ID;+ delete process.env.LOBEHUB_JWT;+ });++ afterEach(() => {+ saveActiveWorkspace.mockClear();+ });++ it('reports personal scope when nothing is selected', async () => {+ const outcome = await runCheck(scopeChecks, 'scope.workspace');++ expect(outcome.status).toBe('ok');+ expect(outcome.detail).toContain('Personal scope');+ });++ it('redacts a basic-auth server URL before it reaches the report', async () => {+ // Found by sweeping every check's evidence for an injected credential.+ state.serverUrl = 'https://alice:[email protected]';++ const outcome = await runCheck(scopeChecks, 'scope.workspace');++ expect(JSON.stringify(outcome.evidence)).not.toContain('s3cret');+ expect(JSON.stringify(outcome.evidence)).toContain('lobe.internal');+ });++ it('warns without offering to repair when the account cannot be identified', async () => {+ // An API key has no readable subject, so a valid saved scope must not be+ // classified as stale β `--fix` would delete the user's selection.+ state.stored = {+ identity: 'user:me',+ serverUrl: 'https://app.lobehub.com',+ workspaceId: 'ws_1',+ };+ state.identity = undefined;++ const outcome = await runCheck(scopeChecks, 'scope.workspace');++ expect(outcome.status).toBe('warn');+ expect(outcome.evidence?.repairable).toBeUndefined();+ });++ it('fails a saved scope that belongs to another account', async () => {+ state.stored = {+ identity: 'user:someone-else',+ serverUrl: 'https://app.lobehub.com',+ workspaceId: 'ws_1',+ };++ const outcome = await runCheck(scopeChecks, 'scope.workspace');++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('saved under a different account');+ });++ it('fails a saved scope that belongs to another server', async () => {+ state.stored = { identity: 'user:me', serverUrl: 'https://lobe.internal', workspaceId: 'ws_1' };++ const outcome = await runCheck(scopeChecks, 'scope.workspace');++ expect(outcome.status).toBe('fail');+ expect(outcome.detail).toContain('https://lobe.internal');+ });++ it('drops the stale scope under --fix', async () => {+ state.stored = {+ identity: 'user:someone-else',+ serverUrl: 'https://app.lobehub.com',+ workspaceId: 'ws_1',+ };+ const outcome = await runCheck(scopeChecks, 'scope.workspace');+ const check = findCheck(scopeChecks, 'scope.workspace');++ const action = await check.repair!(makeContext({ fix: true }), {+ ...outcome,+ durationMs: 0,+ group: 'scope',+ id: 'scope.workspace',+ title: '',+ });++ expect(saveActiveWorkspace).toHaveBeenCalledWith(null);+ expect(action).toContain('cleared');+ });++ it('warns when the env var overrides a different saved scope', async () => {+ state.stored = {+ identity: 'user:me',+ serverUrl: 'https://app.lobehub.com',+ workspaceId: 'ws_1',+ };+ process.env.LOBEHUB_WORKSPACE_ID = 'ws_2';++ const outcome = await runCheck(scopeChecks, 'scope.workspace');++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('ws_2');+ });++ it('treats a dispatched run as personal, ignoring the saved scope', async () => {+ state.stored = {+ identity: 'user:me',+ serverUrl: 'https://app.lobehub.com',+ workspaceId: 'ws_1',+ };+ process.env.LOBEHUB_JWT = 'header.payload.sig';++ const outcome = await runCheck(scopeChecks, 'scope.workspace');++ expect(outcome.status).toBe('ok');+ expect(outcome.detail).toContain('deliberately ignored');+ });+});diff --git a/apps/cli/src/doctor/checks/scope.ts b/apps/cli/src/doctor/checks/scope.tsnew file mode 100644index 00000000000..71b8464c017--- /dev/null+++ b/apps/cli/src/doctor/checks/scope.ts@@ -0,0 +1,104 @@+import { resolveIdentityFingerprint } from '../../auth/identity';+import { loadActiveWorkspace, resolveServerUrl, saveActiveWorkspace } from '../../settings';+import { redactUrlCredentials } from '../redact';+import type { CheckOutcome, DoctorCheck } from '../types';++/**+ * Which tenant this CLI writes into.+ *+ * The failure worth catching is silent: cloud answers an `X-Workspace-Id` the+ * caller has no membership in by falling back to personal scope, so a scope+ * left over from another account (or another server) keeps printing+ * "workspace" while reads and writes land on personal data. Ingests that+ * "disappear" are almost always this.+ */+const workspaceScope: DoctorCheck = {+ group: 'scope',+ id: 'scope.workspace',+ profiles: ['core'],+ repair: (_ctx, result) => {+ // A saved scope that an env var merely overrides for this one run is still+ // the user's valid selection β dropping it would silently move them to+ // personal scope the moment the override goes away.+ if (result.evidence?.repairable !== 'stale')+ throw new Error('the saved workspace scope is valid; only an unusable one is dropped');++ saveActiveWorkspace(null);+ return 'cleared the stale workspace scope; commands now run in personal scope';+ },+ run: (): CheckOutcome => {+ const stored = loadActiveWorkspace();+ const fromEnv = process.env.LOBEHUB_WORKSPACE_ID?.trim();+ const identity = resolveIdentityFingerprint();+ const serverUrl = resolveServerUrl();+ const evidence: Record<string, unknown> = {+ envWorkspaceId: fromEnv,+ // Redacted like every other URL that reaches the report: a self-hosted+ // server behind basic auth carries its credential in the URL itself.+ serverUrl: redactUrlCredentials(serverUrl),+ storedWorkspaceId: stored?.workspaceId,+ };++ if (fromEnv) {+ if (stored && stored.workspaceId !== fromEnv)+ return {+ detail: `LOBEHUB_WORKSPACE_ID=${fromEnv} overrides the saved scope ${stored.workspaceId}.`,+ evidence,+ fix: 'Intentional in a dispatched run; otherwise unset the env var or re-run `lh workspace use`.',+ status: 'warn',+ };++ return { detail: `Workspace ${fromEnv}, from LOBEHUB_WORKSPACE_ID.`, evidence, status: 'ok' };+ }++ // A dispatched run carries its complete scope in env; the persisted scope+ // belongs to whoever sits at this terminal and must not leak into it.+ if (process.env.LOBEHUB_JWT)+ return {+ detail: stored+ ? `Personal scope: LOBEHUB_JWT is set, so the saved scope ${stored.workspaceId} is deliberately ignored.`+ : 'Personal scope (dispatched run).',+ evidence,+ status: 'ok',+ };++ if (!stored)+ return { detail: 'Personal scope β no workspace selected.', evidence, status: 'ok' };++ // An API key carries no readable subject, so `identity` is undefined for a+ // perfectly valid saved scope whenever LOBEHUB_CLI_API_KEY is exported for+ // one command. That is "cannot tell", not "stale" β marking it repairable+ // would let `--fix` delete a selection that is still the user's.+ if (!identity)+ return {+ detail: `The saved scope ${stored.workspaceId} is ignored while the current credentials do not identify an account.`,+ evidence,+ fix: 'Expected under an API key: set LOBEHUB_WORKSPACE_ID to scope these commands.',+ status: 'warn',+ };++ const reason =+ identity !== stored.identity+ ? 'it was saved under a different account'+ : stored.serverUrl !== serverUrl+ ? `it was saved for ${redactUrlCredentials(stored.serverUrl)}`+ : undefined;++ if (reason)+ return {+ detail: `The saved scope ${stored.workspaceId} is being ignored because ${reason}.`,+ evidence: { ...evidence, repairable: 'stale' },+ fix: `Re-select it with 'lh workspace use ${stored.workspaceId}', or re-run with --fix to drop it.`,+ status: 'fail',+ };++ return {+ detail: `Workspace ${stored.workspaceId}, from 'lh workspace use'.`,+ evidence,+ status: 'ok',+ };+ },+ title: 'workspace scope',+};++export const scopeChecks: readonly DoctorCheck[] = [workspaceScope];diff --git a/apps/cli/src/doctor/checks/server.test.ts b/apps/cli/src/doctor/checks/server.test.tsnew file mode 100644index 00000000000..897acac2555--- /dev/null+++ b/apps/cli/src/doctor/checks/server.test.ts@@ -0,0 +1,144 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { runCheck } from '../testUtils';+import { enabledProviders, serverChecks } from './server';++const state = vi.hoisted(() => ({+ agentGatewayUrl: 'wss://agent-gateway.lobehub.com',+ globalConfig: {} as any,+ providers: [] as any[],+ userState: {} as any,+ userStateError: undefined as Error | undefined,+}));++vi.mock('../../settings', () => ({ resolveAgentGatewayUrl: () => state.agentGatewayUrl }));+vi.mock('../../constants/urls', () => ({+ OFFICIAL_AGENT_GATEWAY_URL: 'wss://agent-gateway.lobehub.com',+}));++vi.mock('../probes', () => ({+ probeClient: async () => ({+ user: {+ getUserState: {+ query: async () => {+ if (state.userStateError) throw state.userStateError;+ return state.userState;+ },+ },+ },+ }),+ probeGlobalConfig: async () => state.globalConfig,+ probeProviders: async () => state.providers,+}));++describe('enabledProviders', () => {+ it('unions account-enabled providers with the ones the server enables from env', () => {+ expect(+ enabledProviders(+ [+ { enabled: true, id: 'openai' },+ { enabled: false, id: 'anthropic' },+ ],+ {+ fireworksai: { enabled: true },+ groq: { enabled: false },+ },+ ),+ ).toEqual(['fireworksai', 'openai']);+ });+});++describe('server.identity', () => {+ beforeEach(() => {+ state.userStateError = undefined;+ state.userState = { subscriptionPlan: 'pro', userId: 'user_1', username: 'me' };+ });++ it('names the account the server accepted', async () => {+ const outcome = await runCheck(serverChecks, 'server.identity');++ expect(outcome.status).toBe('ok');+ expect(outcome.detail).toContain('me');+ });++ it('separates a rejected credential from a broken call', async () => {+ state.userStateError = new Error('UNAUTHORIZED');++ const outcome = await runCheck(serverChecks, 'server.identity');++ expect(outcome.status).toBe('fail');+ expect(outcome.fix).toContain('Log in again');+ });+});++describe('server.capabilities', () => {+ it('flags an agent gateway the CLI and the server disagree about', async () => {+ state.globalConfig = {+ serverConfig: {+ agentGatewayUrl: 'wss://gateway.internal',+ enableGatewayMode: true,+ enableUploadFileToServer: true,+ },+ };++ const outcome = await runCheck(serverChecks, 'server.capabilities');++ expect(outcome.status).toBe('fail');+ expect(outcome.fix).toContain('AGENT_GATEWAY_URL=wss://gateway.internal');+ });++ it('does not escalate an unrelated capability to a failure', async () => {+ state.agentGatewayUrl = 'wss://agent-gateway.lobehub.com';+ state.globalConfig = {+ serverConfig: {+ agentGatewayUrl: 'wss://agent-gateway.lobehub.com',+ enableGatewayMode: true,+ enableUploadFileToServer: false,+ },+ };++ const outcome = await runCheck(serverChecks, 'server.capabilities');++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('file storage is off');+ });++ it('warns when gateway mode is off server-side', async () => {+ state.agentGatewayUrl = 'wss://gateway.internal';+ state.globalConfig = {+ serverConfig: {+ agentGatewayUrl: 'wss://gateway.internal',+ enableGatewayMode: false,+ enableUploadFileToServer: true,+ },+ };++ const outcome = await runCheck(serverChecks, 'server.capabilities');++ expect(outcome.status).toBe('warn');+ expect(outcome.detail).toContain('gateway mode is off');+ });+});++describe('server.providers', () => {+ it('fails when no provider is enabled at all', async () => {+ state.providers = [{ enabled: false, id: 'openai' }];+ state.globalConfig = { serverConfig: { aiProvider: {} } };++ const outcome = await runCheck(serverChecks, 'server.providers');++ expect(outcome.status).toBe('fail');+ expect(outcome.fix).toContain('<PROVIDER>_API_KEY');+ });++ it('claims enablement, not a usable key, for the providers it lists', async () => {+ state.providers = [{ enabled: true, id: 'openai' }];+ state.globalConfig = { serverConfig: { aiProvider: {} } };++ const outcome = await runCheck(serverChecks, 'server.providers');++ expect(outcome.status).toBe('ok');+ expect(outcome.detail).toContain('1 enabled provider(s)');+ expect(outcome.detail).not.toContain('usable');+ });+});diff --git a/apps/cli/src/doctor/checks/server.ts b/apps/cli/src/doctor/checks/server.tsnew file mode 100644index 00000000000..ce9570ae0b3--- /dev/null+++ b/apps/cli/src/doctor/checks/server.ts@@ -0,0 +1,185 @@+import { OFFICIAL_AGENT_GATEWAY_URL } from '../../constants/urls';+import { resolveAgentGatewayUrl } from '../../settings';+import { probeClient, probeGlobalConfig, probeProviders } from '../probes';+import { maskEmail } from '../redact';+import type { CheckOutcome, DoctorCheck } from '../types';++const errorMessage = (error: unknown): string =>+ error instanceof Error ? error.message : String(error);++/** Does the server accept this credential, and as whom. */+const identity: DoctorCheck = {+ dependsOn: ['credentials.validity'],+ group: 'server',+ id: 'server.identity',+ network: true,+ profiles: ['core'],+ run: async (ctx): Promise<CheckOutcome> => {+ const client = await probeClient(ctx);++ try {+ const state = (await client.user.getUserState.query()) as Record<string, any>;+ const evidence = {+ email: maskEmail(state.email),+ plan: state.subscriptionPlan,+ userId: state.userId,+ username: state.username,+ };++ return {+ detail: `Authenticated as ${state.username || maskEmail(state.email) || state.userId}${state.subscriptionPlan ? ` (${state.subscriptionPlan})` : ''}.`,+ evidence,+ status: 'ok',+ };+ } catch (error) {+ const message = errorMessage(error);+ const rejected = /UNAUTHORIZED|FORBIDDEN|401|403/i.test(message);++ return {+ detail: rejected+ ? `The server rejected this credential: ${message}.`+ : `The identity call failed: ${message}.`,+ evidence: { error: message },+ fix: rejected+ ? 'Log in again, or check that the credential belongs to this server.'+ : 'The credential looks fine β suspect the server or the network path.',+ status: 'fail',+ };+ }+ },+ title: 'server identity',+};++/**+ * Self-hosting reads as "the CLI is broken" whenever a capability the command+ * needs was never switched on server-side. Gateway mode, the agent gateway URL+ * and server-side file storage are the three that produce the most confusing+ * downstream errors.+ */+const capabilities: DoctorCheck = {+ dependsOn: ['server.identity'],+ group: 'server',+ id: 'server.capabilities',+ network: true,+ profiles: ['agent', 'selfhost'],+ run: async (ctx): Promise<CheckOutcome> => {+ const config = (await probeGlobalConfig(ctx)) as Record<string, any>;+ const serverConfig = (config?.serverConfig ?? {}) as Record<string, any>;+ const cliAgentGateway = resolveAgentGatewayUrl();+ const evidence = {+ cliAgentGatewayUrl: cliAgentGateway,+ enableGatewayMode: serverConfig.enableGatewayMode,+ enableUploadFileToServer: serverConfig.enableUploadFileToServer,+ serverAgentGatewayUrl: serverConfig.agentGatewayUrl,+ };++ const problems: string[] = [];+ const fixes: string[] = [];+ // A capability that is merely off degrades one feature; streaming from+ // someone else's agent gateway means every run silently goes nowhere.+ let status: CheckOutcome['status'] = 'warn';++ if (serverConfig.enableGatewayMode === false) {+ problems.push('gateway mode is off, so the server will not run agents on your behalf');+ fixes.push('set AGENT_RUNTIME_MODE / the gateway env on the server');+ }++ if (+ serverConfig.agentGatewayUrl &&+ cliAgentGateway &&+ serverConfig.agentGatewayUrl.replace(/\/$/, '') !== cliAgentGateway.replace(/\/$/, '')+ ) {+ problems.push(+ `the server advertises agent gateway ${serverConfig.agentGatewayUrl} but this CLI streams from ${cliAgentGateway}`,+ );+ fixes.push(`export AGENT_GATEWAY_URL=${serverConfig.agentGatewayUrl}`);+ if (cliAgentGateway === OFFICIAL_AGENT_GATEWAY_URL) status = 'fail';+ }++ if (serverConfig.enableUploadFileToServer === false) {+ problems.push('server-side file storage is off, so uploads and evidence capture will fail');+ fixes.push('configure S3_* on the server');+ }++ if (problems.length > 0)+ return { detail: `${problems.join('; ')}.`, evidence, fix: fixes.join('; '), status };++ return {+ detail: `Gateway mode ${serverConfig.enableGatewayMode ? 'on' : 'unset'}, server-side file storage ${serverConfig.enableUploadFileToServer ? 'on' : 'unset'}.`,+ evidence,+ status: 'ok',+ };+ },+ title: 'server capabilities',+};++/**+ * Whether any model can actually be called.+ *+ * This is the check that turns `InvalidProviderAPIKey` β raised deep inside a+ * run, after minutes of setup β into a one-line answer before the run starts.+ */+const providers: DoctorCheck = {+ dependsOn: ['server.identity'],+ group: 'server',+ id: 'server.providers',+ network: true,+ profiles: ['agent', 'selfhost'],+ run: async (ctx): Promise<CheckOutcome> => {+ const [userProviders, config] = await Promise.all([+ probeProviders(ctx),+ probeGlobalConfig(ctx).catch(() => undefined),+ ]);++ const serverProviders = ((config as any)?.serverConfig?.aiProvider ?? {}) as Record<+ string,+ { enabled?: boolean }+ >;+ const enabled = enabledProviders(userProviders, serverProviders);+ const evidence = {+ enabled,+ fromServerEnv: Object.entries(serverProviders)+ .filter(([, value]) => value?.enabled)+ .map(([id]) => id),+ };++ if (enabled.length === 0)+ return {+ detail: 'No provider is enabled, on the account or on the server.',+ evidence,+ fix: "Add a key with 'lh provider' in the app, or set <PROVIDER>_API_KEY on the server.",+ status: 'fail',+ };++ // Enablement is not the same as having a key β a provider can be toggled on+ // with an empty key vault. Whether a specific one can actually be called is+ // answered per agent by `execution.agent`.+ return {+ detail: `${enabled.length} enabled provider(s): ${enabled.slice(0, 6).join(', ')}${enabled.length > 6 ? 'β¦' : ''}.`,+ evidence,+ status: 'ok',+ };+ },+ title: 'model providers',+};++/**+ * Providers enabled on the account, plus those the server enables from its env.+ *+ * Enabled is all this can honestly claim: `getAiProviderList` reports the+ * toggle, and a provider can be switched on with no key stored at all.+ */+export function enabledProviders(+ userProviders: any[],+ serverProviders: Record<string, { enabled?: boolean }>,+): string[] {+ const enabled = new Set<string>();++ for (const provider of userProviders)+ if (provider?.enabled && provider.id) enabled.add(String(provider.id));+ for (const [id, value] of Object.entries(serverProviders)) if (value?.enabled) enabled.add(id);++ return [...enabled].sort();+}++export const serverChecks: readonly DoctorCheck[] = [identity, capabilities, providers];diff --git a/apps/cli/src/doctor/index.ts b/apps/cli/src/doctor/index.tsnew file mode 100644index 00000000000..eca13e06802--- /dev/null+++ b/apps/cli/src/doctor/index.ts@@ -0,0 +1,31 @@+import { contextChecks } from './checks/context';+import { credentialChecks } from './checks/credentials';+import { deviceChecks } from './checks/device';+import { endpointChecks } from './checks/endpoints';+import { executionChecks } from './checks/execution';+import { runtimeChecks } from './checks/runtime';+import { scopeChecks } from './checks/scope';+import { serverChecks } from './checks/server';+import type { DoctorCheck } from './types';++/**+ * Every check, in the order they run.+ *+ * Order is the diagnosis: each layer is only meaningful once the one above it+ * holds, and the runner uses `dependsOn` to stop reporting derived symptoms+ * once a root cause has been found.+ */+export const ALL_CHECKS: readonly DoctorCheck[] = [+ ...runtimeChecks,+ ...endpointChecks,+ ...credentialChecks,+ ...scopeChecks,+ ...contextChecks,+ ...serverChecks,+ ...deviceChecks,+ ...executionChecks,+];++export { renderCompact, renderReport } from './report';+export { exitCodeFor, runDoctor, summarize } from './runner';+export * from './types';diff --git a/apps/cli/src/doctor/probes.ts b/apps/cli/src/doctor/probes.tsnew file mode 100644index 00000000000..4b178d054b9--- /dev/null+++ b/apps/cli/src/doctor/probes.ts@@ -0,0 +1,164 @@+import { createLambdaClient, type TrpcClient } from '../api/client';+import { resolveWorkspaceScope } from '../api/workspace';+import { getUserIdFromApiKey } from '../auth/apiKey';+import { getValidToken } from '../auth/refresh';+import type { AuthSourceKind } from '../auth/source';+import { parseJwtPayload, pickAuthSource } from '../auth/source';+import { resolveServerUrl } from '../settings';+import type { DoctorContext } from './types';++/**+ * Shared loaders. Each is memoized per `lh doctor` run through `ctx.probe`, so+ * the six checks that need "who am I" or "what does the server say" cost one+ * request between them, and every one of them sees the same answer.+ */++export interface ServerVersionProbe {+ /** The server's own clock, from the response `Date` header. */+ dateHeader?: string;+ latencyMs: number;+ serverUrl: string;+ statusCode: number;+ version?: string;+}++export async function probeServerVersion(ctx: DoctorContext): Promise<ServerVersionProbe> {+ return ctx.probe('server:version', async () => {+ const serverUrl = resolveServerUrl();+ const startedAt = Date.now();+ const response = await fetch(`${serverUrl}/api/version`, {+ headers: { accept: 'application/json' },+ signal: AbortSignal.timeout(ctx.options.timeoutMs),+ });+ const latencyMs = Date.now() - startedAt;++ let version: string | undefined;+ try {+ const body = (await response.json()) as { version?: string };+ version = body.version;+ } catch {+ // A reachable endpoint that isn't JSON is still a reachability signal.+ }++ return {+ dateHeader: response.headers.get('date') ?? undefined,+ latencyMs,+ serverUrl,+ statusCode: response.status,+ version,+ };+ });+}++export interface CredentialProbe {+ /** Why the credential could not be used, when it could not. */+ error?: string;+ /** `exp` claim, for JWTs. */+ expiresAt?: number;+ kind: AuthSourceKind;+ origin: string;+ serverUrl: string;+ token?: string;+ tokenType: 'apiKey' | 'jwt' | 'serviceToken';+ userId?: string;+}++/**+ * Resolve the live credential the way a real command would β refreshing a+ * stored token, validating an API key against the server β but reporting+ * failure instead of exiting, because "no usable credential" is an answer+ * doctor has to print rather than die on.+ */+export async function probeCredential(ctx: DoctorContext): Promise<CredentialProbe> {+ return ctx.probe('auth:credential', async () => {+ const source = pickAuthSource();+ const serverUrl = resolveServerUrl();+ const base = {+ kind: source.kind,+ origin: source.origin,+ serverUrl,+ tokenType: source.tokenType,+ };++ if (source.kind === 'env-api-key') {+ try {+ const userId = await getUserIdFromApiKey(source.token!, serverUrl);+ return { ...base, token: source.token, userId };+ } catch (error) {+ return { ...base, error: error instanceof Error ? error.message : String(error) };+ }+ }++ if (source.kind === 'stored') {+ const refreshed = await getValidToken();+ if (!refreshed)+ return {+ ...base,+ error: source.token+ ? 'the stored token has expired and could not be refreshed'+ : 'no stored login on this machine',+ };+ const payload = parseJwtPayload(refreshed.credentials.accessToken);+ return {+ ...base,+ expiresAt: typeof payload?.exp === 'number' ? payload.exp : undefined,+ token: refreshed.credentials.accessToken,+ userId: typeof payload?.sub === 'string' ? payload.sub : undefined,+ };+ }++ const payload = source.token ? parseJwtPayload(source.token) : undefined;+ return {+ ...base,+ expiresAt: typeof payload?.exp === 'number' ? payload.exp : undefined,+ token: source.token,+ userId: typeof payload?.sub === 'string' ? payload.sub : undefined,+ };+ });+}++/**+ * A tRPC client built from the already-probed credential.+ *+ * Deliberately not `getTrpcClient()`: that one re-resolves credentials and+ * exits the process when there are none, which would kill the report right+ * where it gets interesting.+ */+export async function probeClient(ctx: DoctorContext): Promise<TrpcClient> {+ return ctx.probe('api:client', async () => {+ const credential = await probeCredential(ctx);+ if (!credential.token) throw new Error(credential.error ?? 'no usable credential');++ return createLambdaClient(+ {+ serverUrl: credential.serverUrl,+ token: credential.token,+ tokenType: credential.tokenType,+ },+ resolveWorkspaceScope().workspaceId,+ );+ });+}++export async function probeGlobalConfig(ctx: DoctorContext): Promise<any> {+ return ctx.probe('server:globalConfig', async () => {+ const client = await probeClient(ctx);+ return client.config.getGlobalConfig.query();+ });+}++export async function probeDevices(ctx: DoctorContext): Promise<any[]> {+ return ctx.probe('server:devices', async () => {+ const client = await probeClient(ctx);+ const devices = await client.device.listDevices.query();+ return Array.isArray(devices) ? devices : [];+ });+}++export async function probeProviders(ctx: DoctorContext): Promise<any[]> {+ return ctx.probe('server:providers', async () => {+ const client = await probeClient(ctx);+ const providers = await client.aiProvider.getAiProviderList.query();+ return Array.isArray(providers) ? providers : [];+ });+}diff --git a/apps/cli/src/doctor/redact.test.ts b/apps/cli/src/doctor/redact.test.tsnew file mode 100644index 00000000000..a5fe9eede5a--- /dev/null+++ b/apps/cli/src/doctor/redact.test.ts@@ -0,0 +1,100 @@+import { describe, expect, it } from 'vitest';++import {+ maskEmail,+ redactUrlCredentials,+ redactUrlsInMessage,+ scrubDeep,+ scrubText,+} from './redact';++describe('redactUrlCredentials', () => {+ it('keeps the host and drops the credential', () => {+ expect(redactUrlCredentials('https://alice:[email protected]:8443/x')).toBe(+ 'https://***:***@lobe.internal:8443/x',+ );+ });++ it('leaves a credential-free URL untouched', () => {+ expect(redactUrlCredentials('https://app.lobehub.com')).toBe('https://app.lobehub.com');+ });++ it('passes through a value that is not a URL', () => {+ // NO_PROXY is a host list, not a URL.+ expect(redactUrlCredentials('localhost,127.0.0.1,.internal')).toBe(+ 'localhost,127.0.0.1,.internal',+ );+ });+});++describe('maskEmail', () => {+ it('leaves enough to recognise the account and no more', () => {+ expect(maskEmail('[email protected]')).toBe('a***@e***.com');+ });++ it('does not pass through something that is not an address', () => {+ expect(maskEmail('not-an-email')).toBe('***');+ });+});++describe('redactUrlsInMessage', () => {+ it('drops the query string a gateway error quotes', () => {+ const message =+ "WebSocket connection to 'ws://127.0.0.1:9/ws?deviceId=d1&hostname=mac&userId=user_1' failed";++ const redacted = redactUrlsInMessage(message);++ expect(redacted).toBe("WebSocket connection to 'ws://127.0.0.1:9/ws' failed");+ expect(redacted).not.toContain('user_1');+ });++ it('stays linear on input built to make it backtrack', () => {+ const hostile = `${'ws://'.repeat(20_000)}x`;++ const startedAt = Date.now();+ redactUrlsInMessage(hostile);++ expect(Date.now() - startedAt).toBeLessThan(1000);+ });+});++describe('scrubText', () => {+ it('scrubs a credential-bearing URL quoted inside an error message', () => {+ // Node's fetch error names the full request URL.+ expect(+ scrubText('fetch failed for https://alice:[email protected]/api/version (ECONNREFUSED)'),+ ).toBe('fetch failed for https://***@lobe.internal/api/version (ECONNREFUSED)');+ });++ it('masks a bare email and strips a WebSocket query', () => {+ expect(scrubText("user [email protected] via 'wss://gw.example.com/ws?userId=u1'")).toBe(+ "user a***@e***.com via 'wss://gw.example.com/ws'",+ );+ });++ it('leaves ordinary text alone', () => {+ const text = 'node v24.3.0 on darwin/arm64, 2 installs at /opt/homebrew/bin/lh';+ expect(scrubText(text)).toBe(text);+ });++ it('stays linear on hostile input', () => {+ const startedAt = Date.now();+ scrubText(`${'https://a@'.repeat(20_000)}x ${'@'.repeat(50_000)}`);+ expect(Date.now() - startedAt).toBeLessThan(1000);+ });+});++describe('scrubDeep', () => {+ it('reaches strings nested anywhere in evidence', () => {+ const scrubbed = scrubDeep({+ evidence: {+ gateways: ['wss://bob:[email protected]/ws'],+ nested: { server: 'https://a:[email protected]' },+ },+ status: 'ok',+ });++ expect(JSON.stringify(scrubbed)).not.toMatch(/pw@|a:b@/);+ expect(scrubbed.status).toBe('ok');+ });+});diff --git a/apps/cli/src/doctor/redact.ts b/apps/cli/src/doctor/redact.tsnew file mode 100644index 00000000000..5047a59d45b--- /dev/null+++ b/apps/cli/src/doctor/redact.ts@@ -0,0 +1,114 @@+/**+ * Report-boundary redaction.+ *+ * The whole report β `--json` and `-v` evidence included β exists to be pasted+ * into an issue, so anything that reaches it has to be safe to share. These+ * helpers are applied where a value enters a detail, a fix, or evidence; the+ * raw values keep flowing to the code that actually connects.+ */++/**+ * `https://user:password@host` is a normal way to point at a+ * basic-auth-protected deployment or a corporate proxy. Keep the host, drop+ * the credential.+ */+export function redactUrlCredentials(value: string): string;+export function redactUrlCredentials(value: string | undefined): string | undefined;+export function redactUrlCredentials(value: string | undefined): string | undefined {+ if (!value) return value;++ try {+ const url = new URL(value);+ if (!url.username && !url.password) return value;+ if (url.username) url.username = '***';+ if (url.password) url.password = '***';+ return url.toString();+ } catch {+ // Not a URL (NO_PROXY is a host list) β nothing to redact.+ return value;+ }+}++/**+ * Enough of an address to recognise which account answered, not enough to+ * hand someone else the address itself.+ */+export function maskEmail(value: string | undefined): string | undefined {+ if (!value) return value;++ const at = value.lastIndexOf('@');+ if (at <= 0) return '***';++ const [local, domain] = [value.slice(0, at), value.slice(at + 1)];+ const head = local.slice(0, 1);+ const dot = domain.lastIndexOf('.');+ const maskedDomain = dot > 0 ? `${domain.slice(0, 1)}***${domain.slice(dot)}` : '***';++ return `${head}***@${maskedDomain}`;+}++/**+ * Gateway client errors quote the full WebSocket URL, whose query string+ * carries this machine's hostname, its device id and the user id. The failure+ * is worth reporting; that query string is not.+ */+export function redactUrlsInMessage(message: string): string {+ // Tokenise first, then decide per token. A single pattern that matches the+ // URL and then *requires* a `?` backtracks across the rest of the string at+ // every starting position β quadratic, and what CodeQL flags as a ReDoS.+ // `[^\s'"]+` has nothing following it to backtrack for.+ return message.replaceAll(/[^\s'"]+/g, (token) =>+ /^wss?:\/\//i.test(token) ? token.split('?')[0]! : token,+ );+}++const EMAIL_TOKEN = /^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i;++/**+ * Scrub one whitespace/quote-delimited token. Index arithmetic rather than a+ * regex so the cost stays linear in the token length whatever it contains.+ */+function scrubToken(token: string): string {+ const schemeEnd = token.indexOf('://');++ if (schemeEnd === -1) return EMAIL_TOKEN.test(token) ? maskEmail(token)! : token;++ const authorityStart = schemeEnd + 3;+ let authorityEnd = token.length;+ for (const delimiter of ['/', '?', '#']) {+ const index = token.indexOf(delimiter, authorityStart);+ if (index !== -1 && index < authorityEnd) authorityEnd = index;+ }++ let scrubbed = token;+ const at = token.lastIndexOf('@', authorityEnd - 1);+ if (at >= authorityStart)+ scrubbed = `${token.slice(0, authorityStart)}***@${token.slice(at + 1)}`;++ // WebSocket URLs from the gateway client carry device id, hostname and user+ // id in their query string.+ if (/^wss?:\/\//i.test(scrubbed)) scrubbed = scrubbed.split('?')[0]!;++ return scrubbed;+}++/** Credentials in URLs, WebSocket query strings and email addresses, anywhere in a string. */+export function scrubText(text: string): string {+ return text.replaceAll(/[^\s'"`()<>]+/g, scrubToken);+}++/**+ * Scrub every string reachable from a value. The runner applies this to each+ * result before it enters the report, so a check that forgets to redact+ * something β the failure mode three review rounds kept finding one instance of+ * at a time β cannot leak it.+ */+export function scrubDeep<T>(value: T): T {+ if (typeof value === 'string') return scrubText(value) as T;+ if (Array.isArray(value)) return value.map((item) => scrubDeep(item)) as T;+ if (value && typeof value === 'object')+ return Object.fromEntries(+ Object.entries(value as Record<string, unknown>).map(([key, item]) => [key, scrubDeep(item)]),+ ) as T;+ return value;+}diff --git a/apps/cli/src/doctor/report.test.ts b/apps/cli/src/doctor/report.test.tsnew file mode 100644index 00000000000..8af79c241c7--- /dev/null+++ b/apps/cli/src/doctor/report.test.ts@@ -0,0 +1,78 @@+import { describe, expect, it } from 'vitest';++import { renderReport } from './report';+import type { CheckResult, DoctorReport } from './types';++const result = (overrides: Partial<CheckResult>): CheckResult => ({+ detail: 'detail',+ durationMs: 1,+ group: 'runtime',+ id: 'runtime.node',+ status: 'ok',+ title: 'node runtime',+ ...overrides,+});++const report = (checks: CheckResult[]): DoctorReport => ({+ checks,+ cli: { bin: 'lh', version: '0.0.55' },+ generatedAt: '2026-09-16T00:00:00.000Z',+ profile: 'core',+ status: checks.some((c) => c.status === 'fail') ? 'fail' : 'ok',+ summary: {+ fail: checks.filter((c) => c.status === 'fail').length,+ ok: checks.filter((c) => c.status === 'ok').length,+ skip: checks.filter((c) => c.status === 'skip').length,+ warn: checks.filter((c) => c.status === 'warn').length,+ },+});++describe('renderReport', () => {+ it('groups checks and shows the fix only for findings', () => {+ const output = renderReport(+ report([+ result({ fix: 'not shown', status: 'ok' }),+ result({+ detail: 'broken',+ fix: 'do this',+ group: 'endpoints',+ id: 'endpoints.resolution',+ status: 'fail',+ title: 'endpoint resolution',+ }),+ ]),+ );++ expect(output).toContain('Runtime');+ expect(output).toContain('Endpoints');+ expect(output).toContain('do this');+ expect(output).not.toContain('not shown');+ });++ it('hides evidence unless verbose', () => {+ const checks = [result({ evidence: { nodeVersion: 'v24.3.0' } })];++ expect(renderReport(report(checks))).not.toContain('nodeVersion');+ expect(renderReport(report(checks), { verbose: true })).toContain('nodeVersion: v24.3.0');+ });++ it('names what a repair changed', () => {+ expect(renderReport(report([result({ repaired: 'cleared the stale scope' })]))).toContain(+ 'cleared the stale scope',+ );+ });++ it('counts every status in the footer', () => {+ const output = renderReport(+ report([+ result({}),+ result({ id: 'b', status: 'warn' }),+ result({ id: 'c', status: 'skip' }),+ ]),+ );++ expect(output).toContain('1 ok');+ expect(output).toContain('1 warning');+ expect(output).toContain('1 skipped');+ });+});diff --git a/apps/cli/src/doctor/report.ts b/apps/cli/src/doctor/report.tsnew file mode 100644index 00000000000..9939a250cfe--- /dev/null+++ b/apps/cli/src/doctor/report.ts@@ -0,0 +1,99 @@+import pc from 'picocolors';++import { displayWidth } from '../utils/format';+import type { CheckResult, CheckStatus, DoctorReport } from './types';+import { CHECK_GROUP_ORDER, CHECK_GROUP_TITLES } from './types';++const ICONS: Record<CheckStatus, string> = { fail: 'β', ok: 'β', skip: 'Β·', warn: 'β ' };++const paint = (status: CheckStatus, text: string): string => {+ switch (status) {+ case 'fail': {+ return pc.red(text);+ }+ case 'ok': {+ return pc.green(text);+ }+ case 'warn': {+ return pc.yellow(text);+ }+ default: {+ return pc.dim(text);+ }+ }+};++const pad = (text: string, width: number): string =>+ text + ' '.repeat(Math.max(0, width - displayWidth(text)));++/**+ * Render the report for a terminal. The machine-readable form is the report+ * object itself β `--json` prints it verbatim, so the two never drift.+ */+export function renderReport(report: DoctorReport, options: { verbose?: boolean } = {}): string {+ const lines: string[] = [];+ const titleWidth = Math.max(0, ...report.checks.map((c) => displayWidth(c.title)));++ lines.push(+ `${pc.bold('LobeHub CLI doctor')} ${pc.dim(`Β· ${report.cli.version} Β· profile ${report.profile}`)}`,+ '',+ );++ for (const group of CHECK_GROUP_ORDER) {+ const checks = report.checks.filter((check) => check.group === group);+ if (checks.length === 0) continue;++ lines.push(pc.bold(CHECK_GROUP_TITLES[group]));+ for (const check of checks) {+ lines.push(+ ` ${paint(check.status, ICONS[check.status])} ${pad(check.title, titleWidth)} ${+ check.status === 'skip' ? pc.dim(check.detail) : check.detail+ }`,+ );+ if (check.repaired) lines.push(` ${pc.cyan('fixed')} ${check.repaired}`);+ if (check.fix && check.status !== 'ok' && check.status !== 'skip')+ lines.push(` ${pc.cyan('β')} ${check.fix}`);+ if (options.verbose && check.evidence)+ for (const [key, value] of Object.entries(check.evidence))+ lines.push(` ${pc.dim(`${key}: ${formatEvidence(value)}`)}`);+ }+ lines.push('');+ }++ if (report.repairs?.some((repair) => !repair.ok)) {+ lines.push(pc.bold('Repairs that did not apply'));+ for (const repair of report.repairs.filter((r) => !r.ok))+ lines.push(` ${pc.red('β')} ${repair.id}: ${repair.action}`);+ lines.push('');+ }++ const { fail, ok, skip, warn } = report.summary;+ lines.push(+ [+ pc.green(`${ok} ok`),+ warn > 0 ? pc.yellow(`${warn} warning${warn === 1 ? '' : 's'}`) : pc.dim('0 warnings'),+ fail > 0 ? pc.red(`${fail} failing`) : pc.dim('0 failing'),+ pc.dim(`${skip} skipped`),+ ].join(pc.dim(' Β· ')),+ );++ if (fail > 0)+ lines.push(+ pc.dim('Work top to bottom: a later layer cannot be right if an earlier one is broken.'),+ );+ else if (report.profile === 'core')+ lines.push(pc.dim('Deeper checks: --profile connect | agent | hetero | selfhost | all'));++ return lines.join('\n');+}++function formatEvidence(value: unknown): string {+ if (value === null || value === undefined) return 'β';+ if (typeof value === 'object') return JSON.stringify(value);+ return String(value);+}++/** One line per check, for `--json` consumers that want to grep instead. */+export function renderCompact(checks: CheckResult[]): string {+ return checks.map((check) => `${check.status}\t${check.id}\t${check.detail}`).join('\n');+}diff --git a/apps/cli/src/doctor/runner.test.ts b/apps/cli/src/doctor/runner.test.tsnew file mode 100644index 00000000000..7ceb548bcb6--- /dev/null+++ b/apps/cli/src/doctor/runner.test.ts@@ -0,0 +1,239 @@+import { describe, expect, it, vi } from 'vitest';++import { exitCodeFor, runDoctor } from './runner';+import type { CheckOutcome, DoctorCheck, DoctorOptions, DoctorReport } from './types';++const baseOptions: DoctorOptions = {+ deep: false,+ fix: false,+ offline: false,+ profile: 'core',+ strict: false,+ timeoutMs: 1000,+};++const check = (+ id: string,+ outcome: CheckOutcome,+ extra: Partial<DoctorCheck> = {},+): DoctorCheck => ({+ group: 'runtime',+ id,+ profiles: ['core'],+ run: () => outcome,+ title: id,+ ...extra,+});++const ok: CheckOutcome = { detail: 'fine', status: 'ok' };+const fail: CheckOutcome = { detail: 'broken', status: 'fail' };++describe('runDoctor', () => {+ it('skips checks whose dependency failed, instead of reporting their symptoms', async () => {+ const downstream = vi.fn(() => ok);+ const report = await runDoctor(+ [check('root', fail), check('leaf', ok, { dependsOn: ['root'], run: downstream })],+ baseOptions,+ );++ expect(downstream).not.toHaveBeenCalled();+ const leaf = report.checks.find((result) => result.id === 'leaf');+ expect(leaf?.status).toBe('skip');+ expect(leaf?.skippedBecause).toBe('root');+ });++ it('still runs checks whose dependency only warned', async () => {+ const report = await runDoctor(+ [+ check('root', { detail: 'meh', status: 'warn' }),+ check('leaf', ok, { dependsOn: ['root'] }),+ ],+ baseOptions,+ );++ expect(report.checks.find((result) => result.id === 'leaf')?.status).toBe('ok');+ });++ it('skips network checks in offline mode and deep checks without --deep', async () => {+ const report = await runDoctor(+ [check('net', ok, { network: true }), check('slow', ok, { deep: true })],+ { ...baseOptions, offline: true },+ );++ expect(report.checks.map((result) => [result.id, result.skippedBecause])).toEqual([+ ['net', '--offline'],+ ['slow', '--deep not set'],+ ]);+ });++ it('selects checks by profile, with core always included', async () => {+ const report = await runDoctor(+ [+ check('core-one', ok),+ check('connect-one', ok, { profiles: ['connect'] }),+ check('agent-one', ok, { profiles: ['agent'] }),+ ],+ { ...baseOptions, profile: 'connect' },+ );++ expect(report.checks.map((result) => result.id)).toEqual(['core-one', 'connect-one']);+ });++ it('turns a thrown check into a failure rather than crashing the run', async () => {+ const report = await runDoctor(+ [+ check('boom', ok, {+ run: () => {+ throw new Error('exploded');+ },+ }),+ check('after', ok),+ ],+ baseOptions,+ );++ expect(report.checks[0]).toMatchObject({ detail: 'exploded', status: 'fail' });+ expect(report.checks[1]?.status).toBe('ok');+ });++ it('gives a check its own budget when it declares one', async () => {+ const report = await runDoctor(+ [+ check('slow', ok, {+ budgetMs: () => 50,+ run: () => new Promise<CheckOutcome>((resolve) => setTimeout(() => resolve(ok), 500)),+ }),+ ],+ baseOptions,+ );++ expect(report.checks[0]?.status).toBe('fail');+ expect(report.checks[0]?.detail).toContain('timed out after 50ms');+ });++ it('memoizes a probe across checks', async () => {+ const load = vi.fn(async () => 'value');+ const useProbe = (): DoctorCheck['run'] => async (ctx) => {+ await ctx.probe('shared', load);+ return ok;+ };++ await runDoctor(+ [check('a', ok, { run: useProbe() }), check('b', ok, { run: useProbe() })],+ baseOptions,+ );++ expect(load).toHaveBeenCalledTimes(1);+ });++ it('re-runs a check after its repair so the report shows the repaired state', async () => {+ let broken = true;+ const report = await runDoctor(+ [+ check('fixable', ok, {+ repair: () => {+ broken = false;+ return 'unbroke it';+ },+ run: () => (broken ? { ...fail, evidence: { repairable: 'the-thing' } } : ok),+ }),+ ],+ { ...baseOptions, fix: true },+ );++ expect(report.checks[0]).toMatchObject({ repaired: 'unbroke it', status: 'ok' });+ expect(report.repairs).toEqual([{ action: 'unbroke it', id: 'fixable', ok: true }]);+ });++ it('records a repair that threw without losing the original finding', async () => {+ const report = await runDoctor(+ [+ check(+ 'fixable',+ { ...fail, evidence: { repairable: 'the-thing' } },+ {+ repair: () => {+ throw new Error('permission denied');+ },+ },+ ),+ ],+ { ...baseOptions, fix: true },+ );++ expect(report.checks[0]?.status).toBe('fail');+ expect(report.repairs).toEqual([{ action: 'permission denied', id: 'fixable', ok: false }]);+ });++ it('leaves repairs alone without --fix', async () => {+ const repair = vi.fn(() => 'nope');+ const report = await runDoctor([check('fixable', fail, { repair })], baseOptions);++ expect(repair).not.toHaveBeenCalled();+ expect(report.repairs).toBeUndefined();+ });++ it('does not invoke a repair for a finding the check did not call repairable', async () => {+ // Otherwise `--fix` reports a failed repair for every warning that simply+ // has nothing to undo, e.g. "no daemon is running".+ const repair = vi.fn(() => 'nope');+ const report = await runDoctor([check('unfixable', fail, { repair })], {+ ...baseOptions,+ fix: true,+ });++ expect(repair).not.toHaveBeenCalled();+ expect(report.repairs).toBeUndefined();+ expect(report.checks[0]?.status).toBe('fail');+ });++ it('summarises and ranks the overall status by the worst result', async () => {+ const report = await runDoctor(+ [check('a', ok), check('b', { detail: '', status: 'warn' }), check('c', fail)],+ baseOptions,+ );++ expect(report.summary).toEqual({ fail: 1, ok: 1, skip: 0, warn: 1 });+ expect(report.status).toBe('fail');+ });+});++describe('runDoctor report boundary', () => {+ it('scrubs whatever a check forgot to redact', async () => {+ const report = await runDoctor(+ [+ check('leaky', {+ detail: 'GET https://alice:[email protected] failed',+ evidence: { agentGatewayUrl: 'wss://bob:[email protected]/ws?userId=u1' },+ fix: 'mail [email protected]',+ status: 'fail',+ }),+ ],+ baseOptions,+ );++ expect(JSON.stringify(report)).not.toMatch(/hunter2|bob:pw|userId=u1|admin@example\.com/);+ });+});++describe('exitCodeFor', () => {+ const report = (status: DoctorReport['status']): DoctorReport => ({+ checks: [],+ cli: { bin: 'lh', version: '0.0.0' },+ generatedAt: '',+ profile: 'core',+ status,+ summary: { fail: 0, ok: 0, skip: 0, warn: 0 },+ });++ it('is 0 when nothing failed', () => {+ expect(exitCodeFor(report('ok'), false)).toBe(0);+ expect(exitCodeFor(report('warn'), false)).toBe(0);+ });++ it('is 1 on failure, and on warnings under --strict', () => {+ expect(exitCodeFor(report('fail'), false)).toBe(1);+ expect(exitCodeFor(report('warn'), true)).toBe(1);+ expect(exitCodeFor(report('ok'), true)).toBe(0);+ });+});diff --git a/apps/cli/src/doctor/runner.ts b/apps/cli/src/doctor/runner.tsnew file mode 100644index 00000000000..60770d5e699--- /dev/null+++ b/apps/cli/src/doctor/runner.ts@@ -0,0 +1,198 @@+import { cliVersion } from '../pkg';+import { scrubDeep } from './redact';+import type {+ CheckResult,+ CheckStatus,+ DoctorCheck,+ DoctorContext,+ DoctorOptions,+ DoctorReport,+} from './types';++/** A check body that hangs must not hang `lh doctor`. */+async function withTimeout<T>(+ run: () => Promise<T> | T,+ timeoutMs: number,+ label: string,+): Promise<T> {+ let timer: NodeJS.Timeout | undefined;+ try {+ return await Promise.race([+ Promise.resolve().then(run),+ new Promise<never>((_, reject) => {+ timer = setTimeout(+ () => reject(new Error(`${label} timed out after ${timeoutMs}ms`)),+ timeoutMs,+ );+ }),+ ]);+ } finally {+ if (timer) clearTimeout(timer);+ }+}++function isSelected(check: DoctorCheck, profile: DoctorOptions['profile']): boolean {+ if (profile === 'all') return true;+ // `core` is the baseline: its checks run under every profile.+ return check.profiles.includes('core') || check.profiles.includes(profile);+}++/**+ * Why this check cannot run right now, or undefined when it can.+ *+ * A dependency that failed or was skipped short-circuits everything behind it:+ * reporting "credentials rejected" when the server was never reachable sends+ * the user after the wrong problem, which is the failure mode doctor exists to+ * remove.+ */+function skipReason(+ check: DoctorCheck,+ options: DoctorOptions,+ results: Map<string, CheckResult>,+): string | undefined {+ if (check.network && options.offline) return '--offline';+ if (check.deep && !options.deep) return '--deep not set';++ for (const dependency of check.dependsOn ?? []) {+ const upstream = results.get(dependency);+ if (!upstream) return dependency;+ if (upstream.status === 'fail' || upstream.status === 'skip') return dependency;+ }++ return undefined;+}++function worstStatus(results: CheckResult[]): DoctorReport['status'] {+ if (results.some((r) => r.status === 'fail')) return 'fail';+ if (results.some((r) => r.status === 'warn')) return 'warn';+ return 'ok';+}++export function summarize(results: CheckResult[]): Record<CheckStatus, number> {+ const summary: Record<CheckStatus, number> = { fail: 0, ok: 0, skip: 0, warn: 0 };+ for (const result of results) summary[result.status] += 1;+ return summary;+}++/**+ * The exit code contract: 0 when nothing failed, 1 when something did.+ * `--strict` promotes warnings to failures. Nothing else is expressed through+ * the exit code β a caller that needs detail reads `--json`.+ */+export function exitCodeFor(report: DoctorReport, strict: boolean): number {+ if (report.status === 'fail') return 1;+ if (strict && report.status === 'warn') return 1;+ return 0;+}++export async function runDoctor(+ checks: readonly DoctorCheck[],+ options: DoctorOptions,+): Promise<DoctorReport> {+ const results = new Map<string, CheckResult>();+ const probes = new Map<string, Promise<unknown>>();+ const repairs: NonNullable<DoctorReport['repairs']> = [];++ const ctx: DoctorContext = {+ options,+ probe: <T>(key: string, load: () => Promise<T>): Promise<T> => {+ const existing = probes.get(key);+ if (existing) return existing as Promise<T>;+ const started = load();+ probes.set(key, started);+ return started;+ },+ result: (id) => results.get(id),+ };++ const execute = async (check: DoctorCheck): Promise<CheckResult> => {+ const startedAt = Date.now();+ try {+ const outcome = await withTimeout(+ () => check.run(ctx),+ // Local checks share the default budget; they never approach it.+ check.budgetMs?.(options) ?? options.timeoutMs,+ check.title,+ );+ return {+ ...outcome,+ durationMs: Date.now() - startedAt,+ group: check.group,+ id: check.id,+ title: check.title,+ };+ } catch (error) {+ return {+ detail: error instanceof Error ? error.message : String(error),+ durationMs: Date.now() - startedAt,+ fix: 'Re-run with --verbose for the full error.',+ group: check.group,+ id: check.id,+ status: 'fail',+ title: check.title,+ };+ }+ };++ for (const check of checks) {+ if (!isSelected(check, options.profile)) continue;++ const skipped = skipReason(check, options, results);+ if (skipped) {+ results.set(check.id, {+ detail: `Not run (${skipped}).`,+ durationMs: 0,+ group: check.group,+ id: check.id,+ skippedBecause: skipped,+ status: 'skip',+ title: check.title,+ });+ continue;+ }++ let result = await execute(check);++ // `evidence.repairable` is the check's own statement that this finding is+ // actionable. Without it, a warning like "no daemon is running" would+ // otherwise invoke a repair that has nothing to undo.+ const repairable =+ options.fix &&+ check.repair &&+ (result.status === 'fail' || result.status === 'warn') &&+ Boolean(result.evidence?.repairable);++ if (repairable) {+ try {+ const action = await check.repair(ctx, result);+ repairs.push({ action: scrubDeep(action), id: check.id, ok: true });+ // Re-run so the report describes the world after the repair, not before.+ result = { ...(await execute(check)), repaired: action };+ } catch (error) {+ repairs.push({+ action: scrubDeep(error instanceof Error ? error.message : String(error)),+ id: check.id,+ ok: false,+ });+ }+ }++ // The report exists to be pasted into an issue. Scrub centrally rather than+ // trusting every check to redact everything it touches: error messages from+ // fetch and the gateway client quote URLs, and evidence copies config+ // verbatim, in more places than per-check redaction ever caught.+ results.set(check.id, scrubDeep(result));+ }++ const checkResults = [...results.values()];++ return {+ checks: checkResults,+ cli: { bin: process.argv[1] ?? 'lh', version: cliVersion },+ generatedAt: new Date().toISOString(),+ profile: options.profile,+ ...(repairs.length > 0 ? { repairs } : {}),+ status: worstStatus(checkResults),+ summary: summarize(checkResults),+ };+}diff --git a/apps/cli/src/doctor/testUtils.ts b/apps/cli/src/doctor/testUtils.tsnew file mode 100644index 00000000000..6290f3f029f--- /dev/null+++ b/apps/cli/src/doctor/testUtils.ts@@ -0,0 +1,42 @@+import type { CheckOutcome, DoctorCheck, DoctorContext, DoctorOptions } from './types';++/** Minimal context for exercising a single check in isolation. */+export function makeContext(options: Partial<DoctorOptions> = {}): DoctorContext {+ const cache = new Map<string, Promise<unknown>>();++ return {+ options: {+ deep: false,+ fix: false,+ offline: false,+ profile: 'all',+ strict: false,+ timeoutMs: 1000,+ ...options,+ },+ probe: <T>(key: string, load: () => Promise<T>): Promise<T> => {+ const existing = cache.get(key);+ if (existing) return existing as Promise<T>;+ const started = load();+ cache.set(key, started);+ return started;+ },+ result: () => undefined,+ };+}++export function runCheck(+ checks: readonly DoctorCheck[],+ id: string,+ ctx: DoctorContext = makeContext(),+): Promise<CheckOutcome> {+ const check = checks.find((candidate) => candidate.id === id);+ if (!check) throw new Error(`No such check: ${id}`);+ return Promise.resolve(check.run(ctx));+}++export function findCheck(checks: readonly DoctorCheck[], id: string): DoctorCheck {+ const check = checks.find((candidate) => candidate.id === id);+ if (!check) throw new Error(`No such check: ${id}`);+ return check;+}diff --git a/apps/cli/src/doctor/types.ts b/apps/cli/src/doctor/types.tsnew file mode 100644index 00000000000..731913548e2--- /dev/null+++ b/apps/cli/src/doctor/types.ts@@ -0,0 +1,154 @@+/**+ * `lh doctor` β one command that walks the whole chain, from this process up to+ * a real agent round trip, and says which link is broken.+ *+ * Every check is a small, independent unit with an id, a group, the profiles it+ * belongs to, and the checks it cannot run without. The runner owns ordering,+ * skipping and timeouts so a check body only has to answer one question.+ */++export type CheckStatus = 'ok' | 'warn' | 'fail' | 'skip';++/** Layers of the chain, reported (and rendered) in this order. */+export type CheckGroup =+ 'runtime' | 'endpoints' | 'credentials' | 'scope' | 'context' | 'server' | 'device' | 'execution';++export const CHECK_GROUP_ORDER: readonly CheckGroup[] = [+ 'runtime',+ 'endpoints',+ 'credentials',+ 'scope',+ 'context',+ 'server',+ 'device',+ 'execution',+];++export const CHECK_GROUP_TITLES: Record<CheckGroup, string> = {+ context: 'Run context',+ credentials: 'Credentials',+ device: 'Device gateway',+ endpoints: 'Endpoints',+ execution: 'Execution',+ runtime: 'Runtime',+ scope: 'Workspace scope',+ server: 'Server',+};++/**+ * `core` runs on a bare `lh doctor`: fast, cheap and useful without knowing+ * what you are debugging. The rest are opt-in via `--profile`.+ */+export type SelectableProfile = 'core' | 'connect' | 'agent' | 'hetero' | 'selfhost';+export type DoctorProfile = SelectableProfile | 'all';++export const SELECTABLE_PROFILES: readonly SelectableProfile[] = [+ 'core',+ 'connect',+ 'agent',+ 'hetero',+ 'selfhost',+];++export const DOCTOR_PROFILES: readonly DoctorProfile[] = [...SELECTABLE_PROFILES, 'all'];++/** What a check body returns. */+export interface CheckOutcome {+ /** One line, the finding itself. */+ detail: string;+ /**+ * Structured facts a script can assert on; never contains secrets.+ *+ * A `repairable` key is the check's signal that THIS finding is one `--fix`+ * can act on, and which one it is: a check that detects several broken states+ * repairs only the state it actually found. Without it the runner leaves the+ * finding alone, so a warning nobody can fix produces no failed-repair noise.+ */+ evidence?: Record<string, unknown> & { repairable?: string };+ /** What the user should do about it. */+ fix?: string;+ /**+ * Why a check excluded itself β a missing `--agent`, an inapplicable+ * platform. Runner-level skips (`--offline`, a failed dependency) set this+ * too, so a caller never has to guess why a check produced no finding.+ */+ skippedBecause?: string;+ status: CheckStatus;+}++export interface CheckResult extends CheckOutcome {+ durationMs: number;+ group: CheckGroup;+ id: string;+ /** Set when `--fix` changed something before this result was produced. */+ repaired?: string;+ title: string;+}++export interface DoctorOptions {+ /** Agent id or slug to check execution readiness against. */+ agent?: string;+ /** Run the expensive / side-effecting checks. */+ deep: boolean;+ /** Apply the repairs the failing checks know how to apply. */+ fix: boolean;+ /** Extra heterogeneous agent types to probe, beyond the defaults. */+ hetero?: string[];+ /** Skip every check that would touch the network. */+ offline: boolean;+ profile: DoctorProfile;+ /** Treat warnings as failures for the exit code. */+ strict: boolean;+ /** Per-check budget for anything that talks to the network. */+ timeoutMs: number;+}++export interface DoctorContext {+ options: DoctorOptions;+ /**+ * Memoized cross-check probe. Several checks read the same server response;+ * the loader for a given key runs at most once per `lh doctor` invocation.+ */+ probe: <T>(key: string, load: () => Promise<T>) => Promise<T>;+ /** An already-produced result, for checks that build on an earlier finding. */+ result: (id: string) => CheckResult | undefined;+}++export interface DoctorCheck {+ /**+ * Time this check may take, when `--timeout` is the wrong budget for it β+ * a check that waits on a model needs minutes where a health probe needs+ * seconds. Defaults to `options.timeoutMs`.+ */+ budgetMs?: (options: DoctorOptions) => number;+ /** Only runs with `--deep`: slow, costly, or it starts a real run. */+ deep?: boolean;+ /** Ids whose failure (or skip) makes this check unrunnable. */+ dependsOn?: readonly string[];+ group: CheckGroup;+ id: string;+ /** Talks to the network β excluded by `--offline`. */+ network?: boolean;+ profiles: readonly SelectableProfile[];+ /**+ * Undo the specific broken state this check detects. Runs only under `--fix`,+ * only when the check did not pass AND reported `evidence.repairable`, and+ * the check is re-run afterwards so the report shows the post-repair truth.+ * Returns what it did.+ */+ repair?: (ctx: DoctorContext, result: CheckResult) => Promise<string> | string;+ run: (ctx: DoctorContext) => Promise<CheckOutcome> | CheckOutcome;+ title: string;+}++export interface DoctorReport {+ checks: CheckResult[];+ cli: { bin: string; version: string };+ generatedAt: string;+ profile: DoctorProfile;+ /** Present when `--fix` ran; one line per attempted repair. */+ repairs?: { action: string; id: string; ok: boolean }[];+ /** Worst status across the checks. */+ status: 'ok' | 'warn' | 'fail';+ summary: Record<CheckStatus, number>;+}diff --git a/apps/cli/src/pkg.ts b/apps/cli/src/pkg.tsindex 903e5c54d4d..01f885308a8 100644--- a/apps/cli/src/pkg.ts+++ b/apps/cli/src/pkg.ts@@ -10,7 +10,13 @@ import { createRequire } from 'node:module';* the path outside the package once everything is bundled into a single file.*/const require = createRequire(import.meta.url);-const pkg = require('../package.json') as { name: string; version: string };+const pkg = require('../package.json') as {+ engines?: { node?: string };+ name: string;+ version: string;+};export const cliPackageName = pkg.name;export const cliVersion = pkg.version;+/** The node range this build is published for, e.g. `>=22.15`. */+export const cliNodeEngine = pkg.engines?.node;diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.tsindex c1d8db7ef13..6ee61b4954d 100644--- a/apps/cli/src/program.ts+++ b/apps/cli/src/program.ts@@ -10,6 +10,7 @@ import { registerConfigCommand } from './commands/config';import { registerConnectCommand } from './commands/connect';import { registerDeviceCommand } from './commands/device';import { registerDocCommand } from './commands/doc';+import { registerDoctorCommand } from './commands/doctor';import { registerEvalCommand } from './commands/eval';import { registerFileCommand } from './commands/file';import { registerGenerateCommand } from './commands/generate';@@ -80,6 +81,7 @@ export function createProgram() {registerConnectCommand(program);registerDeviceCommand(program);registerStatusCommand(program);+ registerDoctorCommand(program);registerDocCommand(program);registerSearchCommand(program);registerKbCommand(program);