Skip to content

The agent that grows with you

4.2 KB
Raw Blame
import { execFile } from 'node:child_process'

import { appVersionInfo } from './app-version'
import { buildDesktopBackendEnv } from './backend-env'
import { PROBE_TIMEOUT_MS } from './backend-probes'
import type { InstallStamp } from './install-stamp'
import { resolveInstallationLauncherAsync } from './updater-process'
import { windowsShellCommand } from './windows-child-options'

export type VersionProbeRunner = (
  command: string,
  args: string[],
  options: {
    cwd: string
    env: NodeJS.ProcessEnv
    timeout: number
    maxBuffer: number
    shell: boolean
    windowsHide: boolean
  }
) => Promise<string>

const DEFAULT_CACHE_TTL_MS = 5_000
// Keyed by installation (root + HERMES_HOME), not launcher: the cache must answer before any
// launcher discovery, whose historical rung spawns the launcher to prove its identity.
let cached: { key: string; version: string; expiresAt: number } | null = null
let inFlight: { key: string; promise: Promise<string> } | null = null

/** Extract the client version printed by the exact local installation launcher. */
export function parseLocalRuntimeVersion(output: string): string {
  const match = output.match(/^\s*Hermes Agent\s+([^\s(]+)/m)

  return match?.[1]?.replace(/^v/, '') ?? ''
}

function runVersionProbe(
  command: string,
  args: string[],
  options: Parameters<VersionProbeRunner>[2]
): Promise<string> {
  return new Promise((resolve, reject) => {
    execFile(command, args, { ...options, encoding: 'utf8' }, (error, stdout) => {
      if (error) {
        reject(error)

        return
      }

      resolve(stdout)
    })
  })
}

/**
 * Read the version from the local source installation without contacting a
 * gateway or starting the full backend. The short cache prevents repeated
 * About/status refreshes from spawning the launcher unnecessarily.
 */
export async function resolveLocalRuntimeVersion(
  root: string,
  hermesHome: string,
  options: {
    isWindows?: boolean
    launcher?: string | null
    run?: VersionProbeRunner
    cacheTtlMs?: number
  } = {}
): Promise<string> {
  const useCache = options.run === undefined
  const key = `${root}\0${hermesHome}`

  if (useCache && cached?.key === key && cached.expiresAt > Date.now()) {
    return cached.version
  }

  if (useCache && inFlight?.key === key) {
    return inFlight.promise
  }

  const promise = probeLocalRuntimeVersion(root, hermesHome, options)

  if (useCache) {
    inFlight = { key, promise }
    void promise.then(version => {
      cached = { key, version, expiresAt: Date.now() + (options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS) }
    }).finally(() => {
      if (inFlight?.promise === promise) {
        inFlight = null
      }
    })
  }

  return promise
}

async function probeLocalRuntimeVersion(
  root: string,
  hermesHome: string,
  options: { isWindows?: boolean; launcher?: string | null; run?: VersionProbeRunner }
): Promise<string> {
  const isWindows = options.isWindows ?? process.platform === 'win32'
  let launcher: string | null

  try {
    launcher = options.launcher === undefined
      ? await resolveInstallationLauncherAsync(root, isWindows, hermesHome)
      : options.launcher
  } catch {
    return ''
  }

  if (!launcher) {
    return ''
  }

  const shell = isWindows && /\.(cmd|bat)$/i.test(launcher)
  const command = windowsShellCommand(launcher, shell, isWindows)

  return (options.run ?? runVersionProbe)(command, ['--version'], {
    cwd: root,
    env: { ...process.env, ...buildDesktopBackendEnv({ currentEnv: process.env }), HERMES_HOME: hermesHome },
    timeout: PROBE_TIMEOUT_MS,
    maxBuffer: 64 * 1024,
    shell,
    windowsHide: true
  })
    .then(parseLocalRuntimeVersion)
    .catch(() => '')
}

/**
 * This machine's install, whatever connection the window is on: the stamp for
 * packaged artifacts, the install launcher's `--version` for source installs.
 * The About page shows it beside the active connection's backend version.
 */
export async function resolveDesktopClientVersion(
  stamp: Readonly<InstallStamp> | null,
  root: string,
  hermesHome: string,
  packageVersion: string
): Promise<string> {
  if (stamp?.payload && stamp.payload !== 'bootstrap') {
    return appVersionInfo(stamp, '', packageVersion).appVersion
  }

  return resolveLocalRuntimeVersion(root, hermesHome)
}