mirror of
https://github.com/wu736139669/hapi.git
synced 2026-11-26 05:27:06 +00:00
* feat(shared): add session-child-exited CLI socket event * feat(cli): report unexpected runner child exits to the hub * feat(hub): mark a session inactive when its owning runner child exits * fix(hub): respawn resume when the active session has no live CLI socket * fix(hub): fail safe owner guard when the session row has no start marker A session row can carry no hostStartMarker (the CLI's start-marker probe fails at spawn). The child-exit owner guard then matched on pid alone, so a late notice from an old process whose pid the OS reused deactivated the current owner instead of being ignored. Require an exact marker match whenever either side carries a marker, and when both sides lack one, accept only a notice that is not older than the current owner's registration (metadata.lifecycleStateSince, written by the CLI together with hostPid on every spawn). Anything else falls back to the keep-alive grace. * fix(cli): release intentional-stop pid markers that no exit event will consume intentionallyStoppedPids entries were only consumed by onChildExited. A stop that ended already_gone, still_alive or unknown never produced that exit event for pids without a runner-spawned child handle, so the entry stayed forever and suppressed the real unexpected exit of a later child that reused the pid. markIntentionalStop now returns the pids it marked plus the subset with a child 'exit' listener; the stop wrapper releases the rest once the stop attempt settles, so only exits that a spawned child will still report through onChildExited keep their suppression. * fix(hub): only respawn an active row without a live socket when it is runner-spawned An empty session socket room also happens during a transport reconnect while the CLI process still runs. Resuming a terminal-started session in that window fell through to spawning a second CLI: the runner's spawn dedupe only covers sessions it spawned itself, so the replacement could overwrite ownership metadata and compete with the original process when its socket returns. Keep the legacy no-op success for active rows the hub cannot prove are runner-spawned; runner-spawned rows keep the respawn shortcut, where the runner deduplicates spawns per existing session while its child lives. * fix(cli): keep intentional-stop suppression only for the pids a stop terminated A stop that preserved a shared Codex wrapper for sibling roots returned stopped while its PID stayed marked intentional; because the wrapper has an exit listener, the marker survived until the wrapper's own exit. A wrapper that later crashed on its own consumed that stale marker and suppressed the death notifications for every sibling root, leaving them active until the keep-alive grace. Failed stops that leave a tracked child alive leaked the same way. Record the PIDs each stop attempt actually terminated and retain their suppression only while the child's own exit event is still pending; release the rest (preserved wrappers, children left alive, already-gone outcomes) so a later real death is reported. * revert(hub): keep the active-session resume shortcut Revert the ghost-active respawn from resume: an empty socket room also happens during a transport reconnect, runner dedupe can return the live child while the resume path waits for a fresh ready the session never re-emits (Pi readiness emits once), and a ghost-active Codex row refuses cold resume while the row is still active. Upstream's original behavior returns success for any active row; dead owners there are recovered by the child-exit notice, the owner guard, and the keep-alive grace.
314 lines
12 KiB
TypeScript
314 lines
12 KiB
TypeScript
import { z } from 'zod'
|
|
import type { CodexCollaborationMode, PermissionMode } from './modes'
|
|
import type { CopilotAgentMode } from './copilotModes'
|
|
import type { SessionEndReason } from './schemas'
|
|
export { SessionEndReasonSchema, type SessionEndReason } from './schemas'
|
|
|
|
export type SocketErrorReason = 'namespace-missing' | 'access-denied' | 'not-found'
|
|
|
|
export const TerminalOpenPayloadSchema = z.object({
|
|
sessionId: z.string().min(1),
|
|
terminalId: z.string().min(1),
|
|
cols: z.number().int().positive(),
|
|
rows: z.number().int().positive()
|
|
})
|
|
|
|
export type TerminalOpenPayload = z.infer<typeof TerminalOpenPayloadSchema>
|
|
|
|
export const TerminalWritePayloadSchema = z.object({
|
|
sessionId: z.string().min(1),
|
|
terminalId: z.string().min(1),
|
|
data: z.string()
|
|
})
|
|
|
|
export type TerminalWritePayload = z.infer<typeof TerminalWritePayloadSchema>
|
|
|
|
export const TerminalResizePayloadSchema = z.object({
|
|
sessionId: z.string().min(1),
|
|
terminalId: z.string().min(1),
|
|
cols: z.number().int().positive(),
|
|
rows: z.number().int().positive()
|
|
})
|
|
|
|
export type TerminalResizePayload = z.infer<typeof TerminalResizePayloadSchema>
|
|
|
|
// Read-only agent-terminal viewer controls (no terminalId — the agent PTY is the
|
|
// session's single TUI, keyed by sessionId). `resize` repaints the agent TUI at a
|
|
// given size; `refresh` forces a repaint of the current screen so a freshly
|
|
// (re)subscribed viewer sees the live state instead of a stale/black buffer.
|
|
export const AgentTerminalResizePayloadSchema = z.object({
|
|
sessionId: z.string().min(1),
|
|
cols: z.number().int().positive(),
|
|
rows: z.number().int().positive()
|
|
})
|
|
|
|
export type AgentTerminalResizePayload = z.infer<typeof AgentTerminalResizePayloadSchema>
|
|
|
|
export const AgentTerminalRefreshPayloadSchema = z.object({
|
|
sessionId: z.string().min(1)
|
|
})
|
|
|
|
export type AgentTerminalRefreshPayload = z.infer<typeof AgentTerminalRefreshPayloadSchema>
|
|
|
|
// Raw keystroke(s) typed into the agent TUI from a web viewer — the agent PTY is
|
|
// the session's single TUI, keyed by sessionId (no terminalId). Lets a remote
|
|
// viewer navigate TUI screens (e.g. answer/escape a /usage or /model dialog) that
|
|
// the structured chat composer cannot express.
|
|
export const AgentTerminalInputPayloadSchema = z.object({
|
|
sessionId: z.string().min(1),
|
|
data: z.string().min(1)
|
|
})
|
|
|
|
export type AgentTerminalInputPayload = z.infer<typeof AgentTerminalInputPayloadSchema>
|
|
|
|
export const TerminalClosePayloadSchema = z.object({
|
|
sessionId: z.string().min(1),
|
|
terminalId: z.string().min(1)
|
|
})
|
|
|
|
export type TerminalClosePayload = z.infer<typeof TerminalClosePayloadSchema>
|
|
|
|
export const TerminalReadyPayloadSchema = z.object({
|
|
sessionId: z.string().min(1),
|
|
terminalId: z.string().min(1)
|
|
})
|
|
|
|
export type TerminalReadyPayload = z.infer<typeof TerminalReadyPayloadSchema>
|
|
|
|
export const TerminalOutputPayloadSchema = z.object({
|
|
sessionId: z.string().min(1),
|
|
terminalId: z.string().min(1),
|
|
data: z.string()
|
|
})
|
|
|
|
export type TerminalOutputPayload = z.infer<typeof TerminalOutputPayloadSchema>
|
|
|
|
export const TerminalExitPayloadSchema = z.object({
|
|
sessionId: z.string().min(1),
|
|
terminalId: z.string().min(1),
|
|
code: z.number().int().nullable(),
|
|
signal: z.string().nullable()
|
|
})
|
|
|
|
export type TerminalExitPayload = z.infer<typeof TerminalExitPayloadSchema>
|
|
|
|
export const TerminalErrorPayloadSchema = z.object({
|
|
sessionId: z.string().min(1),
|
|
terminalId: z.string().min(1),
|
|
message: z.string()
|
|
})
|
|
|
|
export type TerminalErrorPayload = z.infer<typeof TerminalErrorPayloadSchema>
|
|
export const UpdateNewMessageBodySchema = z.object({
|
|
t: z.literal('new-message'),
|
|
sid: z.string(),
|
|
message: z.object({
|
|
id: z.string(),
|
|
seq: z.number(),
|
|
createdAt: z.number(),
|
|
localId: z.string().nullable().optional(),
|
|
content: z.unknown()
|
|
})
|
|
})
|
|
|
|
export type UpdateNewMessageBody = z.infer<typeof UpdateNewMessageBodySchema>
|
|
|
|
export const UpdateSessionBodySchema = z.object({
|
|
t: z.literal('update-session'),
|
|
sid: z.string(),
|
|
metadata: z.object({
|
|
version: z.number(),
|
|
value: z.unknown()
|
|
}).nullable(),
|
|
agentState: z.object({
|
|
version: z.number(),
|
|
value: z.unknown().nullable()
|
|
}).nullable()
|
|
})
|
|
|
|
export type UpdateSessionBody = z.infer<typeof UpdateSessionBodySchema>
|
|
|
|
export const UpdateMachineBodySchema = z.object({
|
|
t: z.literal('update-machine'),
|
|
machineId: z.string(),
|
|
metadata: z.object({
|
|
version: z.number(),
|
|
value: z.unknown()
|
|
}).nullable(),
|
|
runnerState: z.object({
|
|
version: z.number(),
|
|
value: z.unknown().nullable()
|
|
}).nullable()
|
|
})
|
|
|
|
export type UpdateMachineBody = z.infer<typeof UpdateMachineBodySchema>
|
|
|
|
export const UpdateRetryQueuedMessageBodySchema = z.object({
|
|
t: z.literal('retry-queued-message'),
|
|
sid: z.string(),
|
|
messageId: z.string(),
|
|
localId: z.string().nullable(),
|
|
message: UpdateNewMessageBodySchema.shape.message
|
|
})
|
|
|
|
export type UpdateRetryQueuedMessageBody = z.infer<typeof UpdateRetryQueuedMessageBodySchema>
|
|
|
|
export const UpdateCancelQueuedMessageBodySchema = z.object({
|
|
t: z.literal('cancel-queued-message'),
|
|
sid: z.string(),
|
|
messageId: z.string(),
|
|
localId: z.string().optional()
|
|
})
|
|
|
|
export type UpdateCancelQueuedMessageBody = z.infer<typeof UpdateCancelQueuedMessageBodySchema>
|
|
|
|
export const CancelQueuedMessageAckSchema = z.object({
|
|
removed: z.boolean(),
|
|
inFlight: z.boolean().optional(),
|
|
indeterminate: z.boolean().optional(),
|
|
accepted: z.boolean().optional(),
|
|
consumed: z.boolean().optional()
|
|
})
|
|
|
|
export type CancelQueuedMessageAck = z.infer<typeof CancelQueuedMessageAckSchema>
|
|
|
|
export const UpdateSchema = z.object({
|
|
id: z.string(),
|
|
seq: z.number(),
|
|
body: z.union([UpdateNewMessageBodySchema, UpdateRetryQueuedMessageBodySchema, UpdateSessionBodySchema, UpdateMachineBodySchema, UpdateCancelQueuedMessageBodySchema]),
|
|
createdAt: z.number()
|
|
})
|
|
|
|
export type Update = z.infer<typeof UpdateSchema>
|
|
|
|
export type UpdateMetadataAck = {
|
|
result: 'error'
|
|
reason?: SocketErrorReason
|
|
} | {
|
|
result: 'version-mismatch'
|
|
version: number
|
|
metadata: unknown | null
|
|
} | {
|
|
result: 'success'
|
|
version: number
|
|
metadata: unknown | null
|
|
}
|
|
|
|
export type UpdateStateAck = {
|
|
result: 'error'
|
|
reason?: SocketErrorReason
|
|
} | {
|
|
result: 'version-mismatch'
|
|
version: number
|
|
agentState: unknown | null
|
|
} | {
|
|
result: 'success'
|
|
version: number
|
|
agentState: unknown | null
|
|
}
|
|
|
|
export type MachineUpdateMetadataAck = {
|
|
result: 'error'
|
|
reason?: SocketErrorReason
|
|
} | {
|
|
result: 'version-mismatch'
|
|
version: number
|
|
metadata: unknown | null
|
|
} | {
|
|
result: 'success'
|
|
version: number
|
|
metadata: unknown | null
|
|
}
|
|
|
|
export type MachineUpdateStateAck = {
|
|
result: 'error'
|
|
reason?: SocketErrorReason
|
|
} | {
|
|
result: 'version-mismatch'
|
|
version: number
|
|
runnerState: unknown | null
|
|
} | {
|
|
result: 'success'
|
|
version: number
|
|
runnerState: unknown | null
|
|
}
|
|
|
|
export interface ServerToClientEvents {
|
|
update: (data: Update, ack?: (response: CancelQueuedMessageAck & { accepted?: boolean }) => void) => void
|
|
'rpc-request': (data: { method: string; params: string }, callback: (response: string) => void) => void
|
|
'terminal:open': (data: TerminalOpenPayload) => void
|
|
'terminal:write': (data: TerminalWritePayload) => void
|
|
'terminal:resize': (data: TerminalResizePayload) => void
|
|
'terminal:close': (data: TerminalClosePayload) => void
|
|
'agent-terminal:resize': (data: AgentTerminalResizePayload) => void
|
|
'agent-terminal:refresh': (data: AgentTerminalRefreshPayload) => void
|
|
// Raw keystroke(s) from a web viewer, relayed to the CLI to write into the
|
|
// agent PTY (interactive TUI navigation; see AgentTerminalInputPayload).
|
|
'agent-terminal:input': (data: AgentTerminalInputPayload) => void
|
|
// Sent to the CLI when the last agent-terminal viewer leaves, so it stops
|
|
// streaming PTY output to the hub until someone subscribes again.
|
|
'agent-terminal:idle': (data: AgentTerminalRefreshPayload) => void
|
|
error: (data: { message: string; code?: SocketErrorReason; scope?: 'session' | 'machine'; id?: string }) => void
|
|
}
|
|
|
|
export interface ClientToServerEvents {
|
|
// createdAt: optional client-provided timestamp (epoch ms) for the entry's
|
|
// own origin time (e.g. a Claude transcript entry's timestamp). Currently
|
|
// only honored by the hub for agent messages (no localId) — see
|
|
// messages.ts addMessage. Absent -> hub falls back to Date.now().
|
|
message: (data: { sid: string; message: unknown; localId?: string; createdAt?: number }) => void
|
|
'session-alive': (data: {
|
|
sid: string
|
|
time: number
|
|
thinking: boolean
|
|
mode?: 'local' | 'remote'
|
|
permissionMode?: PermissionMode
|
|
model?: string | null
|
|
modelReasoningEffort?: string | null
|
|
effort?: string | null
|
|
serviceTier?: string | null
|
|
collaborationMode?: CodexCollaborationMode
|
|
copilotAgentMode?: CopilotAgentMode
|
|
}) => void
|
|
/** CLI agent finished session/load (or equivalent) and can accept prompts. */
|
|
'session-ready': (data: { sid: string; time: number }) => void
|
|
'session-end': (data: { sid: string; time: number; reason?: SessionEndReason }) => void
|
|
/**
|
|
* Machine-scoped notice that a runner's child process for a HAPI session
|
|
* exited without going through the normal session-end handshake (crash,
|
|
* SIGKILL, OOM, ...). The hub only acts when this pid + process start
|
|
* marker still identify the session's current owner.
|
|
*/
|
|
'session-child-exited': (data: {
|
|
machineId: string
|
|
sid: string
|
|
pid: number
|
|
processStartMarker?: string
|
|
time: number
|
|
}) => void
|
|
'messages-consumed': (data: { sid: string; localIds: string[]; clearQueuedThinkingGrace?: boolean; steered?: boolean }) => void
|
|
'messages-indeterminate': (data: { sid: string; localIds: string[] }) => void
|
|
/** Native shared-engine queue projection. null = positively acknowledged removal. */
|
|
'native-queue-message': (data: { sid: string; localId: string; text: string | null }) => void
|
|
'messages-steer-state': (data: { sid: string; localIds: string[]; state: 'queued' | 'dispatching' }, cb: (response: { ok: boolean }) => void) => void
|
|
'update-metadata': (data: { sid: string; expectedVersion: number; metadata: unknown }, cb: (answer: UpdateMetadataAck) => void) => void
|
|
'update-state': (data: { sid: string; expectedVersion: number; agentState: unknown | null }, cb: (answer: UpdateStateAck) => void) => void
|
|
'machine-alive': (data: { machineId: string; time: number; health?: unknown }) => void
|
|
'machine-update-metadata': (data: { machineId: string; expectedVersion: number; metadata: unknown }, cb: (answer: MachineUpdateMetadataAck) => void) => void
|
|
'machine-update-state': (data: { machineId: string; expectedVersion: number; runnerState: unknown | null }, cb: (answer: MachineUpdateStateAck) => void) => void
|
|
/** The machine's `agy models` listing changed on a background re-check. */
|
|
'machine-agy-models-changed': (data: { machineId: string }) => void
|
|
'rpc-register': (data: { method: string }) => void
|
|
'rpc-unregister': (data: { method: string }) => void
|
|
'terminal:ready': (data: TerminalReadyPayload) => void
|
|
'terminal:output': (data: TerminalOutputPayload) => void
|
|
'terminal:exit': (data: TerminalExitPayload) => void
|
|
'terminal:error': (data: TerminalErrorPayload) => void
|
|
'agent-terminal:output': (data: TerminalOutputPayload) => void
|
|
// Drop the hub's scrollback buffer for this session (a new agent PTY just
|
|
// spawned, e.g. after archive→restart, so old output must not replay).
|
|
'agent-terminal:reset': (data: { sessionId: string }) => void
|
|
ping: (callback: () => void) => void
|
|
'usage-report': (data: unknown) => void
|
|
}
|