mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-28 05:57:13 +00:00
Use one native app-server for terminal, Web and phone clients while retaining the existing CLI and Runner lifecycle. Synchronize native queues, permissions, question history and steering state; preserve explicit permission precedence and per-turn usage models. Resume inactive clear commands through Runner and reject independent child cold resumes. Add shared-runtime regression tests, generated protocol fixtures and lifecycle documentation.
393 lines
15 KiB
TypeScript
393 lines
15 KiB
TypeScript
import os from 'node:os'
|
|
import { randomUUID } from 'node:crypto'
|
|
import { resolve } from 'node:path'
|
|
|
|
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 { 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'
|
|
|
|
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
|
|
agentState?: AgentState | null
|
|
model?: string
|
|
modelReasoningEffort?: string
|
|
effort?: string
|
|
metadataOverrides?: Partial<Metadata>
|
|
}
|
|
|
|
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,
|
|
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 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({
|
|
tag: sessionTag,
|
|
metadata,
|
|
state: agentState,
|
|
model: options.model,
|
|
modelReasoningEffort: options.modelReasoningEffort,
|
|
effort: options.effort
|
|
})
|
|
|
|
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>
|
|
}): 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)
|
|
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.exportSessionEnv !== false) exportHapiSessionEnv(sessionInfo.id)
|
|
|
|
if (options.reportStarted !== false) await reportSessionStarted(sessionInfo.id, metadata)
|
|
|
|
return {
|
|
api,
|
|
session,
|
|
sessionInfo,
|
|
metadata,
|
|
machineId,
|
|
startedBy,
|
|
workingDirectory: options.workingDirectory
|
|
}
|
|
}
|