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.

43.5 KB
Raw Blame
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';

import {
  defaultGetLocalFilePreview,
  defaultGetProjectFileIndex,
  defaultSearchProjectFiles,
  type DeviceControlDeps,
  DeviceMetricsSampler,
  pushMetrics,
} from '@lobechat/device-control';
import { createTerminalDeps, TerminalSessionManager } from '@lobechat/device-control/terminal';
import { GatewayClient } from '@lobechat/device-gateway-client';
import { listHeterogeneousAgentModels } from '@lobechat/heterogeneous-agents/models';
import { createRuntimeProbeCache } from '@lobechat/heterogeneous-agents/runtimeProbeCache';
import type { Command } from 'commander';

import { createLambdaClient } from '../../api/client';
import { scheduleProactiveRefresh } from '../../auth/proactiveRefresh';
import { resolveToken } from '../../auth/resolveToken';
import { CLI_API_KEY_ENV } from '../../constants/auth';
import {
  CLI_CONNECT_SERVICE_NAME,
  CLI_DISPLAY_NAME,
  CLI_PRIMARY_BIN,
} from '../../constants/identity';
import { getCliInstallationPath } from '../../daemon/installation';
import { CliMaintenance } from '../../daemon/maintenance';
import {
  appendLog,
  getLogPath,
  getRunningDaemonPid,
  isProcessAlive,
  removePid,
  removeStatus,
  reportDaemonStartupReady,
  spawnDaemon,
  stopDaemon,
  stopDaemonAndWait,
  writeStatus,
} from '../../daemon/manager';
import { listTasks } from '../../daemon/taskRegistry';
import { ActivityReporter } from '../../device/activityHook';
import {
  describeDeviceGateway,
  describeDeviceGatewayFailure,
  rememberGatewayOverride,
  resolveCliDeviceGateway,
} from '../../device/gatewayEndpoint';
import { MANAGED_GATEWAY_ENV } from '../../device/managed';
import { disposeDeviceMcp, listDeviceMcpTools } from '../../device/mcp';
import {
  mintWorkspaceConnectToken,
  registerDevice,
  registerWorkspaceDevice,
  resolveDeviceIdentity,
  resolveWorkspaceDeviceIdentity,
} from '../../device/register';
import { probeNativeRuntimes } from '../../device/systemInfo';
import { redactUrlCredentials } from '../../doctor/redact';
import { cliVersion } from '../../pkg';
import {
  CONNECT_RETRYABLE_EXIT_CODE,
  getWorkspaceFailureExitCode,
  installConnectService,
  startConnectService,
  stopConnectService,
  uninstallConnectService,
} from '../../service/connect';
import { getServiceRestartCommand, readConnectServices } from '../../service/status';
import {
  addWorkspaceEnrollment,
  loadOrCreateConnectionId,
  loadWorkspaceEnrollments,
  removeWorkspaceEnrollment,
  resolveDeviceMetricsBacklogPath,
} from '../../settings';
import { closeBrowserSessions, resolveBrowserDevice } from '../../tools/browser';
import { resolveComputerUseDevice } from '../../tools/computerUse';
import { cleanupAllProcesses, getActiveShellCount } from '../../tools/shell';
import { log, setVerbose } from '../../utils/logger';
import { sweepLocalTraces } from '../../utils/traceMaintenance';
import { restartConnector } from '../connectRestart';
import { printConnectStatus } from '../connectStatus';
import { bindGatewayClientHandlers, type GatewayHandlerContext } from './handlers';
import { getManagedFlagConflicts, startManagedDevice } from './managed';

/** Longest a clean stop waits to push pending device health samples. */
const SHUTDOWN_METRICS_FLUSH_MS = 3000;
const CONNECT_SERVICE_NAME = CLI_CONNECT_SERVICE_NAME;

interface ConnectOptions {
  /** `agent-browser` binary for the browser tool; see `resolveBrowserDevice`. */
  agentBrowser?: string;
  /** `auv` binary that runs Computer Use on this device; see `resolveComputerUseDevice`. */
  auv?: string;
  daemon?: boolean;
  daemonChild?: boolean;
  deviceId?: string;
  gateway?: string;
  /** Run as a managed cloud device; identity and credentials come from the environment. */
  managed?: boolean;
  manager?: string;
  /** With --workspace: enroll into the shared pool visible to every member (default: private). */
  public?: boolean;
  serviceChild?: boolean;
  token?: string;
  verbose?: boolean;
  /** Enroll this machine as a device of the given workspace (workspace members). */
  workspace?: string;
}

export function registerConnectCommand(program: Command) {
  const connectCmd = program
    .command('connect')
    .description('Connect to the device gateway and listen for tool calls')
    .option('--token <jwt>', 'JWT access token')
    .option('--gateway <url>', 'Device gateway URL')
    .option('--device-id <id>', 'Device ID (auto-generated if not provided)')
    .option('--workspace <id>', 'Enroll as a device of this workspace (workspace members)')
    .option(
      '--public',
      'With --workspace: enroll into the shared pool visible to every member (default: private, visible only to you)',
    )
    .option(
      '--managed',
      'Run as a managed cloud device: read the device id, secret, server and gateway from LOBEHUB_MANAGED_DEVICE_ID, LOBEHUB_MANAGED_DEVICE_SECRET, LOBEHUB_SERVER and LOBEHUB_DEVICE_GATEWAY_URL',
    )
    .option('--auv <binary>', 'Offer Computer Use by running this AUV binary (`auv invoke`)')
    .option(
      '--agent-browser <binary>',
      'Run the browser tool with this agent-browser binary (default: agent-browser on PATH)',
    )
    .option('-v, --verbose', 'Enable verbose logging')
    .option('-d, --daemon', 'Run as a background daemon process')
    .option('--daemon-child', 'Internal: runs as the daemon child process')
    .option('--service-child', 'Internal: runs as the system service child process')
    .action(async (options: ConnectOptions) => {
      if (options.verbose) setVerbose(true);

      if (options.managed) {
        const conflicts = getManagedFlagConflicts(options);
        if (conflicts.length > 0) {
          log.error(`--managed cannot be combined with ${conflicts.join(', ')}.`);
          process.exit(1);
          return;
        }
      }

      // --daemon: spawn detached child and exit
      if (options.daemon) {
        return handleDaemonStart(options);
      }

      const isServiceChild = options.serviceChild || process.env.LOBEHUB_CONNECT_SERVICE === '1';
      if (isServiceChild) process.env.LOBEHUB_CONNECT_SERVICE = '1';
      const isDaemonChild =
        options.daemonChild || isServiceChild || process.env.LOBEHUB_DAEMON === '1';

      await runConnect(options, isDaemonChild);
    });

  // Capability discovery runs without login or opening a gateway connection. Desktop
  // invokes its bundled CLI here so the probe and subsequent dispatch share a runtime.
  connectCmd
    .command('capabilities')
    .description('Report native agent runtimes supported by this CLI and installed binaries')
    .action(async () => {
      console.log(JSON.stringify({ supportedAgentRuntimes: await probeNativeRuntimes() }));
    });

  // Subcommands
  connectCmd.command('stop').description('Stop the background daemon process').action(handleStop);

  connectCmd
    .command('status')
    .description('Show connection, running version, and any required action')
    .option('-v, --verbose', 'Include service details and installation paths')
    .action((options: { verbose?: boolean }, command: Command) =>
      printConnectStatus({ verbose: options.verbose || command.optsWithGlobals().verbose }),
    );

  connectCmd
    .command('logs')
    .description('Tail the daemon log file')
    .option('-n, --lines <count>', 'Number of lines to show', '50')
    .option('-f, --follow', 'Follow log output')
    .action(async (opts: { follow?: boolean; lines?: string }) => {
      const logPath = getLogPath();
      if (!fs.existsSync(logPath)) {
        log.warn('No log file found. Start the daemon first.');
        return;
      }

      const lines = opts.lines || '50';
      const args = [`-n`, lines];
      if (opts.follow) args.push('-f');

      // Use tail directly β€” this hands control to the child process
      try {
        const { execFileSync } = await import('node:child_process');
        execFileSync('tail', [...args, logPath], { stdio: 'inherit' });
      } catch {
        // tail -f exits via SIGINT, which throws β€” that's fine
      }
    });

  connectCmd
    .command('restart')
    .description('Restart the detected daemon or systemd connect service')
    .option('--manager <manager>', 'Choose a connector when multiple exist: daemon, user, system')
    .option('--token <jwt>', 'JWT access token')
    .option('--gateway <url>', 'Device gateway URL')
    .option('--device-id <id>', 'Device ID')
    .option('--auv <binary>', 'Offer Computer Use by running this AUV binary (`auv invoke`)')
    .option(
      '--agent-browser <binary>',
      'Run the browser tool with this agent-browser binary (default: agent-browser on PATH)',
    )
    .option('-v, --verbose', 'Enable verbose logging')
    .action((_options: ConnectOptions, command: Command) => {
      const options = command.optsWithGlobals<ConnectOptions>();
      return restartConnector(options, async () => {
        const wasStopped = await stopDaemonAndWait();
        if (wasStopped) log.info('Stopped existing daemon.');
        await handleDaemonStart({ ...options, daemon: true });
      });
    });

  const serviceCmd = connectCmd
    .command('service')
    .description('Inspect Linux connect services and manage the user-level systemd service');

  serviceCmd
    .command('install')
    .description('Install and start the Linux user systemd connect service')
    .option('--workspace <id>', 'Enroll as a device of this workspace (workspace members)')
    .option(
      '--public',
      'With --workspace: enroll into the shared pool visible to every member (default: private, visible only to you)',
    )
    // TODO: `--auv` is not forwarded to the service unit; add it when a service-mode device needs Computer Use.
    .action((options: Pick<ConnectOptions, 'public' | 'workspace'>) => {
      installConnectService({ public: options.public, workspace: options.workspace });
      log.info(
        options.workspace
          ? `Installed and started ${CONNECT_SERVICE_NAME} for workspace ${options.workspace}.`
          : `Installed and started ${CONNECT_SERVICE_NAME}.`,
      );
      log.info("Run 'lh connect service status' to inspect the service.");
    });

  serviceCmd
    .command('uninstall')
    .description('Remove the Linux user systemd connect service')
    .action(() => {
      const removed = uninstallConnectService();
      if (removed) log.info(`Uninstalled ${CONNECT_SERVICE_NAME}.`);
      else
        log.warn(
          "No user-level connect service is installed. Run 'lh connect service status' to check for a system-level service.",
        );
    });

  serviceCmd
    .command('start')
    .description('Start the installed connect service')
    .action(() => {
      const started = startConnectService();
      if (started) log.info(`Started ${CONNECT_SERVICE_NAME}.`);
      else
        log.warn(
          "No user-level connect service is installed. Run 'lh connect service status' to check for a system-level service.",
        );
    });

  serviceCmd
    .command('stop')
    .description('Stop the installed connect service')
    .action(() => {
      const stopped = stopConnectService();
      if (stopped) log.info(`Stopped ${CONNECT_SERVICE_NAME}.`);
      else
        log.warn(
          "No user-level connect service is installed. Run 'lh connect service status' to check for a system-level service.",
        );
    });

  serviceCmd
    .command('restart')
    .description(
      'Restart the user-level connect service (alias for connect restart --manager user)',
    )
    .action(() => restartConnector({ manager: 'user' }, async () => {}));

  serviceCmd
    .command('status')
    .description('Show user-level and system-level connect service status')
    .option('-v, --verbose', 'Include service details and installation paths')
    .action((options: { verbose?: boolean }, command: Command) =>
      printConnectStatus({
        servicesOnly: true,
        verbose: options.verbose || command.optsWithGlobals().verbose,
      }),
    );

  // Top-level alias for `connect stop`. Users who run `lh connect` naturally
  // reach for `lh disconnect` to undo it; the nested `connect stop` is not
  // discoverable enough on its own.
  program
    .command('disconnect')
    .description('Disconnect from the device gateway (alias for `connect stop`)')
    .action(handleStop);
}

// --- Internal helpers ---

function handleStop() {
  const stopped = stopDaemon();
  if (stopped) {
    log.info('Daemon stopped.');
  } else {
    log.warn('No daemon is running.');
  }
}

async function handleDaemonStart(options: ConnectOptions) {
  const { services } = await readConnectServices();
  const runningService = services.find((service) => service.active || service.mainPid);
  if (runningService) {
    log.error(
      `A ${runningService.scope}-level connect service is already running. After active tasks finish, restart it with: ${getServiceRestartCommand(runningService)}`,
    );
    process.exitCode = 1;
    return;
  }
  const existingPid = getRunningDaemonPid();
  if (existingPid !== null) {
    log.error(`Daemon is already running (PID ${existingPid}).`);
    log.error("Use 'lh connect stop' to stop it, or 'lh connect restart' to restart.");
    process.exit(1);
  }

  // Build args to re-run with --daemon-child
  const args = buildDaemonArgs(options);
  const pid = await spawnDaemon(args);

  log.info(`Daemon started (PID ${pid}).`);
  log.info(`  Logs: ${getLogPath()}`);
  log.info("  Run 'lh connect status' to check connection.");
  log.info("  Run 'lh connect stop' to stop.");
}

function buildDaemonArgs(options: ConnectOptions): string[] {
  // Find the entry script (process.argv[1])
  const script = process.argv[1];
  const args = [script, 'connect'];

  if (options.token) args.push('--token', options.token);
  if (options.gateway) args.push('--gateway', options.gateway);
  if (options.deviceId) args.push('--device-id', options.deviceId);
  if (options.workspace) args.push('--workspace', options.workspace);
  if (options.public) args.push('--public');
  if (options.managed) args.push('--managed');
  if (options.auv) args.push('--auv', path.resolve(options.auv));
  if (options.agentBrowser) args.push('--agent-browser', path.resolve(options.agentBrowser));
  if (options.verbose) args.push('--verbose');

  return args;
}

async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
  const info = (msg: string) => {
    if (isDaemonChild) appendLog(msg);
    else log.info(msg);
  };

  const error = (msg: string) => {
    if (isDaemonChild) appendLog(`[ERROR] ${msg}`);
    else log.error(msg);
  };

  const debug = (msg: string) => {
    if (!isDaemonChild) log.debug(msg);
    else if (options.verbose) appendLog(`[DEBUG] ${msg}`);
  };

  // Managed cloud device: identity, server, gateway and credentials all come
  // from the environment the platform injected; the stored login is unused.
  const managed = options.managed ? await startManagedDevice({ debug, error, info }) : undefined;

  const unavailableExitCode = options.workspace ? CONNECT_RETRYABLE_EXIT_CODE : undefined;
  let auth = managed ? managed.auth : await resolveToken({ ...options, unavailableExitCode });

  // Resolved once per process, against the server the token belongs to. The
  // client's own reconnects and every workspace share connection reuse it.
  const gateway = managed
    ? ({ endpoint: { source: 'override', url: managed.config.gatewayUrl }, ok: true } as const)
    : await resolveCliDeviceGateway({
        override: options.gateway,
        serverUrl: auth.serverUrl,
      });
  if (!gateway.ok) {
    const { detail, fix } = describeDeviceGatewayFailure(gateway, auth.serverUrl);
    // Thrown, so a daemon parent reports it as the startup error too.
    throw new Error(`${detail} ${fix}`);
  }
  const resolvedGatewayUrl = gateway.endpoint.url;
  const gatewayDescription = managed
    ? `${redactUrlCredentials(resolvedGatewayUrl)} (${MANAGED_GATEWAY_ENV})`
    : describeDeviceGateway(gateway.endpoint);
  if (!managed && rememberGatewayOverride(auth.serverUrl, gateway.endpoint)) {
    info(
      `Saved ${resolvedGatewayUrl} as the device gateway for ${auth.serverUrl}; later runs use it ahead of the server's own address.`,
    );
  }

  // Fail before connecting rather than advertise a tool this device cannot run.
  const computerUse = await resolveComputerUseDevice(options.auv).catch((err: Error) => {
    log.error(err.message);
    process.exit(1);
    throw err;
  });
  const browser = await resolveBrowserDevice(options.agentBrowser).catch((err: Error) => {
    log.error(err.message);
    process.exit(1);
    throw err;
  });
  if (browser) info(`Browser tool enabled via ${browser.binaryPath}`);

  // Workspace enrollment: the device joins a workspace pool (reachable by all
  // members) instead of the personal pool. It authenticates with a minted
  // workspace-device token (carrying the `workspace_id` claim) and uses a
  // workspace-derived deviceId. `auth` stays the admin's identity β€” used only to
  // (re-)mint the connect token and register the row.
  const workspaceId = options.workspace;
  // The gateway principal of a managed device: its token's workspace, or its owner.
  const managedWorkspaceId = managed?.principal.workspaceId;

  // Resolve a stable device identity. An explicit `--device-id` wins (lets a
  // user pin a VM to a fixed identity); otherwise derive from the machine id so
  // the same machine maps to one device across reconnects.
  // A managed device has no derived identity: the platform registered its row
  // and fixed its id, so it never registers itself.
  const identity = managed
    ? undefined
    : workspaceId
      ? resolveWorkspaceDeviceIdentity(workspaceId, options.deviceId, loadOrCreateConnectionId())
      : resolveDeviceIdentity(auth.userId, options.deviceId);
  const deviceId = managed?.config.deviceId ?? identity?.deviceId ?? options.deviceId;

  // The token the gateway socket authenticates with. Re-minted on refresh for
  // workspace devices (see `refreshConnectToken`).
  let connectToken = auth.token;
  let connectTokenType: 'apiKey' | 'jwt' | 'serviceToken' = auth.tokenType;
  if (workspaceId) {
    try {
      const minted = await mintWorkspaceConnectToken(auth, workspaceId);
      connectToken = minted.token;
    } catch (err) {
      log.error(`Workspace connect token mint failed: ${(err as Error).message}`);
      process.exit(getWorkspaceFailureExitCode(err));
      throw new Error('process.exit', { cause: err });
    }
    connectTokenType = 'jwt';
  }

  // Re-resolve the admin auth and, for workspace mode, re-mint the connect token.
  const refreshConnectToken = async (): Promise<string | undefined> => {
    // `refreshNow` reports the new token through `onToken`, which updates
    // `auth`, `connectToken` and the client.
    if (managed) return (await managed.session.refreshNow()).token;
    const refreshed = await resolveToken({ unavailableExitCode });
    if (!refreshed) return undefined;
    auth = refreshed;
    if (workspaceId) {
      const minted = await mintWorkspaceConnectToken(auth, workspaceId);
      connectToken = minted.token;
      return connectToken;
    }
    connectToken = refreshed.token;
    return connectToken;
  };

  // Freeform channel label (`cli` by default); `LOBEHUB_CLI_CHANNEL` lets a
  // dev build tag itself `cli-dev` so the gateway can prioritise / display it.
  const channel = process.env.LOBEHUB_CLI_CHANNEL || 'cli';

  const client = new GatewayClient({
    channel,
    connectionId: loadOrCreateConnectionId(),
    deviceId,
    gatewayUrl: resolvedGatewayUrl,
    logger: isDaemonChild ? createDaemonLogger() : log,
    serverUrl: auth.serverUrl,
    token: connectToken,
    tokenType: connectTokenType,
    userId: managed ? managed.principal.userId : workspaceId ? undefined : auth.userId,
    workspaceId: managed ? managedWorkspaceId : workspaceId,
  });

  if (managed) {
    // Only the next (re)connection authenticates with the token, so a refresh
    // never closes the socket: tool calls, agent runs and tunnels keep running.
    managed.events.onToken = (token) => {
      connectToken = token.token;
      auth = { ...auth, token: token.token };
      client.updateToken(token.token);
      debug('Refreshed the managed device token');
    };
    managed.events.onFatal = (err) => exitManaged(err.message);
  }

  // Print device info
  info(`─── ${CLI_DISPLAY_NAME} ───`);
  info(`  Device ID : ${client.currentDeviceId}`);
  info(`  Hostname  : ${os.hostname()}`);
  info(`  Platform  : ${process.platform}`);
  info(`  Gateway   : ${gatewayDescription}`);
  info(`  Auth      : ${managed ? 'managed device token' : auth.tokenType}`);
  if (managed) {
    info(
      `  Principal : ${managedWorkspaceId ? `workspace ${managedWorkspaceId}` : `user ${managed.principal.userId}`}`,
    );
  }
  info(`  Mode      : ${isDaemonChild ? 'daemon' : 'foreground'}`);
  info('───────────────────');

  // Update local connection status so other CLI commands can resolve the current device
  const cliPath = await getCliInstallationPath();
  let connectionStatus = 'connecting';
  let lastRequestAt: string | undefined;
  const updateStatus = (status: string) => {
    connectionStatus = status;
    writeStatus({
      cliPath,
      cliVersion,
      connectionStatus,
      deviceId: client.currentDeviceId,
      gatewaySource: gateway.endpoint.source,
      gatewayUrl: resolvedGatewayUrl,
      lastRequestAt,
      pid: process.pid,
      startedAt: startedAt.toISOString(),
    });
  };
  const recordRequest = () => {
    lastRequestAt = new Date().toISOString();
    updateStatus(connectionStatus);
  };

  const startedAt = new Date();
  updateStatus('connecting');

  // Housekeeping for the local trace store: partials left behind by killed
  // agent processes become `interrupted` snapshots (so `lh trace op list` shows
  // the crashed runs), and aged-out snapshots are deleted. Fire-and-forget β€”
  // it must never delay the gateway connection.
  void sweepLocalTraces().then(({ deleted, reconciled }) => {
    if (reconciled > 0 || deleted > 0) {
      info(`  Traces    : ${reconciled} interrupted run(s) closed, ${deleted} expired removed`);
    }
  });

  // Platform handlers for the shared `@lobechat/device-control` dispatcher.
  // File preview / index use the package's portable defaults (no
  // preview-protocol approval on the CLI). Deliberately mutable: the
  // mode-specific `enrollWorkspace` / `unenrollWorkspace` handlers are attached
  // further below once the workspace-share machinery is in scope β€” every bound
  // connection reads this object by reference, so late attachment is safe.
  //
  // Interactive shells for the remote terminal. One manager per process, read
  // by reference by every gateway connection this daemon owns, so a
  // workspace-share connection reaches the same sessions as the personal one.
  // Constructing it is cheap β€” the native PTY binding is only loaded when a
  // session is actually created, so a daemon that never opens a terminal never
  // touches it.
  const terminals = new TerminalSessionManager({
    client: 'cli',
    // Lazy: the CLI bundle is embedded in contexts that have no `node_modules`
    // at all (the desktop app runs it from `Resources/bin`), so a static import
    // would fail every one of them at startup.
    loadPty: () => import('@lydell/node-pty'),
    logger: { warn: (message) => info(message) },
  });

  const countActiveTasks = () =>
    getActiveShellCount() + listTasks().filter((task) => isProcessAlive(task.pid)).length;

  const maintenance = new CliMaintenance({
    activeTasks: countActiveTasks,
    daemon:
      !!options.daemonChild && !options.serviceChild && process.env.LOBEHUB_CONNECT_SERVICE !== '1',
    restartArgs: buildDaemonArgs(options).slice(1),
    shutdown: (exitCode) => shutdown(exitCode),
  });

  const deviceControlDeps: DeviceControlDeps = {
    checkCliUpdate: maintenance.check,
    ...createTerminalDeps(terminals),
    getCliUpdateState: maintenance.getState,
    getLocalFilePreview: defaultGetLocalFilePreview,
    getProjectFileIndex: defaultGetProjectFileIndex,
    listHeterogeneousAgentModels: (params) =>
      listHeterogeneousAgentModels({
        ...params,
        env: { ...process.env, ...params.env },
      }),
    // A server that can't reach an MCP server itself lists its tools here
    listMcpTools: listDeviceMcpTools,
    restartCli: maintenance.restart,
    searchProjectFiles: defaultSearchProjectFiles,
  };

  // One native runtime probe per connection: system info is queried by tool runs and
  // agent dispatch alike, and each probe starts a Codex app-server process.
  const nativeRuntimes = createRuntimeProbeCache(probeNativeRuntimes);

  // Tool calls and RPCs report themselves through `begin()`; agent runs (which
  // outlive their dispatch), background shells and tunnels are polled.
  const activity = managed?.config.activityCommand
    ? new ActivityReporter({
        command: managed.config.activityCommand,
        isBusy: () => countActiveTasks() > 0 || client.activeTunnelCount > 0,
        logger: { debug },
      })
    : undefined;

  const handlerContext: GatewayHandlerContext = {
    activity,
    browser,
    computerUse,
    deps: deviceControlDeps,
    error,
    // Read at dispatch time β€” `auth` may be refreshed mid-session.
    getAuth: () => auth,
    // The managed token authenticates with the gateway only, never the server API.
    getToolAuth: () => (managed ? undefined : auth),
    info,
    isDaemonChild,
    maintenance,
    nativeRuntimes,
    recordRequest,
  };

  // Request handlers (system info / tool calls / device RPCs / agent runs) β€”
  // shared with the workspace-share connections opened via `enrollWorkspace`.
  bindGatewayClientHandlers(client, handlerContext, workspaceId ?? managedWorkspaceId);

  // A scheduled refresh and an auth handler can both reach a final answer from
  // the one shared token exchange; stop only once.
  let managedExiting = false;
  const exitManaged = (message: string) => {
    if (managedExiting) return;
    managedExiting = true;
    error(message);
    cleanup();
    process.exit(1);
  };

  // Managed mode: one token refresh per rejected connection. A token the
  // gateway rejects right after it was issued will not get better by retrying,
  // so exit and let the platform restart the agent.
  let managedAuthRetried = false;

  // Machine health (CPU / memory / load) for the device page. Samples go to
  // the device gateway over this socket (the gateway is their only store);
  // they keep accruing while disconnected and upload once the connection is
  // back, so the stretch around a drop is visible afterwards. Each batch is
  // mirrored to this machine's workspace-share connections so a shared
  // device's workspace row has the same history.
  const metricsDeviceId = identity?.deviceId ?? managed?.config.deviceId;
  const metricsSampler = metricsDeviceId
    ? new DeviceMetricsSampler({
        isConnected: () => client.connectionStatus === 'connected',
        logger: { warn: (msg) => info(msg) },
        storagePath: resolveDeviceMetricsBacklogPath(metricsDeviceId),
        upload: (samples) =>
          pushMetrics(
            client,
            [...workspaceConnections.values()].map((entry) => entry.client),
            samples,
          ),
      })
    : undefined;

  client.on('connected', () => {
    managedAuthRetried = false;
    updateStatus('connected');
    void metricsSampler?.flush();
    // Back online: the server runs the worktree cleanups that waited for this
    // device (topics archived or trashed while it was offline) over the gateway.
    const connectedDeviceId = client.currentDeviceId;
    if (connectedDeviceId)
      void createLambdaClient(auth, managed ? managedWorkspaceId : workspaceId)
        .device.drainWorktreeCleanups.mutate({ deviceId: connectedDeviceId })
        .catch((err) => info(`Worktree cleanup drain failed: ${(err as Error).message}`));
    // A (re)connection reprobes so an upgraded or downgraded Codex is reported, and
    // warms the cache before the gateway's first system_info_request.
    nativeRuntimes.invalidate();
    void nativeRuntimes.get();
  });

  client.on('disconnected', () => {
    updateStatus('disconnected');
  });

  client.on('reconnecting', () => {
    updateStatus('reconnecting');
  });

  // ─── Workspace share connections (personal mode) ───
  //
  // The server shares this personal device into a workspace by sending an
  // `enrollWorkspace` RPC over the PERSONAL connection. The process then keeps a
  // second gateway connection per shared workspace, authenticated with a minted
  // workspace-device connect token and identified by the workspace-derived
  // deviceId β€” so the machine is simultaneously reachable as a personal device
  // and as a device of each shared workspace.

  interface WorkspaceShareConnection {
    cancelRefresh: (() => void) | null;
    client: GatewayClient;
  }

  const workspaceConnections = new Map<string, WorkspaceShareConnection>();

  const closeWorkspaceConnection = (wsId: string) => {
    const entry = workspaceConnections.get(wsId);
    if (!entry) return;
    workspaceConnections.delete(wsId);
    entry.cancelRefresh?.();
    entry.client.disconnect();
  };

  const openWorkspaceConnection = async (wsId: string, initialToken: string) => {
    // Re-enroll replaces the previous share connection instead of stacking one.
    closeWorkspaceConnection(wsId);

    // Same derivation as `lh connect --workspace` so the enroll RPC and a manual
    // workspace enrollment on this machine resolve to one workspace device.
    const wsIdentity = resolveWorkspaceDeviceIdentity(wsId, undefined, loadOrCreateConnectionId());

    const wsClient = new GatewayClient({
      channel,
      connectionId: loadOrCreateConnectionId(),
      deviceId: wsIdentity.deviceId,
      gatewayUrl: resolvedGatewayUrl,
      logger: isDaemonChild ? createDaemonLogger() : log,
      serverUrl: auth.serverUrl,
      token: initialToken,
      tokenType: 'jwt',
      userId: undefined,
      workspaceId: wsId,
    });

    bindGatewayClientHandlers(wsClient, handlerContext, wsId);
    // The share has its own device id: drain what waited for it, in its workspace.
    wsClient.on('connected', () => {
      const shareDeviceId = wsClient.currentDeviceId;
      if (shareDeviceId)
        void createLambdaClient(auth, wsId)
          .device.drainWorktreeCleanups.mutate({ deviceId: shareDeviceId })
          .catch((err) =>
            info(`Worktree cleanup drain failed (${wsId}): ${(err as Error).message}`),
          );
    });

    const entry: WorkspaceShareConnection = { cancelRefresh: null, client: wsClient };

    // The connect token is short-lived; the current user is the enroller, so
    // they hold the permission to re-mint it for as long as the share exists.
    let liveToken = initialToken;
    const remintToken = async (): Promise<string> => {
      const minted = await mintWorkspaceConnectToken(auth, wsId);
      liveToken = minted.token;
      return minted.token;
    };

    const startRefresh = (): (() => void) | null =>
      scheduleProactiveRefresh(
        liveToken,
        'jwt',
        async () => {
          const newToken = await remintToken();
          wsClient.updateToken(newToken);
          entry.cancelRefresh = startRefresh();
          return newToken;
        },
        info,
        error,
      );
    entry.cancelRefresh = startRefresh();

    wsClient.on('auth_expired', async () => {
      info(`Workspace ${wsId} connect token expired. Re-minting...`);
      try {
        const newToken = await remintToken();
        wsClient.updateToken(newToken);
        entry.cancelRefresh?.();
        entry.cancelRefresh = startRefresh();
        await wsClient.reconnect();
        return;
      } catch {
        // fall through β€” likely the share (or membership) was revoked
      }
      error(`Could not refresh workspace ${wsId} connect token. Closing share connection.`);
      closeWorkspaceConnection(wsId);
    });

    wsClient.on('replaced', () => {
      error(
        `Workspace ${wsId} share connection was taken over by another '${CLI_PRIMARY_BIN} connect' on this machine. Closing it here.`,
      );
      closeWorkspaceConnection(wsId);
    });

    wsClient.on('auth_failed', (reason) => {
      // Only this share connection is affected β€” never exit the personal process.
      error(`Workspace ${wsId} authentication failed: ${reason}. Closing share connection.`);
      closeWorkspaceConnection(wsId);
    });

    wsClient.on('error', (err) => {
      error(`Workspace ${wsId} connection error: ${err.message}`);
    });

    workspaceConnections.set(wsId, entry);
    await wsClient.connect();
    return wsIdentity;
  };

  if (workspaceId) {
    // Workspace-mode process (`lh connect --workspace <id>`): an unenroll for
    // our own workspace means the server revoked this enrollment β€” ack, then
    // exit gracefully so a daemon stops reconnecting as a ghost device.
    deviceControlDeps.unenrollWorkspace = async (params) => {
      if (params.workspaceId !== workspaceId) {
        throw new Error(
          `This connection is enrolled to workspace ${workspaceId}, not ${params.workspaceId}`,
        );
      }
      info('Workspace enrollment was revoked by the server. Shutting down...');
      // Delay the teardown so the RPC response flushes before the socket closes.
      setTimeout(() => {
        cleanup();
        process.exit(0);
      }, 500);
      return { success: true };
    };
  } else if (!managed) {
    // A managed device belongs to one principal; it is never shared into a workspace.
    deviceControlDeps.enrollWorkspace = async ({
      identityOnly,
      token: wsToken,
      workspaceId: wsId,
    }) => {
      // Dry-run probe: hand the server our derived identity so it can detect
      // an existing enrollment (and ask for overwrite confirmation) without
      // this machine opening or persisting anything.
      if (identityOnly)
        return resolveWorkspaceDeviceIdentity(wsId, undefined, loadOrCreateConnectionId());
      const wsIdentity = await openWorkspaceConnection(wsId, wsToken);
      // Persist so a restart re-opens the share connection without the server
      // having to re-share. The server registers the device row itself from
      // the identity we return.
      addWorkspaceEnrollment(wsId);
      info(`Enrolled into workspace ${wsId} as device ${wsIdentity.deviceId}`);
      return wsIdentity;
    };

    // The revoke instruction may arrive on the workspace connection (preferred)
    // or on the personal one β€” both bind the same deps, so either path lands here.
    deviceControlDeps.unenrollWorkspace = async ({ workspaceId: wsId }) => {
      closeWorkspaceConnection(wsId);
      removeWorkspaceEnrollment(wsId);
      info(`Unenrolled from workspace ${wsId}`);
      return { success: true };
    };
  }

  /**
   * Re-open share connections persisted by a previous run. Before reconnecting,
   * confirm our derived workspace deviceId still has a registered row β€” the
   * share may have been revoked while this device was offline (the server can't
   * deliver `unenrollWorkspace` to a dead socket), and reconnecting anyway would
   * resurrect the device as a ghost in the workspace pool.
   */
  const restoreWorkspaceEnrollments = async () => {
    for (const wsId of loadWorkspaceEnrollments()) {
      try {
        const wsIdentity = resolveWorkspaceDeviceIdentity(
          wsId,
          undefined,
          loadOrCreateConnectionId(),
        );
        const trpc = createLambdaClient(auth, wsId);
        const devices = await trpc.device.listDevices.query();
        const stillEnrolled = devices.some(
          (d) => d.deviceId === wsIdentity.deviceId && d.registered,
        );
        if (!stillEnrolled) {
          info(`Workspace share ${wsId} was revoked while offline. Clearing local enrollment.`);
          removeWorkspaceEnrollment(wsId);
          continue;
        }
        const minted = await mintWorkspaceConnectToken(auth, wsId);
        await openWorkspaceConnection(wsId, minted.token);
        info(`Restored workspace share connection: ${wsId}`);
      } catch (err) {
        // Non-fatal (e.g. transient network error): keep the record and retry on
        // the next startup rather than silently dropping the share.
        error(`Failed to restore workspace share ${wsId}: ${(err as Error).message}`);
      }
    }
  };

  // Proactive token refresh β€” schedule before the connect token expires. For a
  // workspace device `refreshConnectToken` re-mints the workspace token; for a
  // personal device it refreshes the user token. Scheduling watches the actual
  // connect token, so the workspace token's shorter life is respected.
  const startProactiveRefresh = (): (() => void) | null =>
    // A managed token session schedules its own refreshes.
    managed
      ? null
      : scheduleProactiveRefresh(
          connectToken,
          connectTokenType,
          async () => {
            const newToken = await refreshConnectToken();
            if (newToken) {
              client.updateToken(newToken);
              cancelRefreshTimer = startProactiveRefresh();
            }
            return newToken;
          },
          info,
          error,
        );
  let cancelRefreshTimer = startProactiveRefresh();

  // Handle auth failed β€” attempt token refresh once before giving up
  // (e.g., auto-reconnect may send an expired JWT before proactive refresh fires)
  let authFailedRefreshAttempted = false;
  client.on('auth_failed', async (reason) => {
    if (managed) {
      if (managedAuthRetried) {
        exitManaged(`The gateway rejected the managed device token: ${reason}`);
        return;
      }
      managedAuthRetried = true;
      info(`Authentication failed (${reason}). Getting a new managed device token...`);
      try {
        await managed.session.refreshNow();
        await client.reconnect();
      } catch (err) {
        exitManaged((err as Error).message);
      }
      return;
    }

    let exitCode = 1;
    if (connectTokenType === 'jwt' && !authFailedRefreshAttempted) {
      authFailedRefreshAttempted = true;
      info(`Authentication failed (${reason}). Attempting token refresh...`);
      try {
        const prev = connectToken;
        const newToken = await refreshConnectToken();
        if (newToken && newToken !== prev) {
          info('Token refreshed successfully. Reconnecting...');
          client.updateToken(newToken);
          authFailedRefreshAttempted = false;
          cancelRefreshTimer = startProactiveRefresh();
          await client.reconnect();
          return;
        }
      } catch (err) {
        error(`Token refresh failed: ${(err as Error).message}`);
        if (workspaceId) exitCode = getWorkspaceFailureExitCode(err);
      }
    }

    error(`Authentication failed: ${reason}`);
    error(
      `Run '${CLI_PRIMARY_BIN} login', or set ${CLI_API_KEY_ENV} and run '${CLI_PRIMARY_BIN} login --server <url>' to configure API key authentication.`,
    );
    cleanup();
    process.exit(exitCode);
  });

  // Handle auth expired β€” refresh token and reconnect automatically
  client.on('auth_expired', async () => {
    if (connectTokenType === 'apiKey') {
      // API keys don't expire; ignore stale auth_expired signals
      return;
    }

    info('Authentication expired. Attempting to refresh token...');
    let exitCode = 1;

    try {
      const newToken = await refreshConnectToken();
      if (newToken) {
        info('Token refreshed successfully. Reconnecting...');
        client.updateToken(newToken);
        cancelRefreshTimer = startProactiveRefresh();
        await client.reconnect();
        return;
      }
    } catch (err) {
      error(`Token refresh failed: ${(err as Error).message}`);
      if (workspaceId) exitCode = getWorkspaceFailureExitCode(err);
    }

    if (managed) {
      exitManaged('Could not get a new managed device token.');
      return;
    }
    error("Could not refresh token. Run 'lh login' to re-authenticate.");
    cleanup();
    process.exit(exitCode);
  });

  // Another `lh connect` of this install (same persisted connection id) took
  // over. The client no longer reconnects β€” doing so is what made the two trade
  // the connection every second β€” so exit instead of sitting silently offline.
  client.on('replaced', () => {
    error(
      `Another '${CLI_PRIMARY_BIN} connect' on this machine took over this device's gateway connection. Only one can be connected at a time; stopping this one.`,
    );
    cleanup();
    process.exit(1);
  });

  // Handle errors
  client.on('error', (err) => {
    error(`Connection error: ${err.message}`);
  });

  // Graceful shutdown
  const cleanup = () => {
    info('Shutting down...');
    cancelRefreshTimer?.();
    managed?.session.stop();
    activity?.stop();
    cleanupAllProcesses();
    void disposeDeviceMcp();
    // Kill every remote-terminal shell this daemon started, so a stopping
    // `lh connect` does not leave orphaned PTYs behind on the machine.
    terminals.dispose();
    // Close share connections but keep the persisted enrollments β€” the next
    // startup restores them (or clears them if revoked meanwhile).
    for (const wsId of workspaceConnections.keys()) closeWorkspaceConnection(wsId);
    void metricsSampler?.stop();
    client.disconnect();
    removeStatus(process.pid);
    if (isDaemonChild) {
      removePid(process.pid);
    }
  };

  // A clean stop pushes the health samples taken since the last upload
  // (bounded) before the socket closes, so the device page doesn't show the
  // final minutes as "not running".
  const shutdown = async (exitCode = 0) => {
    await Promise.all([
      metricsSampler?.stop({ flushTimeoutMs: SHUTDOWN_METRICS_FLUSH_MS }),
      closeBrowserSessions(browser),
      disposeDeviceMcp(),
    ]);
    cleanup();
    process.exit(exitCode);
  };

  process.on('SIGINT', () => shutdown());
  process.on('SIGTERM', () => shutdown());

  // Register this device in the server registry before opening the WS, so the
  // row exists by the time the gateway reports it online. `lh login` already
  // registers, but re-running here is cheap (idempotent upsert) and covers
  // `--token` sessions that never went through login. Best-effort: a failure
  // must not block the connection.
  if (identity) {
    try {
      // Reuse the already-resolved auth (respects `--token` mode) so we don't
      // re-discover creds and exit when none are found.
      if (workspaceId)
        await registerWorkspaceDevice(
          auth,
          identity,
          workspaceId,
          options.public ? 'public' : undefined,
        );
      else await registerDevice(auth, identity);
    } catch (err) {
      // Workspace-mode registration is AUTHORITATIVE, not best-effort: the
      // `devices` row is what carries the (default-private) visibility marker
      // that hides this machine from other members. Connecting without it β€”
      // whether the server refused the id (another member's PRIVATE
      // enrollment β†’ CONFLICT) or the write simply failed transiently β€” would
      // join the workspace pool as an unregistered transient that everyone
      // can see, so abort before connecting.
      if (workspaceId) {
        error(`Workspace device registration failed: ${(err as Error).message}`);
        cleanup();
        process.exit(getWorkspaceFailureExitCode(err));
      }
      error(`Device registration failed (non-fatal): ${(err as Error).message}`);
    }
  }

  await reportDaemonStartupReady();

  await metricsSampler?.start();
  activity?.start();

  // Connect
  await client.connect();

  // Personal mode: re-open any workspace share connections from a previous run.
  // Best-effort after the main connection β€” a failed restore never blocks it.
  if (!workspaceId && !managed) void restoreWorkspaceEnrollments();
}

function createDaemonLogger() {
  return {
    debug: (msg: string) => appendLog(`[DEBUG] ${msg}`),
    error: (msg: string) => appendLog(`[ERROR] ${msg}`),
    info: (msg: string) => appendLog(`[INFO] ${msg}`),
    warn: (msg: string) => appendLog(`[WARN] ${msg}`),
  };
}