Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,15 @@ bun scripts/tooling/hapi-display-image.mjs /absolute/path/to/image.png "optional
hook falls back to a plain exec or to continuing in-process, and is logged.
Implementation: `src/runtime/disclaimExec.ts`, `src/runtime/responsibility.ts`.

- On Windows, Runner-spawned wrappers join a private Job Object before loading
the CLI or launching agents. The Runner and wrapper each hold a handle; a
normal Runner stop or crash does not kill the session. A new Runner reopens
the Job only when the original wrapper generation can still prove membership.
A missing handle or a root-only exit is not proof that descendants are gone.
Only an empty, verified Job authorizes generation-scoped Archive exit proof.
`StopSession` targets the Job, after shared-root protection, rather than a
list of PIDs. Legacy sessions do not gain Job ownership retroactively.

When changing agent bootstrap, handoff, or shared-session plumbing:

- One conversation keeps one HAPI session id. `HAPI_SESSION_ID` is exported into the agent process at bootstrap and cannot change afterwards, so a resume must pick the HAPI session *before* the agent starts. Terminal `hapi claude --resume <id>` / `--continue` look up the owning session (`GET /cli/sessions/resume-target-by-agent`, which also matches rotated-away ids in `claudeSessionIdHistory`) and reopen it with `--existing-session-id`, handing an active remote session over first, asking the hub to clear a hub-authored archive on an inactive one (`POST /cli/sessions/:id/prepare-local-resume`; bootstrap still refuses hub-archived rows), and refusing one already controlled by another terminal; bare `--resume` uses the `hapi resume` picker filtered to Claude. `--fork-session` and conversations unknown to HAPI start a new session. Implementation: `src/claude/resumeIdentity.ts`, `src/commands/resume.ts` (`prepareLocalResume`).
Expand Down
3 changes: 2 additions & 1 deletion cli/src/agent/sessionFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { getInvokedCwd } from '@/utils/invokedCwd'
import { getProcessStartMarker } from '@/utils/process'
import { readWorktreeEnv } from '@/utils/worktreeEnv'
import { CURRENT_MACHINE_CAPABILITIES } from '@hapi/protocol/runnerCapabilities'
import { windowsSessionWrapperMarker } from '@/runtime/windowsJobEntry'
import { exportHapiSessionEnv } from '@/agent/hapiSessionEnv'
import packageJson from '../../package.json'

Expand Down Expand Up @@ -137,7 +138,7 @@ export function buildSessionMetadata(options: {
// 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 }
? { hostStartMarker: windowsSessionWrapperMarker() ?? getProcessStartMarker(process.pid) ?? undefined }
: {}),
startedBy: options.startedBy,
lifecycleState: 'running',
Expand Down
7 changes: 4 additions & 3 deletions cli/src/api/apiMachine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@ type MachineRpcHandlers = {
/** Read-only exit probe — never tree-kills (#2658). */
probeSessionExit: (
sessionId: string,
opts?: { processStartMarker?: string }
) => Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown'>
opts?: { processStartMarker?: string; hubSessionId?: string; windowsJobOnly?: boolean }
) => Promise<'stopped' | 'already_gone' | 'still_alive' | 'unknown' | 'not_contained'>
requestShutdown: () => void
}

Expand Down Expand Up @@ -717,14 +717,15 @@ export class ApiMachineClient {
})

this.rpcHandlerManager.registerHandler(RPC_METHODS.ProbeSessionExit, async (params: any) => {
const { sessionId, processStartMarker, hubSessionId } = params || {}
const { sessionId, processStartMarker, hubSessionId, windowsJobOnly } = params || {}
if (!sessionId) {
throw new Error('Session ID is required')
}
const status = await probeSessionExit(
sessionId,
{
...(typeof processStartMarker === 'string' ? { processStartMarker } : {}),
...(windowsJobOnly === true ? { windowsJobOnly } : {}),
...(typeof hubSessionId === 'string' && hubSessionId.length > 0
? { hubSessionId }
: {}),
Expand Down
2 changes: 2 additions & 0 deletions cli/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
#!/usr/bin/env bun

import { handleDisclaimExecEntry, takeDisclaimFallbackNote } from './runtime/disclaimExec'
import { joinWindowsSessionJobAtEntry } from './runtime/windowsJobEntry'

async function main(): Promise<void> {
// Before the CLI module graph loads: the macOS responsibility re-exec must
// happen before any module side effects.
await handleDisclaimExecEntry()
await joinWindowsSessionJobAtEntry()
const fallbackNote = takeDisclaimFallbackNote()
// Dependency-free, so `--help` and `--version` work even when HAPI_HOME cannot be created.
const { captureLauncherPid } = await import('./runtime/launcherPid')
Expand Down
8 changes: 4 additions & 4 deletions cli/src/runner/orphanReap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,15 +341,15 @@ export async function reapRunnerSpawnedOrphans(
findTargets?: (sessionId: string) => Promise<OrphanTarget[] | 'scan_failed'>
/** @deprecated Prefer findTargets (includes same-snapshot markers). */
findOrphans?: (sessionId: string) => Promise<number[] | 'scan_failed'>
killTree?: (pid: number) => Promise<boolean>
killTree?: (pid: number, expectedMarker: string) => Promise<boolean>
prepare?: (target: OrphanTarget) => Promise<boolean>
getStartMarker?: (pid: number) => string | null | Promise<string | null>
isAlive?: (pid: number) => boolean | Promise<boolean>
} = {}
): Promise<'stopped' | 'still_alive' | null> {
const killTree = deps.killTree ?? (async (pid: number) => {
const killTree = deps.killTree ?? (async (pid: number, expectedMarker: string) => {
const { killProcessTreeByPid } = await import('@/utils/process')
return killProcessTreeByPid(pid)
return killProcessTreeByPid(pid, false, undefined, undefined, undefined, expectedMarker)
})
const getStartMarker = deps.getStartMarker ?? (process.platform === 'win32'
? async (pid: number) => (await readWindowsProcessTable(10_000, [pid]))?.get(pid)?.marker ?? null
Expand Down Expand Up @@ -439,7 +439,7 @@ export async function reapRunnerSpawnedOrphans(
const afterPrepare = normalizeStartMarker(await resolveStartMarker(getStartMarker, orphanPid))
if (afterPrepare !== expectedMarker) { anyUnconfirmed = true; continue }
}
if (!(await killTree(orphanPid))) {
if (!(await killTree(orphanPid, expectedMarker))) {
anyUnconfirmed = true
continue
}
Expand Down
Loading