refactor: rename configuration variables for clarity

Standardize naming across CLI and server components:
- CLI: serverUrl → apiUrl, HAPI_SERVER_URL → HAPI_API_URL
- Server: webapp* → listen*, miniAppUrl → publicUrl, WEBAPP_* → HAPI_LISTEN_*, WEBAPP_URL → HAPI_PUBLIC_URL
- Rename serverUrlInit.ts → apiUrlInit.ts with updated logic for backward compatibility
- Update all imports, function calls, and documentation accordingly
This commit is contained in:
weishu
2026-01-19 12:57:37 +08:00
parent 0228146b99
commit 9e335fa305
27 changed files with 176 additions and 140 deletions
+2 -2
View File
@@ -19,7 +19,7 @@ export class ApiClient {
state: AgentState | null
}): Promise<Session> {
const response = await axios.post<CreateSessionResponse>(
`${configuration.serverUrl}/cli/sessions`,
`${configuration.apiUrl}/cli/sessions`,
{
tag: opts.tag,
metadata: opts.metadata,
@@ -79,7 +79,7 @@ export class ApiClient {
runnerState?: RunnerState
}): Promise<Machine> {
const response = await axios.post<CreateMachineResponse>(
`${configuration.serverUrl}/cli/machines`,
`${configuration.apiUrl}/cli/machines`,
{
id: opts.machineId,
metadata: opts.metadata,
+1 -1
View File
@@ -215,7 +215,7 @@ export class ApiMachineClient {
}
connect(): void {
this.socket = io(`${configuration.serverUrl}/cli`, {
this.socket = io(`${configuration.apiUrl}/cli`, {
transports: ['websocket'],
auth: {
token: this.token,
+2 -2
View File
@@ -71,7 +71,7 @@ export class ApiSessionClient extends EventEmitter {
registerCommonHandlers(this.rpcHandlerManager, this.metadata.path)
}
this.socket = io(`${configuration.serverUrl}/cli`, {
this.socket = io(`${configuration.apiUrl}/cli`, {
auth: {
token: this.token,
clientType: 'session-scoped' as const,
@@ -270,7 +270,7 @@ export class ApiSessionClient extends EventEmitter {
let cursor = startSeq
while (true) {
const response = await axios.get(
`${configuration.serverUrl}/cli/sessions/${encodeURIComponent(this.sessionId)}/messages`,
`${configuration.apiUrl}/cli/sessions/${encodeURIComponent(this.sessionId)}/messages`,
{
params: { afterSeq: cursor, limit },
headers: {
+1 -1
View File
@@ -21,7 +21,7 @@ export async function handleAuthCommand(args: string[]): Promise<void> {
const hasToken = Boolean(envToken || settingsToken)
const tokenSource = envToken ? 'environment' : (settingsToken ? 'settings file' : 'none')
console.log(chalk.bold('\nDirect Connect Status\n'))
console.log(chalk.gray(` HAPI_SERVER_URL: ${configuration.serverUrl}`))
console.log(chalk.gray(` HAPI_API_URL: ${configuration.apiUrl}`))
console.log(chalk.gray(` CLI_API_TOKEN: ${hasToken ? 'set' : 'missing'}`))
console.log(chalk.gray(` Token Source: ${tokenSource}`))
console.log(chalk.gray(` Machine ID: ${settings.machineId ?? 'not set'}`))
+1 -1
View File
@@ -139,7 +139,7 @@ ${chalk.bold.cyan('Claude Code Options (from `claude --help`):')}
messageLower.includes('network error')
) {
console.error(chalk.yellow('Unable to connect to HAPI server'))
console.error(chalk.gray(` Server URL: ${configuration.serverUrl}`))
console.error(chalk.gray(` Server URL: ${configuration.apiUrl}`))
console.error(chalk.gray(' Please check your network connection or server status'))
} else if (httpStatus === 403 && responseErrorText === 'Machine access denied') {
console.error(chalk.red('Machine access denied.'))
+6 -6
View File
@@ -12,7 +12,7 @@ import packageJson from '../package.json'
import { getCliArgs } from '@/utils/cliArgs'
class Configuration {
private _serverUrl: string
private _apiUrl: string
private _cliApiToken: string
public readonly isRunnerProcess: boolean
@@ -29,7 +29,7 @@ class Configuration {
constructor() {
// Server configuration
this._serverUrl = process.env.HAPI_SERVER_URL || 'http://localhost:3006'
this._apiUrl = process.env.HAPI_API_URL || 'http://localhost:3006'
this._cliApiToken = process.env.CLI_API_TOKEN || ''
// Check if we're running as runner based on process args
@@ -64,12 +64,12 @@ class Configuration {
}
}
get serverUrl(): string {
return this._serverUrl
get apiUrl(): string {
return this._apiUrl
}
_setServerUrl(url: string): void {
this._serverUrl = url
_setApiUrl(url: string): void {
this._apiUrl = url
}
get cliApiToken(): string {
+3 -1
View File
@@ -17,7 +17,9 @@ interface Settings {
machineIdConfirmedByServer?: boolean
runnerAutoStartWhenRunningHappy?: boolean
cliApiToken?: string
// Server URL for API connections (priority: env HAPI_SERVER_URL > this > default)
// API URL for server connections (priority: env HAPI_API_URL > this > default)
apiUrl?: string
// Legacy field name (for migration, read-only)
serverUrl?: string
}
+2 -2
View File
@@ -11,7 +11,7 @@
*
* The integration test environment uses .env.integration-test which sets:
* - HAPI_HOME=~/.hapi-dev-test (DIFFERENT from dev's ~/.hapi-dev!)
* - HAPI_SERVER_URL=http://localhost:3006 (local hapi-server)
* - HAPI_API_URL=http://localhost:3006 (local hapi-server)
* - CLI_API_TOKEN=... (must match the server)
*/
@@ -56,7 +56,7 @@ async function isServerHealthy(): Promise<boolean> {
return false;
}
const url = `${configuration.serverUrl}/cli/machines/__healthcheck__`;
const url = `${configuration.apiUrl}/cli/machines/__healthcheck__`;
const response = await fetch(url, {
headers: { Authorization: `Bearer ${configuration.cliApiToken}` },
signal: AbortSignal.timeout(1000)
+1 -1
View File
@@ -28,7 +28,7 @@ const DEFAULT_IDLE_TIMEOUT_MS = 15 * 60_000
const DEFAULT_MAX_TERMINALS = 4
const SENSITIVE_ENV_KEYS = new Set([
'CLI_API_TOKEN',
'HAPI_SERVER_URL',
'HAPI_API_URL',
'HAPI_HTTP_MCP_URL',
'TELEGRAM_BOT_TOKEN',
'OPENAI_API_KEY',
@@ -1,7 +1,7 @@
/**
* Server URL initialization module
* API URL initialization module
*
* Handles HAPI_SERVER_URL initialization with priority:
* Handles HAPI_API_URL initialization with priority:
* 1. Environment variable (highest - allows temporary override)
* 2. Settings file (~/.hapi/settings.json)
* 3. Default value (http://localhost:3006)
@@ -11,19 +11,24 @@ import { configuration } from '@/configuration'
import { readSettings } from '@/persistence'
/**
* Initialize server URL
* Initialize API URL
* Must be called before any API operations
*/
export async function initializeServerUrl(): Promise<void> {
export async function initializeApiUrl(): Promise<void> {
// 1. Environment variable has highest priority (allows temporary override)
if (process.env.HAPI_SERVER_URL) {
if (process.env.HAPI_API_URL) {
return
}
// 2. Read from settings file
// 2. Read from settings file (new name first, then legacy)
const settings = await readSettings()
if (settings.apiUrl) {
configuration._setApiUrl(settings.apiUrl)
return
}
if (settings.serverUrl) {
configuration._setServerUrl(settings.serverUrl)
// Migrate from legacy field name
configuration._setApiUrl(settings.serverUrl)
return
}
+4 -4
View File
@@ -24,7 +24,7 @@ export function getEnvironmentInfo(): Record<string, any> {
return {
PWD: process.env.PWD,
HAPI_HOME: process.env.HAPI_HOME,
HAPI_SERVER_URL: process.env.HAPI_SERVER_URL,
HAPI_API_URL: process.env.HAPI_API_URL,
HAPI_PROJECT_ROOT: process.env.HAPI_PROJECT_ROOT,
CLI_API_TOKEN_SET: Boolean(process.env.CLI_API_TOKEN),
DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING: process.env.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING,
@@ -33,7 +33,7 @@ export function getEnvironmentInfo(): Record<string, any> {
workingDirectory: process.cwd(),
processArgv: process.argv,
happyDir: configuration?.happyHomeDir,
serverUrl: configuration?.serverUrl,
apiUrl: configuration?.apiUrl,
logsDir: configuration?.logsDir,
processPid: process.pid,
nodeVersion: process.version,
@@ -107,14 +107,14 @@ export async function runDoctorCommand(filter?: 'all' | 'runner'): Promise<void>
// Configuration
console.log(chalk.bold('⚙️ Configuration'));
console.log(`hapi Home: ${chalk.blue(configuration.happyHomeDir)}`);
console.log(`Bot URL: ${chalk.blue(configuration.serverUrl)}`);
console.log(`Bot URL: ${chalk.blue(configuration.apiUrl)}`);
console.log(`Logs Dir: ${chalk.blue(configuration.logsDir)}`);
// Environment
console.log(chalk.bold('\n🌍 Environment Variables'));
const env = getEnvironmentInfo();
console.log(`HAPI_HOME: ${env.HAPI_HOME ? chalk.green(env.HAPI_HOME) : chalk.gray('not set')}`);
console.log(`HAPI_SERVER_URL: ${env.HAPI_SERVER_URL ? chalk.green(env.HAPI_SERVER_URL) : chalk.gray('not set')}`);
console.log(`HAPI_API_URL: ${env.HAPI_API_URL ? chalk.green(env.HAPI_API_URL) : chalk.gray('not set')}`);
console.log(`CLI_API_TOKEN: ${env.CLI_API_TOKEN_SET ? chalk.green('set') : chalk.gray('not set')}`);
console.log(`DANGEROUSLY_LOG_TO_SERVER: ${env.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING ? chalk.yellow('ENABLED') : chalk.gray('not set')}`);
console.log(`DEBUG: ${env.DEBUG ? chalk.green(env.DEBUG) : chalk.gray('not set')}`);
+3 -3
View File
@@ -50,10 +50,10 @@ class Logger {
constructor(
public readonly logFilePath = getSessionLogPath()
) {
// Remote logging enabled only when explicitly set with server URL
// Remote logging enabled only when explicitly set with API URL
if (process.env.DANGEROUSLY_LOG_TO_SERVER_FOR_AI_AUTO_DEBUGGING
&& process.env.HAPI_SERVER_URL) {
this.dangerouslyUnencryptedServerLoggingUrl = process.env.HAPI_SERVER_URL
&& process.env.HAPI_API_URL) {
this.dangerouslyUnencryptedServerLoggingUrl = process.env.HAPI_API_URL
console.log(chalk.yellow('[REMOTE LOGGING] Sending logs to server for AI debugging'))
}
}
+3 -3
View File
@@ -12,15 +12,15 @@ import { stdin as input, stdout as output } from 'node:process'
import chalk from 'chalk'
import { configuration } from '@/configuration'
import { readSettings, updateSettings } from '@/persistence'
import { initializeServerUrl } from '@/ui/serverUrlInit'
import { initializeApiUrl } from '@/ui/apiUrlInit'
/**
* Initialize CLI API token
* Must be called before any API operations
*/
export async function initializeToken(): Promise<void> {
// Initialize server URL first (env > settings.json > default)
await initializeServerUrl()
// Initialize API URL first (env > settings.json > default)
await initializeApiUrl()
// 1. Environment variable has highest priority (allows temporary override)
if (configuration.cliApiToken) {
+8 -8
View File
@@ -3,7 +3,7 @@
*
* Automatically starts the HAPI server when CLI is launched
* if specific conditions are met:
* 1. HAPI_SERVER_URL is not set (using default localhost:3006)
* 1. HAPI_API_URL is not set (using default localhost:3006)
* 2. cliApiToken exists in settings.json (server was previously started)
* 3. Port 3006 is not currently listening
*/
@@ -90,18 +90,18 @@ async function waitForServerReady(
* Determine if server should be auto-started
*/
async function shouldAutoStartServer(): Promise<boolean> {
// Condition 1: HAPI_SERVER_URL not set (using default localhost:3006)
if (process.env.HAPI_SERVER_URL) {
logger.debug('[AUTO-START] HAPI_SERVER_URL is set, skipping auto-start')
// Condition 1: HAPI_API_URL not set (using default localhost:3006)
if (process.env.HAPI_API_URL) {
logger.debug('[AUTO-START] HAPI_API_URL is set, skipping auto-start')
return false
}
// Condition 2: Check settings.json
const settings = await readSettings()
// 2a: serverUrl is set in settings.json (user configured a specific server)
if (settings.serverUrl) {
logger.debug('[AUTO-START] serverUrl is set in settings.json, skipping auto-start')
// 2a: apiUrl is set in settings.json (user configured a specific server)
if (settings.apiUrl || settings.serverUrl) {
logger.debug('[AUTO-START] apiUrl is set in settings.json, skipping auto-start')
return false
}
@@ -154,7 +154,7 @@ export async function maybeAutoStartServer(): Promise<void> {
startServerAsChild()
const isReady = await waitForServerReady(configuration.serverUrl)
const isReady = await waitForServerReady(configuration.apiUrl)
if (!isReady) {
console.log(chalk.yellow('Warning: Server did not start within expected time'))