Files
hapi/cli/src/configuration.ts
T
Junmo KimandGitHub 229766dd21 fix(agy): make conversation discovery deterministic at session start (#1369)
* refactor(agy): extract brain UUID adoption from the PreToolUse hook handler

Pull the first-wins UUID-adoption block out of onPreToolUse into a
standalone adoptBrainUuidIfUnset() helper so it can be shared with the
upcoming PreInvocation hook handler without duplicating the guard logic.
No behavior change.

* feat(agy): discover the brain UUID from agy's PreInvocation hook

PreToolUse only fires once a tool actually runs, so a tool-free turn
(e.g. a plain "hi") never gets a brain UUID from it. Register agy's
PreInvocation hook alongside PreToolUse: it fires before every model
call regardless of tool use, carries the same conversationId, and lets
discovery resolve deterministically instead of depending on a tool
being invoked.

PreInvocation uses agy's flat hook schema (distinct from PreToolUse's
grouped {matcher,hooks} shape) and a short 5s timeout, since it blocks
the agent loop synchronously on every model call. The forwarder gains
an explicit --event flag (default pre-tool-use, unchanged) to route to
a new /hook/agy-invocation endpoint; that path is fail-open (always
responds 200 / stdout "{}") since a lost discovery signal must never
block a model call, unlike a permission decision.

Both hooks funnel into the same first-wins UUID adoption guard, so a
resume-seeded sessionId is never overwritten by either.

* refactor(agy): drop transcript content-matching now that the hook is authoritative

The scanner's content-match discovery was the fallback for turns where
the PreToolUse hook never fired (no tool used). Now that PreInvocation
covers exactly that case, the fallback never actually gets a chance to
run in practice: carrier hook loading fails all-or-nothing (both events
live in the same hooks.json), and a failed carrier already aborts the
PTY session before discovery matters. Keeping unreachable code around
just keeps the risk it was flagged for — attaching to an unrelated agy
session that happens to share the same first prompt.

Removes the scan-window heuristics, the wrapped-USER_REQUEST content
matcher, and the ambiguity-reporting path entirely. The scanner is now
purely reactive: it watches nothing until onNewSession() (driven by a
hook) tells it which brain to watch. extractUserRequest/
normalizeUserInput and the launcher's userRequestMatches are untouched
— they answer a different question (did the web-submitted message echo
back into the PTY), which hook payloads carry no text to answer.

* feat(agy): drop the PreInvocation discovery hook once the conversation is identified

PreInvocation fires on every model call (~424ms round trip measured), but the
brain UUID only needs to be discovered once. agy re-reads hooks.json before
every model call, so the carrier's hooks.json can be rewritten in place (via
a temp-file-plus-rename atomic write) to drop the PreInvocation block the
moment handleSessionFound confirms the UUID, leaving PreToolUse untouched.

PreInvocation is restored before every respawn, since a resume that silently
fails would otherwise leave no way to discover the replacement conversation's
UUID. If the carrier itself has vanished (e.g. /tmp's tmpfiles.d sweep on a
long-lived session), it is rebuilt from scratch and hookCarrierDir is
repointed for the next agy spawn.

* refactor(cli): extract resolveHapiHomeDir from Configuration's constructor

Configuration.happyHomeDir is a singleton computed once at process
startup, which the upcoming agy carrier relocation can't reuse directly
without breaking per-test HAPI_HOME isolation. Extract the priority
logic into a standalone, env-injectable function with no behavior
change.

* feat(agy): relocate the hook carrier under HAPI_HOME and sweep dead ones

Carriers used to live under mkdtempSync(join(tmpdir(), 'hapi-agy-
carrier-')). On this machine /tmp is swept by tmpfiles.d after 30 days,
and agy re-reads hooks.json on every model call (not just at spawn), so
a long-lived session's carrier could be deleted out from under it,
silently killing both the permission bridge and discovery at once.

Move carriers to <HAPI_HOME>/agy-carriers/<random>/, record owner
metadata (pid, startedAt) at the carrier root (outside .agents/, which
agy itself reads), and sweep carriers whose owner process has
confirmed-died at session start. Liveness is judged strictly by
process.kill(pid, 0): ESRCH means dead and safe to remove, EPERM means
alive but not ours and must be preserved, anything else is unknown and
also preserved. Carriers with unreadable or missing owner metadata
(pre-existing or corrupted) are only swept once old enough to rule out
a carrier still mid-creation. Every ambiguous case defaults to
preservation, since deleting a live session's carrier is far more
costly than leaving an inert directory on disk.

* fix(agy): abort respawn instead of spawning agy without a permission bridge

syncPreInvocationHookForLaunch used to log-and-return when the hook
carrier could not be recreated before a respawn, letting launchOnce
spawn agy anyway with --dangerously-skip-permissions and no PreToolUse
hook wired up — every tool call would auto-approve with nobody in the
loop. Throw instead, matching runAgy.ts's existing fail-closed contract
for the initial carrier, and notify the web chat via sendSessionEvent
so the abort isn't silent.

* fix(agy): sweep carriers only when the owner is positively identified

An unreadable owner.json is not evidence of staleness: a live session
whose metadata cannot be parsed would have its carrier removed once it
aged past the threshold, taking the PreToolUse approval bridge with it.
Hostname is not an identity either — containers sharing a HAPI_HOME can
share a hostname while their PIDs live in unrelated namespaces, so a
liveness probe there reports ESRCH for a process that is very much alive.

Scope the owner record to the boot id and PID namespace on Linux, fall
back to a distinguishable hostname-only scope elsewhere, and delete only
when the scope matches and the pid is confirmed dead. Carriers whose
owner cannot be identified are now kept.

* fix(agy): drop the hostname scope fallback rather than guess ownership

Hostname is not an identity. Where /proc is unavailable, two machines or
containers sharing a HAPI_HOME and a hostname compute the same scope, so a
pid that is live on the owning system reads as ESRCH here and its carrier
is deleted — taking the PreToolUse approval bridge with it while agy runs
with --dangerously-skip-permissions.

Without a strong boot and PID-namespace identity the scope is now
undefined, which makes the sweep preserve everything. Orphaned carriers
accumulate on those platforms instead, which is the cheaper failure:
ordinary teardown still removes carriers, so only crash leftovers remain.

* fix(agy): point carrier failures at HAPI_HOME instead of the temp dir

The carrier moved under HAPI_HOME/agy-carriers earlier in this branch,
but the abort messages still told users to check the temporary directory.
On a custom or quota-limited HAPI_HOME that sends remediation to a
filesystem that has nothing to do with the failure.

Both the initial-preparation path and the respawn-recreation path carried
the stale hint, so both are updated — otherwise the same failure would
suggest two different places to look.
2026-08-05 07:56:40 +08:00

140 lines
4.6 KiB
TypeScript

/**
* Global configuration for HAPI CLI
*
* Centralizes all configuration including environment variables and paths
* Environment files should be loaded using Node's --env-file flag
*/
import { existsSync, mkdirSync } from 'node:fs'
import { homedir } from 'node:os'
import { join } from 'node:path'
import packageJson from '../package.json'
import { getCliArgs } from '@/utils/cliArgs'
export function normalizeExtraHeaders(
value: unknown,
source: string,
warn: (message: string) => void = console.warn
): Record<string, string> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
warn(`[WARN] ${source} must be a JSON object. Ignoring value.`)
return {}
}
const entries = Object.entries(value)
const headers = Object.fromEntries(
entries.filter((entry): entry is [string, string] => typeof entry[1] === 'string')
)
if (Object.keys(headers).length !== entries.length) {
warn(`[WARN] ${source} only supports string header values. Ignoring non-string entries.`)
}
return headers
}
export function parseExtraHeaders(raw: string | undefined, warn: (message: string) => void = console.warn): Record<string, string> {
if (!raw) {
return {}
}
try {
const parsed = JSON.parse(raw) as unknown
return normalizeExtraHeaders(parsed, 'HAPI_EXTRA_HEADERS_JSON', warn)
} catch {
warn('[WARN] Failed to parse HAPI_EXTRA_HEADERS_JSON. Ignoring value.')
return {}
}
}
/**
* Resolves HAPI's home directory: the `HAPI_HOME` env override (with a
* leading `~` expanded to the current user's home) takes priority, else
* `~/.hapi`. Takes an explicit env object (defaulting to `process.env`) so
* callers that need a fresh read on every call — rather than the cached
* `Configuration.happyHomeDir` singleton value, which is fixed at process
* startup — can reuse this instead of re-deriving the same priority logic.
*/
export function resolveHapiHomeDir(env: NodeJS.ProcessEnv = process.env): string {
if (env.HAPI_HOME) {
return env.HAPI_HOME.replace(/^~/, homedir())
}
return join(homedir(), '.hapi')
}
class Configuration {
private _apiUrl: string
private _cliApiToken: string
private _extraHeaders: Record<string, string>
public readonly isRunnerProcess: boolean
// Directories and paths (from persistence)
public readonly happyHomeDir: string
public readonly logsDir: string
public readonly settingsFile: string
public readonly privateKeyFile: string
public readonly runnerStateFile: string
public readonly runnerLockFile: string
public readonly currentCliVersion: string
public readonly isExperimentalEnabled: boolean
constructor() {
// Server configuration
this._apiUrl = process.env.HAPI_API_URL || 'http://localhost:3006'
this._cliApiToken = process.env.CLI_API_TOKEN || ''
this._extraHeaders = parseExtraHeaders(process.env.HAPI_EXTRA_HEADERS_JSON)
// Check if we're running as runner based on process args
const args = getCliArgs()
this.isRunnerProcess = args.length >= 2 && args[0] === 'runner' && (args[1] === 'start-sync')
// Directory configuration - Priority: HAPI_HOME env > default home dir
this.happyHomeDir = resolveHapiHomeDir()
this.logsDir = join(this.happyHomeDir, 'logs')
this.settingsFile = join(this.happyHomeDir, 'settings.json')
this.privateKeyFile = join(this.happyHomeDir, 'access.key')
this.runnerStateFile = join(this.happyHomeDir, 'runner.state.json')
this.runnerLockFile = join(this.happyHomeDir, 'runner.state.json.lock')
this.isExperimentalEnabled = ['true', '1', 'yes'].includes(process.env.HAPI_EXPERIMENTAL?.toLowerCase() || '')
this.currentCliVersion = packageJson.version
if (!existsSync(this.happyHomeDir)) {
mkdirSync(this.happyHomeDir, { recursive: true })
}
// Ensure directories exist
if (!existsSync(this.logsDir)) {
mkdirSync(this.logsDir, { recursive: true })
}
}
get apiUrl(): string {
return this._apiUrl
}
_setApiUrl(url: string): void {
this._apiUrl = url
}
get cliApiToken(): string {
return this._cliApiToken
}
_setCliApiToken(token: string): void {
this._cliApiToken = token
}
get extraHeaders(): Record<string, string> {
return this._extraHeaders
}
_setExtraHeaders(headers: Record<string, string>): void {
this._extraHeaders = { ...headers }
}
}
export const configuration: Configuration = new Configuration()