Files
hapi/cli/src/agent/sessionFactory.ts
T
2b63091421 fix(runner): adopt untracked runner webhooks only from the reporting process generation (#1943)
* feat(cli): report the CLI process start marker in session metadata

The session webhook only names hostPid. A PID alone does not tell the
runner which process generation reported it: once the CLI exits, the OS
can hand the same PID to any other process, including another
runner-spawned CLI.

Add metadata.hostStartMarker, the reporting process's own start marker
(getProcessStartMarker(process.pid), the same probe the runner uses for
its resume records and the stop-session generation check).
buildSessionMetadata is the only place that sets hostPid, so every
bootstrap path (fresh, existing, lazy, shared Codex) reports it. The
runner uses it to decide whether an untracked runner webhook may be
adopted (decideUntrackedRunnerWebhook).

* fix(runner): adopt untracked runner webhooks only from the reporting process generation

Since #1911 the runner adopts an untracked `startedBy: 'runner'` webhook
(runner restart before the webhook; Claude has no HAPI id on argv) and
persists getProcessStartMarker(pid) of whatever currently owns hostPid,
so that a later stopSession can tree-kill that generation.

If the webhook is late - the reporting CLI has exited and the OS has
already reused its PID - the persisted marker belongs to a foreign
process, possibly another runner-spawned CLI. The generation check in
stopSession then passes and the foreign process tree is killed.

The webhook now has to prove the generation itself: the CLI reports its
own marker as metadata.hostStartMarker and decideUntrackedRunnerWebhook
adopts only when it matches the live PID. A marker that names another
generation, or a failed probe, is ignored without killing anything,
also on the webhook-timeout path: a proven mismatch means the PID is not
the ghost. A webhook without a marker (older CLI) is left untracked
instead of adopted blindly; the timeout kill for those CLIs is unchanged.

The integration test drives a real runner over its control server: a
webhook carrying the live marker is adopted, listed and stoppable; a
webhook with a stale or missing marker leaves the PID untracked and
alive, and stop-session reports unknown.

Follow-up to #1911 (#1910).

* fix(cli): probe the process start marker only for runner-started sessions

buildSessionMetadata probed getProcessStartMarker(process.pid) on every
bootstrap, terminal starts included. The runner reads
metadata.hostStartMarker only in the untracked `startedBy: 'runner'`
path (decideUntrackedRunnerWebhook); a terminal webhook never consumes
it, and neither do hub or web.

The probe is a synchronous spawn: `ps` on POSIX, `tasklist` plus a
PowerShell Get-CimInstance call on Windows, each with a 10 s timeout.
A terminal `hapi` start on Windows therefore blocked on a PowerShell
cold start before the session row existed, for a value nobody reads.
With shared Codex the probe also ran per /new and /fork on the event
loop shared by all sibling roots.

Set hostStartMarker only when startedBy is 'runner'; that is the one
case the runner evaluates. This narrows the earlier commit: every
bootstrap path reports the marker for runner-started sessions, not for
terminal ones.

* fix(codex): keep hostStartMarker in the shared runtime's runner webhook

The shared Codex runtime bootstraps its roots with reportStarted: false
and reports them to the runner itself, from root.session.getMetadata().
That is the hub's view of the metadata: the hub parses stored metadata
through MetadataSchema, so a hub that predates hostStartMarker strips
the field and the webhook arrives without it. The hub's update-metadata
merge never returns it either, so the loss lasts for the root's
lifetime.

With the generation check, an untracked runner-started webhook without
a marker is ignored instead of adopted. A runner restart (for example
the version handoff of a single-host upgrade, where the hub process
keeps running the old code) followed by /new or /fork in a long-lived
shared root therefore left the root unlisted and untracked, the very
situation the adoption from #1911 addresses. The Claude and lazy
bootstrap paths are unaffected: they report the local metadata.

Take the marker from the local bootstrap metadata instead. The opt-in
runtime integration test models the stripped hub view in its session
mock and asserts the reported payload still carries the marker. The
mock also gains the `on` subscription that SharedCodexRoot requires
since #1911, without which the suite's bind test could not run.

* test(runner): run the late-webhook suite in the serial integration project

lateRunnerWebhook.integration.test.ts starts a real runner and a
detached child process per case, but the default vitest project picked
it up and `bun run test` ran it in a parallel worker. Tests that spawn
runner process trees belong to the serial integration project
(vitest.integration.config.ts, CI job `integration`), as the config
comments and .github/workflows/test.yml require.

Include the file in the integration project, exclude it from the
default one, and remove the temporary HAPI_HOME of each case, which
was left behind in the temp directory.

---------

Co-authored-by: Benedict Groppe <195190800+BGGBTAC@users.noreply.github.com>
2026-10-28 12:10:21 +08:00

454 lines
18 KiB
TypeScript

import os from 'node:os'
import { randomUUID } from 'node:crypto'
import { resolve } from 'node:path'
import { z } from 'zod'
import { ApiClient } from '@/api/api'
import type { ApiSessionClient } from '@/api/apiSession'
import type { AgentState, MachineMetadata, Metadata, Session } from '@/api/types'
import { getInstalledCliMtimeMs, notifyRunnerSessionStarted } from '@/runner/controlClient'
import { readSettings } from '@/persistence'
import { configuration } from '@/configuration'
import { logger } from '@/ui/logger'
import { runtimePath } from '@/projectPath'
import { getInvokedCwd } from '@/utils/invokedCwd'
import { getProcessStartMarker } from '@/utils/process'
import { readWorktreeEnv } from '@/utils/worktreeEnv'
import { CURRENT_MACHINE_CAPABILITIES } from '@hapi/protocol/runnerCapabilities'
import { exportHapiSessionEnv } from '@/agent/hapiSessionEnv'
import packageJson from '../../package.json'
export { HAPI_SESSION_ID_ENV, exportHapiSessionEnv, exportHapiHubAuthEnv } from '@/agent/hapiSessionEnv'
export type SessionStartedBy = 'runner' | 'terminal'
/** Matches shared CreateOrLoadSessionRequestSchema `id`. */
const HubReservedSessionIdSchema = z.string().uuid()
export type SessionBootstrapOptions = {
reportStarted?: boolean
/** Multi-session workers inject session identity into each child, never process.env. */
exportSessionEnv?: boolean
flavor: string
startedBy?: SessionStartedBy
workingDirectory?: string
tag?: string
/**
* Hub-preallocated / runner-stamped id for a *fresh* create bootstrap.
* Passed as `getOrCreateSession({ id })` so create-time metadata still runs
* while binding the reserved row. Distinct from reopen via
* `bootstrapExistingSession` / `--existing-session-id`.
*
* Must be a UUID (hub create schema). Non-UUID stamps (legacy HTTP spawn
* hints) stay reap-only: argv retains the id, create mints a new hub row.
*/
reservedSessionId?: string
agentState?: AgentState | null
model?: string
modelReasoningEffort?: string
effort?: string
metadataOverrides?: Partial<Metadata>
}
/** Hub create/load accepts optional `id` only as UUID — match that gate. */
export function resolveReservedHubSessionId(reservedSessionId: string | undefined): string | undefined {
if (!reservedSessionId) return undefined
const parsed = HubReservedSessionIdSchema.safeParse(reservedSessionId)
if (!parsed.success) {
logger.debug(
`[START] Ignoring non-UUID reservedSessionId for create bind (reap stamp only): ${reservedSessionId}`
)
return undefined
}
return parsed.data
}
export type SessionBootstrapResult = {
api: ApiClient
session: ApiSessionClient
sessionInfo: Session
metadata: Metadata
machineId: string
startedBy: SessionStartedBy
workingDirectory: string
}
export function buildMachineMetadata(options?: {
workspaceRoots?: string[]
startedCliMtimeMs?: number
/**
* Only the long-lived runner daemon may advertise machine RPC capabilities
* and CLI mtimes. Terminal/lazy/existing session bootstraps must omit this
* so a newer CLI session cannot paint an old connected runner as current
* (#1108 bot Major).
*/
asRunner?: boolean
}): MachineMetadata {
const installedCliMtimeMs = getInstalledCliMtimeMs()
const startedCliMtimeMs = options?.startedCliMtimeMs ?? installedCliMtimeMs
const base: MachineMetadata = {
host: process.env.HAPI_HOSTNAME || os.hostname(),
platform: os.platform(),
happyCliVersion: packageJson.version,
homeDir: os.homedir(),
happyHomeDir: configuration.happyHomeDir,
happyLibDir: runtimePath(),
workspaceRoots: options?.workspaceRoots,
}
if (!options?.asRunner) {
return base
}
return {
...base,
capabilities: [...CURRENT_MACHINE_CAPABILITIES],
...(typeof startedCliMtimeMs === 'number' ? { startedCliMtimeMs } : {}),
...(typeof installedCliMtimeMs === 'number' ? { installedCliMtimeMs } : {}),
// Always boolean so hub merge can clear a prior true on unsupervised restart.
supervisedRestart: process.env.HAPI_RUNNER_SUPERVISED === '1',
}
}
export function buildSessionMetadata(options: {
flavor: string
startedBy: SessionStartedBy
workingDirectory: string
machineId: string
now?: number
metadataOverrides?: Partial<Metadata>
}): Metadata {
const happyLibDir = runtimePath()
const worktreeInfo = readWorktreeEnv()
const now = options.now ?? Date.now()
return {
path: options.workingDirectory,
host: process.env.HAPI_HOSTNAME || os.hostname(),
version: packageJson.version,
os: os.platform(),
machineId: options.machineId,
homeDir: os.homedir(),
happyHomeDir: configuration.happyHomeDir,
happyLibDir,
happyToolsDir: resolve(happyLibDir, 'tools', 'unpacked'),
startedFromRunner: options.startedBy === 'runner',
hostPid: process.pid,
// Proves which process generation owns hostPid: the runner adopts an
// untracked runner-started webhook only when this matches the live
// PID. It never reads the marker of a terminal session, so skip the
// probe there (on Windows it is a synchronous PowerShell spawn).
...(options.startedBy === 'runner'
? { hostStartMarker: getProcessStartMarker(process.pid) ?? undefined }
: {}),
startedBy: options.startedBy,
lifecycleState: 'running',
lifecycleStateSince: now,
flavor: options.flavor,
capabilities: {
terminal: true
},
worktree: worktreeInfo ?? undefined,
...options.metadataOverrides
}
}
function pickExistingSessionMetadata(metadata: Metadata | null | undefined): Partial<Metadata> {
if (!metadata) return {}
const preserved: Partial<Metadata> = {}
if (metadata.name !== undefined) preserved.name = metadata.name
if (metadata.summary !== undefined) preserved.summary = metadata.summary
if (metadata.claudeSessionId !== undefined) preserved.claudeSessionId = metadata.claudeSessionId
if (metadata.codexSessionId !== undefined) preserved.codexSessionId = metadata.codexSessionId
if (metadata.codexSourceSessionId !== undefined) preserved.codexSourceSessionId = metadata.codexSourceSessionId
if (metadata.geminiSessionId !== undefined) preserved.geminiSessionId = metadata.geminiSessionId
if (metadata.opencodeSessionId !== undefined) preserved.opencodeSessionId = metadata.opencodeSessionId
if (metadata.grokSessionId !== undefined) preserved.grokSessionId = metadata.grokSessionId
if (metadata.agySessionId !== undefined) preserved.agySessionId = metadata.agySessionId
if (metadata.cursorSessionId !== undefined) preserved.cursorSessionId = metadata.cursorSessionId
if (metadata.cursorSessionProtocol !== undefined) preserved.cursorSessionProtocol = metadata.cursorSessionProtocol
if (metadata.kimiSessionId !== undefined) preserved.kimiSessionId = metadata.kimiSessionId
if (metadata.copilotSessionId !== undefined) preserved.copilotSessionId = metadata.copilotSessionId
if (metadata.piSessionId !== undefined) preserved.piSessionId = metadata.piSessionId
if (metadata.piResumeAttempt !== undefined) preserved.piResumeAttempt = metadata.piResumeAttempt
if (metadata.ptyResumeAttempt !== undefined) preserved.ptyResumeAttempt = metadata.ptyResumeAttempt
if (metadata.preferredPermissionMode !== undefined) preserved.preferredPermissionMode = metadata.preferredPermissionMode
if (metadata.tools !== undefined) preserved.tools = metadata.tools
if (metadata.slashCommands !== undefined) preserved.slashCommands = metadata.slashCommands
if (metadata.worktree !== undefined) preserved.worktree = metadata.worktree
// Preserve cached Pi model list so the web can show models immediately
// on inactive-session view without waiting for an RPC round-trip.
if (metadata.piAvailableModels !== undefined) preserved.piAvailableModels = metadata.piAvailableModels
// Preserve provider-qualified Pi model selection (disambiguates duplicate modelIds).
if (metadata.piSelectedModel !== undefined) preserved.piSelectedModel = metadata.piSelectedModel
if (metadata.conversationHistoryPoints !== undefined) {
preserved.conversationHistoryPoints = metadata.conversationHistoryPoints
}
if (metadata.conversationHistoryIndexes !== undefined) {
preserved.conversationHistoryIndexes = metadata.conversationHistoryIndexes
}
if (metadata.conversationHistoryTurns !== undefined) {
preserved.conversationHistoryTurns = metadata.conversationHistoryTurns
}
if (metadata.conversationHistoryEntryIds !== undefined) {
preserved.conversationHistoryEntryIds = metadata.conversationHistoryEntryIds
}
if (metadata.conversationHistoryDiverged !== undefined) {
preserved.conversationHistoryDiverged = metadata.conversationHistoryDiverged
}
if (metadata.forkedFrom !== undefined) {
preserved.forkedFrom = metadata.forkedFrom
}
if (metadata.capabilities?.conversationHistory !== undefined) {
preserved.capabilities = {
...preserved.capabilities,
conversationHistory: metadata.capabilities.conversationHistory
}
}
return preserved
}
async function getMachineIdOrExit(): Promise<string> {
const settings = await readSettings()
const machineId = settings?.machineId
if (!machineId) {
console.error(`[START] No machine ID found in settings, which is unexpected since authAndSetupMachineIfNeeded should have created it. Please report this issue on ${packageJson.bugs}`)
process.exit(1)
}
logger.debug(`Using machineId: ${machineId}`)
return machineId
}
async function reportSessionStarted(sessionId: string, metadata: Metadata): Promise<void> {
try {
logger.debug(`[START] Reporting session ${sessionId} to runner`)
const result = await notifyRunnerSessionStarted(sessionId, metadata)
if (result?.error) {
logger.debug(`[START] Failed to report to runner (may not be running):`, result.error)
} else {
logger.debug(`[START] Reported session ${sessionId} to runner`)
}
} catch (error) {
logger.debug('[START] Failed to report to runner (may not be running):', error)
}
}
export async function bootstrapSession(options: SessionBootstrapOptions): Promise<SessionBootstrapResult> {
const workingDirectory = options.workingDirectory ?? getInvokedCwd()
const startedBy = options.startedBy ?? 'terminal'
const sessionTag = options.tag ?? randomUUID()
const agentState = options.agentState === undefined ? {} : options.agentState
const reservedHubId = resolveReservedHubSessionId(options.reservedSessionId)
const api = await ApiClient.create()
const machineId = await getMachineIdOrExit()
await api.getOrCreateMachine({
machineId,
metadata: buildMachineMetadata()
})
const metadata = buildSessionMetadata({
flavor: options.flavor,
startedBy,
workingDirectory,
machineId,
metadataOverrides: options.metadataOverrides
})
const sessionInfo = await api.getOrCreateSession({
...(reservedHubId
? { id: reservedHubId, adopt: true as const }
: {}),
tag: sessionTag,
metadata,
state: agentState,
model: options.model,
modelReasoningEffort: options.modelReasoningEffort,
effort: options.effort
})
if (reservedHubId && sessionInfo.id !== reservedHubId) {
throw new Error(
`Hub returned unexpected session id ${sessionInfo.id} (reserved ${reservedHubId})`
)
}
const session = api.sessionSyncClient(sessionInfo)
if (options.exportSessionEnv !== false) exportHapiSessionEnv(sessionInfo.id)
if (options.reportStarted !== false) await reportSessionStarted(sessionInfo.id, metadata)
return {
api,
session,
sessionInfo,
metadata,
machineId,
startedBy,
workingDirectory
}
}
export async function bootstrapLazySession(options: SessionBootstrapOptions): Promise<SessionBootstrapResult> {
const workingDirectory = options.workingDirectory ?? getInvokedCwd()
const startedBy = options.startedBy ?? 'terminal'
if (startedBy !== 'terminal') {
throw new Error('Lazy session bootstrap is only supported for terminal sessions')
}
const api = await ApiClient.create()
const machineId = await getMachineIdOrExit()
const machineMetadata = buildMachineMetadata()
const metadata = buildSessionMetadata({
flavor: options.flavor,
startedBy,
workingDirectory,
machineId,
metadataOverrides: options.metadataOverrides
})
const agentState = options.agentState === undefined ? {} : options.agentState
const now = Date.now()
const requestedId = randomUUID()
const sessionTag = options.tag ?? randomUUID()
const sessionInfo: Session = {
id: requestedId,
namespace: 'pending',
seq: 0,
createdAt: now,
updatedAt: now,
active: false,
activeAt: now,
metadata,
metadataVersion: 0,
agentState,
agentStateVersion: 0,
thinking: false,
thinkingAt: now,
todos: [],
model: options.model ?? null,
modelReasoningEffort: options.modelReasoningEffort ?? null,
effort: options.effort ?? null,
serviceTier: null,
permissionMode: undefined,
collaborationMode: undefined
}
const session = api.sessionSyncClient(sessionInfo, {
materialize: async (snapshot, signal) => {
const materialized = await api.getOrCreateSession({
id: requestedId,
tag: sessionTag,
metadata: snapshot.metadata ?? metadata,
state: snapshot.agentState,
model: options.model,
modelReasoningEffort: options.modelReasoningEffort,
effort: options.effort,
machine: {
id: machineId,
metadata: machineMetadata
},
timeoutMs: 10_000,
signal
})
if (materialized.id !== requestedId) {
throw new Error(`Hub returned unexpected session id ${materialized.id}`)
}
return materialized
},
onMaterialized: (materialized, snapshot) => {
// Export only after the hub row exists. Exporting the provisional id at
// bootstrap lets agents inherit HAPI_SESSION_ID before GET /api/sessions/:id
// can resolve (and before hapiMcpUrl is persisted) — #1119 / PR #1121 Major.
if (options.exportSessionEnv !== false) exportHapiSessionEnv(materialized.id)
void reportSessionStarted(materialized.id, snapshot.metadata ?? metadata)
}
})
return {
api,
session,
sessionInfo,
metadata,
machineId,
startedBy,
workingDirectory
}
}
export async function bootstrapExistingSession(options: {
reportStarted?: boolean
exportSessionEnv?: boolean
sessionId: string
flavor: string
startedBy?: SessionStartedBy
workingDirectory: string
metadataOverrides?: Partial<Metadata>
requireMetadataFlush?: (metadata: Metadata | null | undefined) => boolean
}): Promise<SessionBootstrapResult> {
const startedBy = options.startedBy ?? 'terminal'
const api = await ApiClient.create()
const machineId = await getMachineIdOrExit()
await api.getOrCreateMachine({
machineId,
metadata: buildMachineMetadata()
})
const sessionInfo = await api.getSession(options.sessionId)
// #1911 M1 belt: match hub merge-preserve scope — only hub-authored archive.
// CLI self-archive (archivedBy=cli) must still reopen; hub clears before spawn
// for intentional revive. CAS closed hub-side (success+preserve + ack EXIT).
if (
sessionInfo.metadata?.lifecycleState === 'archived'
&& sessionInfo.metadata?.archivedBy === 'hub'
) {
throw new Error(
`HAPI session ${options.sessionId} is hub-archived; refuse --existing-session-id reopen `
+ '(use hub reopen to clear archive metadata first)'
)
}
const baseMetadata = buildSessionMetadata({
flavor: options.flavor,
startedBy,
workingDirectory: options.workingDirectory,
machineId
})
const buildUpdatedMetadata = (current: Metadata | null | undefined): Metadata => {
const preserved = pickExistingSessionMetadata(current)
return {
...baseMetadata,
...preserved,
...options.metadataOverrides,
capabilities: {
...baseMetadata.capabilities,
...preserved.capabilities,
...options.metadataOverrides?.capabilities
}
}
}
const metadata = buildUpdatedMetadata(sessionInfo.metadata)
const session = api.sessionSyncClient(sessionInfo)
session.updateMetadata(buildUpdatedMetadata)
if (options.requireMetadataFlush?.(sessionInfo.metadata) && !await session.flushMetadata()) {
throw new Error('Unable to persist existing-session metadata')
}
if (options.exportSessionEnv !== false) exportHapiSessionEnv(sessionInfo.id)
if (options.reportStarted !== false) await reportSessionStarted(sessionInfo.id, metadata)
return {
api,
session,
sessionInfo,
metadata,
machineId,
startedBy,
workingDirectory: options.workingDirectory
}
}