Skip to content

🤯 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.

4.0 KB
Raw Blame
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 {
  describeDeviceGateway,
  describeDeviceGatewayFailure,
  rememberGatewayOverride,
  resolveCliDeviceGateway,
} from '../device/gatewayEndpoint';
import { log, setVerbose } from '../utils/logger';
import { warnStaleConnectors } from './connectStatus';

/**
 * `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;
  timeout?: string;
  token?: string;
  userId?: string;
  verbose?: boolean;
}

export function registerStatusCommand(program: Command) {
  program
    .command('status')
    .description('Check if gateway connection can be established')
    .option('--token <jwt>', 'JWT access token')
    .option('--service-token <token>', 'Service token (requires --user-id)')
    .option('--user-id <id>', 'User ID (required with --service-token)')
    .option('--gateway <url>', 'Device gateway URL')
    .option('--timeout <ms>', 'Connection timeout in ms', '10000')
    .option('-v, --verbose', 'Enable verbose logging')
    .action(async (options: StatusOptions) => {
      if (options.verbose) setVerbose(true);

      // This probe opens its own connection, so a pass says nothing about the code a
      // running connector executes. Flag that first; it must never block the probe.
      await warnStaleConnectors().catch((error) =>
        log.debug(`Connector version check skipped: ${(error as Error).message}`),
      );

      const auth = await resolveToken(options);
      // Same resolution as `connect`, against the server this token belongs to.
      const gateway = await resolveCliDeviceGateway({
        override: options.gateway,
        serverUrl: auth.serverUrl,
      });

      if (!gateway.ok) {
        const { detail, fix } = describeDeviceGatewayFailure(gateway, auth.serverUrl);
        log.error(`FAILED - ${detail}`);
        log.error(fix);
        process.exit(1);
        throw new Error('process.exit');
      }

      rememberGatewayOverride(auth.serverUrl, gateway.endpoint);
      log.info(`Gateway: ${describeDeviceGateway(gateway.endpoint)}`);

      const timeout = Number.parseInt(options.timeout || '10000', 10);

      const client = new GatewayClient({
        autoReconnect: false,
        gatewayUrl: gateway.endpoint.url,
        logger: log,
        serverUrl: auth.serverUrl,
        // Status is a one-shot probe, not a serving connection.
        tunnel: false,
        token: auth.token,
        tokenType: auth.tokenType,
        userId: auth.userId,
      });

      const timer = setTimeout(() => {
        log.error('FAILED - Connection timed out');
        log.error(DIAGNOSE_HINT);
        client.disconnect();
        process.exit(1);
      }, timeout);

      client.on('connected', () => {
        clearTimeout(timer);
        log.info('CONNECTED');
        client.disconnect();
        process.exit(0);
      });

      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);
      });

      client.on('error', (error) => {
        log.error(`Connection error: ${error.message}`);
      });

      await client.connect();
    });
}