@agimon-ai/doompi 0.0.1-alpha.106 → 0.0.1-alpha.108

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -596,6 +596,7 @@ async function runServerRuntime(options, runtime) {
596
596
  environment: sessionOptions.environment,
597
597
  directEvents: hub.directEvents,
598
598
  requestApi: (mount, basePath, request) => hub.requestApi(mount, basePath, request),
599
+ publishActivity: (activity) => hub.setSessionActivity?.(sessionOptions.sessionId, activity),
599
600
  ...computerUse === void 0 ? {} : { computerUse: {
600
601
  get available() {
601
602
  return computerUse.available;
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.cjs","names":["withShutdownDeadline","createServerExecutionBudget","ensureGlobalLogSink","createServerTelemetry","os","path","piAgentDirectory","createRequestReceipts","createWorkspaceRegistry","createOpenSessionRegistry","createHarnessTelemetry","createHeadlessSessionManager","publishHeadlessSelectionStatus","readMinorModeCatalog","createComputerUseBinding","createHeadlessHub","resolveProfile","createDefaultWorkspaceFolder","checkoutWorkspaceId","monitorRuntimeResources","fs","resolveSessionIdentity","crypto","globalDoomConfigDirectory","createWebCompositions","readSyncRegistration","resolveServerBundleSource","loadMajorModesConfig","resolveLayers","loadServerBundle","loadMcpBundle","readSyncDrift","readSyncState","createRemoteRuntime","WebSocket","findRepositoryRoot","identifyWorkspace","readWorkspaceMarker","HARNESS_STATE_POINTER","HARNESS_STATE_KEYS","readRegisteredBootstrapStatus","filterHookDisabledLayers","serveSessionApis","buildHarnessContext","sessionSelectionArgs","resolveSessionArtifact","listSavedSessionRecords","parseSyncRegistration","resolveSyncLocation","serveHeadlessServer","listSavedSessions","readSqliteTranscript","resolveWorktreeRestart"],"sources":["../../../../src/builders/server/runtime.ts"],"sourcesContent":["import crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { globalDoomConfigDirectory } from '@agimon-ai/doompi-config/config';\nimport { filterHookDisabledLayers, loadMajorModesConfig, resolveLayers } from '@agimon-ai/doompi-config/majorModes';\nimport { resolveProfile } from '@agimon-ai/doompi-config/profiles';\nimport { createHeadlessHub, type HeadlessHub } from '@agimon-ai/doompi-core/headlessHub';\nimport { serveHeadlessServer } from '@agimon-ai/doompi-core/headlessServer';\nimport type { HeadlessSessionHost, HeadlessSessionHostOptions } from '@agimon-ai/doompi-core/headlessSessionHost';\nimport { createHeadlessSessionManager } from '@agimon-ai/doompi-core/headlessSessionManager';\nimport {\n createOpenSessionRegistry,\n createRequestReceipts,\n createWorkspaceRegistry,\n identifyWorkspace,\n listSavedSessionRecords,\n listSavedSessions,\n readSqliteTranscript,\n readWorkspaceMarker,\n writeWorkspaceMarker,\n} from '@agimon-ai/doompi-core/history';\nimport type { OpenSessionRecord, SavedSessionExecution } from '@agimon-ai/doompi-core/history';\nimport type {\n DoomHubSessionApiRequest,\n DoomHubSessionCreateRequest,\n DoomHubSessionScope,\n} from '@agimon-ai/doompi-core/hubChannel';\nimport { loadMcpBundle, type LoadedMcpBundle } from '@agimon-ai/doompi-core/mcpFacet';\nimport { createServerExecutionBudget } from '@agimon-ai/doompi-core/packageApi';\nimport type { DoomHostMediaArbitration, DoomPeerAgentRegistry } from '@agimon-ai/doompi-core/packageApi';\nimport { serveSessionApis, type PackageApiServer } from '@agimon-ai/doompi-core/packageApiServer';\nimport { piAgentDirectory } from '@agimon-ai/doompi-core/piSettings';\nimport { createRemoteRuntime, type RemoteRuntime } from '@agimon-ai/doompi-core/remoteRuntime';\nimport type {\n HeadlessSessionCloseOptions,\n HeadlessSessionManager,\n} from '@agimon-ai/doompi-core/runtimeHeadlessSessionManager';\nimport { createHarnessTelemetry } from '@agimon-ai/doompi-core/runtimeLogSinkTelemetry';\nimport { loadServerBundle, resolveServerBundleSource } from '@agimon-ai/doompi-core/serverFacet';\nimport { createServerTelemetry } from '@agimon-ai/doompi-core/serverTelemetry';\nimport { resolveSyncLocation } from '@agimon-ai/doompi-core/syncLocation';\nimport {\n parseSyncRegistration,\n readSyncRegistration,\n validateSyncRegistration,\n type SyncRegistration,\n} from '@agimon-ai/doompi-core/syncRegistration';\nimport { createWebCompositions } from '@agimon-ai/doompi-core/webCompositions';\nimport { readMinorModeCatalog } from '@agimon-ai/doompi-minor-mode';\nimport WebSocket from 'ws';\n\nimport { HARNESS_STATE_KEYS, HARNESS_STATE_POINTER } from '../../composition/harnessState';\nimport { findRepositoryRoot } from '../../composition/repository';\nimport { readSyncDrift } from '../../composition/syncDrift';\nimport { readSyncState } from '../../composition/syncState';\nimport { readRegisteredBootstrapStatus } from '../cli/bootstrapLocator';\nimport { buildHarnessContext } from '../cli/harnessContext';\nimport { createComputerUseBinding } from './computerUseBinding';\nimport { createDefaultWorkspaceFolder } from './defaultWorkspace';\nimport { ensureGlobalLogSink } from './logSink';\nimport { monitorRuntimeResources } from './runtimeResources';\nimport { publishHeadlessSelectionStatus } from './selectionStatus';\nimport { type PinnedSelectionAxis, resolveSessionIdentity, sessionSelectionArgs } from './sessionArguments';\nimport { resolveSessionArtifact, resolveWorktreeRestart } from './sessionArtifact';\nimport { withShutdownDeadline } from './shutdown';\nimport type { ServeOptions, ServerRuntimeEnvironment } from './types';\nimport { checkoutWorkspaceId } from './workspaceCheckout';\n\nasync function bounded(operation: Promise<unknown>, label: string, notice: (message: string) => void): Promise<void> {\n try {\n await withShutdownDeadline(() => operation, label);\n } catch (error) {\n notice(`${label} failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\nexport async function runServerRuntime(options: ServeOptions, runtime: ServerRuntimeEnvironment): Promise<number> {\n const {\n cwd: baseCwd,\n environment: incomingEnvironment,\n notice,\n resolveHarnessOptions,\n signal,\n syncWorkspace,\n } = runtime;\n // Keep this selection local to this server and its admitted sessions. The\n // process environment may also serve unrelated hosts and must not be changed.\n const baseEnvironment: NodeJS.ProcessEnv = { ...incomingEnvironment, LOG_SINK_INSTANCE: 'global' };\n const executionBudget = createServerExecutionBudget(baseEnvironment);\n await ensureGlobalLogSink({ cwd: baseCwd, env: baseEnvironment, notice }).catch((error: unknown) =>\n notice(`Global log sink unavailable: ${error instanceof Error ? error.message : String(error)}`),\n );\n const telemetry = createServerTelemetry({ cwd: baseCwd, env: baseEnvironment, warn: notice });\n const homeDirectory = baseEnvironment.HOME ?? os.homedir();\n const serverDirectory = path.join(piAgentDirectory(baseEnvironment), 'server');\n // This native history has no agent lane and is deliberately outside the session-history catalog.\n const requestReceipts = createRequestReceipts({ directory: path.join(serverDirectory, 'request-receipts') });\n const activeMedia = new Set<() => boolean>();\n const mediaArbitration: DoomHostMediaArbitration = {\n register(busy) {\n activeMedia.add(busy);\n return () => {\n activeMedia.delete(busy);\n };\n },\n available(busy) {\n return activeMedia.has(busy) && [...activeMedia].every((other) => other === busy || !other());\n },\n };\n const activePeerAgents = new Map<string, { fetch(request: Request): Promise<Response>; hubToken: string }>();\n const peerAgents: DoomPeerAgentRegistry = {\n register(sessionId, agent, hubToken) {\n if (activePeerAgents.has(sessionId)) throw new Error(`Voice peer agent '${sessionId}' is already registered.`);\n const entry = { fetch: (request: Request) => agent.fetch(request), hubToken };\n activePeerAgents.set(sessionId, entry);\n return () => {\n if (activePeerAgents.get(sessionId) === entry) activePeerAgents.delete(sessionId);\n };\n },\n get: (sessionId) => activePeerAgents.get(sessionId),\n };\n const workspaces = createWorkspaceRegistry({ directory: serverDirectory, onNotice: notice });\n // Beside the journals it names, because a record pointing at a sessions\n // directory it is not stored next to is a record that can outlive its target.\n const openSessions = createOpenSessionRegistry({\n directory: serverDirectory,\n homeDirectory,\n onNotice: notice,\n });\n let lastBudgetSnapshot = '';\n let nextEventLoopTick = performance.now() + 1_000;\n const eventLoopMonitor = setInterval(() => {\n const now = performance.now();\n const budget = executionBudget.getSnapshot();\n const snapshot = JSON.stringify(budget);\n if (snapshot !== lastBudgetSnapshot) {\n lastBudgetSnapshot = snapshot;\n void telemetry\n .recordEvent('doompi_server.execution_budget', {\n host_pid: process.pid,\n running_jobs: budget.running,\n queued_jobs: budget.queued,\n limit: budget.limit,\n })\n .catch((error: unknown) => notice(`execution budget telemetry failed: ${String(error)}`));\n }\n const delay = Math.max(0, now - nextEventLoopTick);\n nextEventLoopTick = now + 1_000;\n if (delay >= 100)\n void telemetry\n .recordEvent('doompi_server.event_loop_delay', { duration_ms: Math.round(delay) })\n .catch((error: unknown) => notice(`event loop telemetry failed: ${String(error)}`));\n }, 1_000);\n eventLoopMonitor.unref();\n const harnessTelemetry = createHarnessTelemetry({\n cwd: baseCwd,\n env: baseEnvironment,\n warn: notice,\n deferSpans: true,\n });\n const baseSessionManager = createHeadlessSessionManager({\n publishSelectionStatus: publishHeadlessSelectionStatus,\n contextGroups: (context) =>\n (readMinorModeCatalog(context)?.list() ?? [])\n .filter(({ state }) => state.activation === 'active')\n .map(({ descriptor }) => ({ id: descriptor.id, label: descriptor.label, kind: 'minor' })),\n });\n type SessionSetup = {\n cleanup: () => Promise<void>;\n bundle: Awaited<ReturnType<typeof loadServerBundle>>;\n mcpBundle: LoadedMcpBundle;\n registration: SyncRegistration;\n };\n type SessionArtifacts = SessionSetup & { apis: PackageApiServer };\n const pendingSessions = new Map<string, SessionSetup>();\n const sessionArtifacts = new Map<string, SessionArtifacts>();\n let mountSessionApis:\n | ((options: HeadlessSessionHostOptions, host: HeadlessSessionHost) => Promise<PackageApiServer>)\n | undefined;\n /**\n * Shutdown runs every session through the same close path a user-initiated\n * close uses, so without this the registry would be emptied by the very event\n * it exists to survive.\n */\n let shuttingDown = false;\n\n const closeManagedSession = async (sessionId: string, options?: HeadlessSessionCloseOptions): Promise<void> => {\n // A released session keeps its record, which is what lists it as dormant.\n if (!shuttingDown && options?.keepDormant !== true) openSessions.remove(sessionId);\n const artifacts = sessionArtifacts.get(sessionId);\n sessionArtifacts.delete(sessionId);\n webCompositions?.remove({ scope: 'session', sessionId });\n const failures: unknown[] = [];\n // The host goes first, as on the create-failure path: it stops the running turn and\n // dispatches session_shutdown while the facets that own those hooks are still installed.\n try {\n await withShutdownDeadline(\n () => baseSessionManager.closeSession(sessionId),\n `Session '${sessionId}' runtime shutdown`,\n );\n } catch (error) {\n failures.push(error);\n }\n try {\n await withShutdownDeadline(() => artifacts?.apis.close(), `Session '${sessionId}' API shutdown`);\n } catch (error) {\n failures.push(error);\n }\n try {\n await withShutdownDeadline(() => artifacts?.cleanup(), `Session '${sessionId}' artifact cleanup`);\n } catch (error) {\n failures.push(error);\n }\n if (failures.length > 0) throw new AggregateError(failures, `Session '${sessionId}' shutdown failed`);\n };\n\n const sessionManager: HeadlessSessionManager = {\n async create(sessionOptions) {\n const setup = pendingSessions.get(sessionOptions.sessionId);\n let host: HeadlessSessionHost;\n try {\n host = await baseSessionManager.create(sessionOptions);\n } catch (error) {\n if (setup !== undefined && pendingSessions.delete(sessionOptions.sessionId))\n await setup.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n throw error;\n }\n if (setup === undefined || mountSessionApis === undefined) return host;\n try {\n const apis = await mountSessionApis(sessionOptions, host);\n pendingSessions.delete(sessionOptions.sessionId);\n sessionArtifacts.set(sessionOptions.sessionId, { ...setup, apis });\n return host;\n } catch (error) {\n pendingSessions.delete(sessionOptions.sessionId);\n await baseSessionManager\n .closeSession(sessionOptions.sessionId)\n .catch((closeError: unknown) => notice(String(closeError)));\n await setup.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n throw error;\n }\n },\n get: (sessionId) => baseSessionManager.get(sessionId),\n sessions: () => baseSessionManager.sessions(),\n closeSession: closeManagedSession,\n async close() {\n const ids = baseSessionManager.sessions().map((session) => session.runtime.sessionId);\n const outcomes = await Promise.allSettled(ids.map((id) => closeManagedSession(id)));\n const failures = outcomes\n .filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')\n .map((outcome) => outcome.reason);\n if (failures.length > 0) throw new AggregateError(failures, 'Headless session shutdown failed');\n },\n };\n\n let requestSessionApi: (\n scope: DoomHubSessionScope,\n request: DoomHubSessionApiRequest,\n ) => Promise<Response> = async () => Response.json({ error: 'Session API unavailable.' }, { status: 404 });\n let openSession: (\n request: DoomHubSessionCreateRequest,\n sessionId?: string,\n pinnedArtifact?: SyncRegistration,\n groupingWorkspaceId?: string,\n ) => Promise<DoomHubSessionScope> = async () => {\n throw new Error('The cockpit session service is not ready.');\n };\n let admitWorkspace: (\n root: string,\n name?: string,\n ) => Promise<{ id: string; root: string; name?: string; available: boolean }> = async () => {\n throw new Error('Workspace admission is not ready.');\n };\n const computerUse = await createComputerUseBinding();\n let hub!: HeadlessHub;\n hub = createHeadlessHub({\n manager: sessionManager,\n // Throws for an unknown profile; the hub reports that and shows the session without an avatar.\n resolveProfileIdentity: (root, profile) => {\n const identity = resolveProfile(root, profile, homeDirectory).identity;\n return identity === undefined ? undefined : { displayName: identity.name, icon: identity.icon };\n },\n admitWorkspace: async ({ root, name }) =>\n admitWorkspace(\n root === undefined || root.trim() === '' ? await createDefaultWorkspaceFolder(name ?? '', homeDirectory) : root,\n name,\n ),\n onWorkspaceRemoved: (workspaceId) => {\n workspaces.remove(workspaceId);\n webCompositions?.remove({ scope: 'workspace', workspaceId });\n },\n createSession: async (request, placement) => {\n if (placement === undefined) return openSession(request);\n // A workspace package's top-level session must run in a checkout of that same workspace.\n if (checkoutWorkspaceId(workspaces.list(), request.cwd) !== placement.workspaceId)\n throw new Error('The session directory is outside this workspace.');\n return openSession(request, undefined, undefined, placement.workspaceId);\n },\n sessionReservations: {\n read(id, parentSessionId) {\n if (!cockpit) throw new Error('Session setup is not ready.');\n return cockpit.sessionReservations.read(id, parentSessionId);\n },\n async prepare(id, parentSessionId, cwd) {\n if (!cockpit) throw new Error('Session setup is not ready.');\n return cockpit.sessionReservations.prepare(id, parentSessionId, cwd);\n },\n async complete(id, parentSessionId) {\n if (!cockpit) throw new Error('Session setup is not ready.');\n return cockpit.sessionReservations.complete(id, parentSessionId);\n },\n },\n onNotice: notice,\n hubToken: () => attachToken,\n requestSessionApi: (scope, request) => requestSessionApi(scope, request),\n ...(computerUse === undefined ? {} : { computerUse }),\n });\n const stopPersistSessionNames = hub.onEvent((event) => {\n if (event.kind !== 'upsert') return;\n const record = openSessions.list().find((entry) => entry.sessionId === event.session.id);\n if (record === undefined || record.name === event.session.name) return;\n openSessions.add({ ...record, name: event.session.name });\n });\n let harnessContext: Awaited<ReturnType<typeof buildHarnessContext>> | undefined;\n let cockpit: Awaited<ReturnType<typeof serveHeadlessServer>> | undefined;\n let remoteRuntime: RemoteRuntime | undefined;\n let attachToken: string | undefined;\n let webCompositions: ReturnType<typeof createWebCompositions> | undefined;\n const stopResourceMonitor = monitorRuntimeResources({\n record: (attributes) => telemetry.recordEvent('doompi_server.resources', attributes),\n counts: () => {\n const budget = executionBudget.getSnapshot();\n return {\n sessions: sessionManager.sessions().length,\n running_jobs: budget.running,\n queued_jobs: budget.queued,\n job_limit: budget.limit,\n };\n },\n warn: notice,\n });\n\n try {\n await telemetry.runInSpan('doompi_server.startup', {}, async () => {\n const token = fs.readFileSync(options.tokenFile, 'utf8').trim();\n if (!token) throw new Error('The attach token file is empty.');\n attachToken = token;\n\n const resolved = resolveSessionIdentity(options.agentArgs, {\n sessionId: options.sessionId ?? crypto.randomUUID(),\n sessionName: options.sessionName,\n });\n\n const globalRoot = globalDoomConfigDirectory(homeDirectory);\n webCompositions = createWebCompositions(path.join(globalRoot, 'server'), notice);\n const loadComposition = async (\n root: string,\n scope: 'global' | 'workspace' | 'session',\n selection?: { root: string; majorMode: string; activeLayers: string[] },\n pinnedRegistration?: SyncRegistration,\n ) => {\n const registration = pinnedRegistration ?? readSyncRegistration(root, homeDirectory);\n const source = resolveServerBundleSource({ registration });\n if (source.kind !== 'descriptor')\n throw new Error(`Run the scoped DoomPi sync for '${root}' before opening it.`);\n const selected =\n selection ??\n (() => {\n const config = loadMajorModesConfig(root, homeDirectory);\n const majorMode = config.defaultMajorMode;\n return { root, majorMode, activeLayers: resolveLayers(config, majorMode) };\n })();\n return telemetry.runInSpan('doompi_server.composition_load', { scope }, () =>\n loadServerBundle(scope, {\n ...source,\n ...selected,\n retainCandidates: scope === 'session',\n onNotice: notice,\n }),\n );\n };\n const loadSessionMcp = async (\n root: string,\n selection: { majorMode: string; activeLayers: readonly string[] },\n pinnedRegistration?: SyncRegistration,\n ): Promise<LoadedMcpBundle> => {\n const registration = pinnedRegistration ?? readSyncRegistration(root, homeDirectory);\n if (registration?.mcpBundle === undefined)\n throw new Error(`Run the scoped DoomPi sync for '${root}' before opening its MCP runtime.`);\n const bundle = registration.mcpBundle;\n return telemetry.runInSpan('doompi_server.mcp_bundle_load', {}, () =>\n loadMcpBundle({\n directory: path.dirname(bundle.path),\n generation: registration.generation,\n fingerprint: bundle.fingerprint,\n descriptorSha256: bundle.sha256,\n majorMode: selection.majorMode,\n activeLayers: selection.activeLayers,\n retainCandidates: true,\n onNotice: notice,\n }),\n );\n };\n const sharedApiContext = {\n homeDirectory,\n environment: baseEnvironment,\n hubToken: token,\n sessionService: hub.sessionService,\n mediaArbitration,\n executionBudget,\n peerAgents,\n directEvents: hub.directEvents,\n requestApi: (mount: Parameters<HeadlessHub['requestApi']>[0], basePath: string, request: Request) =>\n hub.requestApi(mount, basePath, request),\n repositories: () =>\n hub.workspaces().map((workspace) => ({\n id: workspace.id,\n path: workspace.root,\n name: workspace.root.split('/').at(-1) ?? workspace.id,\n active: hub.snapshot().some((session) => session.workspaceId === workspace.id),\n })),\n resolveRepository: (id: string) => hub.workspaces().find((workspace) => workspace.id === id)?.root,\n readRepositorySync: (id: string) => {\n const root = hub.workspaces().find((workspace) => workspace.id === id)?.root;\n if (!root) return undefined;\n const drift = readSyncDrift({ repoRoot: root, homeDirectory, requireWebBundle: true });\n const state = readSyncState(root, homeDirectory);\n return { ...drift, mcpProjection: state?.fileState.mcpProjection };\n },\n onNotice: notice,\n };\n const globalBundle = await loadComposition(globalRoot, 'global');\n webCompositions.publishShell(readSyncRegistration(globalRoot, homeDirectory)!);\n remoteRuntime = createRemoteRuntime({\n homeDirectory,\n registrationToken: token,\n reservedPorts: () => [options.webPort],\n bundleTrust: () => webCompositions?.shellTrust(),\n onNotice: notice,\n forward: async (request) => {\n if (!cockpit || !attachToken)\n return Response.json({ error: 'The headless server is not ready.' }, { status: 503 });\n const from = new URL(request.url);\n const headers = new Headers(request.headers);\n headers.set('x-doompi-token', attachToken);\n return fetch(\n new URL(`${from.pathname}${from.search}`, cockpit.url),\n new Request(request, { headers, redirect: 'manual' }),\n );\n },\n connectProtocol: (pathname) => {\n if (!cockpit || !attachToken) throw new Error('The headless protocol listener is not ready.');\n const url = new URL(pathname, cockpit.url);\n url.protocol = 'ws:';\n return new WebSocket(url, { headers: { 'x-doompi-token': attachToken } });\n },\n });\n await hub.mountFacets(globalBundle.facets, {\n ...sharedApiContext,\n scope: 'global',\n requestReceipts: requestReceipts.receipts,\n remoteControl: { fetch: (request: Request) => remoteRuntime!.fetchLocal(request) },\n });\n webCompositions.publish(\n { scope: 'global' },\n readSyncRegistration(globalRoot, homeDirectory)!,\n hub.channelTypes(),\n );\n const admissions = new Map<string, Promise<{ id: string; root: string; name?: string; available: boolean }>>();\n // A member checkout is any checkout other than its workspace root, such as a worktree.\n const isMemberCheckout = (from: string, workspace: { root: string }): boolean =>\n fs.realpathSync(findRepositoryRoot(from)) !== workspace.root;\n admitWorkspace = async (from, requestedName) => {\n const checkoutRoot = fs.realpathSync(findRepositoryRoot(from));\n // Ids are persisted, never re-derived from the path: a checkout of an admitted repository\n // joins its workspace, and a repository that moved keeps its id and sessions.\n const { id, root, moved } = identifyWorkspace({\n records: workspaces.list(),\n checkoutRoot,\n marker: readWorkspaceMarker(checkoutRoot),\n });\n const record = workspaces.list().find((workspace) => workspace.id === id);\n // A name given now replaces the stored one; readmitting without a name keeps it.\n const name = requestedName?.trim() || record?.name;\n const named = name === undefined ? {} : { name };\n const renamed = record !== undefined && name !== record.name;\n const existing = hub.workspaces().find((workspace) => workspace.id === id);\n if (existing !== undefined && existing.available !== false && existing.root === root) {\n if (renamed) {\n workspaces.add({ id, root, ...named });\n hub.registerWorkspace({ ...existing, ...named, available: true });\n }\n return { ...existing, ...named, available: true };\n }\n const pending = admissions.get(id);\n if (pending) return pending;\n const wasRemembered = record !== undefined;\n if (!wasRemembered || moved || renamed) workspaces.add({ id, root, ...named });\n if (moved) notice(`Workspace '${id}' moved to '${root}'.`);\n hub.registerWorkspace({ id, root, ...named, available: false });\n const admission = (async () => {\n const syncEnvironment: NodeJS.ProcessEnv = { ...baseEnvironment, DOOMPI_ROOT: root };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete syncEnvironment[key];\n await syncWorkspace(root, syncEnvironment);\n const bundle = await loadComposition(root, 'workspace');\n await hub.mountFacets(bundle.facets, {\n ...sharedApiContext,\n scope: 'workspace',\n workspaceId: id,\n workspaceRoot: root,\n cwd: root,\n resolveRepository: (requestedId) => (requestedId === id ? root : undefined),\n });\n webCompositions?.publish(\n { scope: 'workspace', workspaceId: id },\n readSyncRegistration(root, homeDirectory)!,\n hub.channelTypes(),\n );\n try {\n if (readWorkspaceMarker(root) === undefined) writeWorkspaceMarker(root, id);\n } catch (error) {\n notice(\n `Workspace '${root}' id could not be recorded in its git data: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return { id, root, ...named, available: true };\n })();\n admissions.set(id, admission);\n try {\n return await admission;\n } catch (error) {\n if (!wasRemembered) {\n await hub.removeWorkspace(id);\n workspaces.remove(id);\n }\n throw error;\n } finally {\n admissions.delete(id);\n }\n };\n for (const record of openSessions.list()) {\n if (workspaces.list().some((workspace) => workspace.id === record.workspaceId)) continue;\n try {\n const candidate = record.groupingRoot ?? record.artifact?.root ?? record.cwd;\n const root = fs.realpathSync(findRepositoryRoot(candidate));\n // The recorded id is kept as is. It may be a legacy path hash, and journals, open-session\n // records and MCP audiences all refer to it.\n if (\n (record.groupingRoot === undefined || root === candidate) &&\n !workspaces.list().some((workspace) => workspace.root === root)\n )\n workspaces.add({ id: record.workspaceId, root });\n else\n notice(\n `Session '${record.sessionId}' no longer resolves to its recorded workspace; skipping registration.`,\n );\n } catch (error) {\n notice(\n `Session '${record.sessionId}' workspace could not be registered: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n for (const workspace of workspaces.list()) {\n hub.registerWorkspace({ ...workspace, available: false });\n try {\n const root = fs.realpathSync(findRepositoryRoot(workspace.root));\n if (root !== workspace.root) {\n notice(\n `Workspace '${workspace.root}' no longer resolves to its recorded identity; leaving it unavailable.`,\n );\n continue;\n }\n await admitWorkspace(workspace.root);\n } catch (error) {\n notice(\n `Workspace '${workspace.root}' could not be restored: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n const sessionHostOptions = (\n context: Awaited<ReturnType<typeof buildHarnessContext>>,\n bundle: Awaited<ReturnType<typeof loadServerBundle>>,\n mcpBundle: LoadedMcpBundle,\n registration: SyncRegistration,\n identity: {\n sessionId: string;\n sessionName: string;\n parentSessionId?: string;\n sessionProvenance?: string;\n },\n workspace: { id: string; root: string },\n explicit: {\n pinned: readonly PinnedSelectionAxis[];\n minorModes?: readonly string[];\n allowedTools?: readonly string[];\n } = { pinned: [] },\n ): HeadlessSessionHostOptions => {\n const policyOptions = context.options;\n const sessionSelection = {\n root: policyOptions.repoRoot,\n majorMode: policyOptions.majorMode,\n activeLayers: context.selectedLayers,\n domains: policyOptions.domains,\n profile: context.profile,\n state: { 'minor-mode': [...(explicit.minorModes ?? [])] },\n };\n const piBootstrap = readRegisteredBootstrapStatus(registration, undefined, homeDirectory);\n if (!piBootstrap.fresh || piBootstrap.bootstrap === undefined) {\n throw new Error(`The admitted DoomPi bootstrap for generation '${registration.generation}' is unavailable.`);\n }\n return {\n cwd: policyOptions.cwd,\n repoRoot: policyOptions.repoRoot,\n sessionId: identity.sessionId,\n workspaceId: workspace.id,\n groupingRoot: workspace.root,\n // A member checkout runs its workspace's compiled composition, not one of its own.\n ...(isMemberCheckout(policyOptions.repoRoot, workspace) ? { inheritedArtifact: registration } : {}),\n sessionName: identity.sessionName,\n webComposition: webCompositions?.publish(\n { scope: 'session', sessionId: identity.sessionId },\n registration,\n hub.channelTypes(),\n ),\n ...(identity.parentSessionId === undefined ? {} : { parentSessionId: identity.parentSessionId }),\n ...(identity.sessionProvenance === undefined ? {} : { sessionProvenance: identity.sessionProvenance }),\n agentArgs: policyOptions.piArgs,\n environment: Object.freeze({ ...context.environment }),\n piExtensionPaths: [piBootstrap.bootstrap],\n selection: sessionSelection,\n ...(explicit.allowedTools === undefined ? {} : { allowedTools: explicit.allowedTools }),\n selectionOverrides: (['majorMode', 'domains', 'profile'] as const).filter((axis) => {\n if (explicit.pinned.includes(axis)) return true;\n const flag = axis === 'majorMode' ? '--major-mode' : `--${axis}`;\n return (\n identity.sessionId === resolved.identity.sessionId &&\n resolved.agentArgs.some((arg) => arg === flag || arg.startsWith(`${flag}=`))\n );\n }),\n inheritedSelection: () => {\n const environment = { ...baseEnvironment };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete environment[key];\n const defaults = resolveHarnessOptions({\n args: ['--cwd', policyOptions.cwd],\n cwd: policyOptions.cwd,\n environment,\n ...(policyOptions.configRoot === undefined ? {} : { configRoot: policyOptions.configRoot }),\n });\n return { majorMode: defaults.majorMode, domains: defaults.domains, profile: defaults.profile };\n },\n candidates: bundle.descriptor.entries,\n mcpPlugins: mcpBundle.plugins,\n resolveSelection: (requested) => {\n const config = loadMajorModesConfig(\n policyOptions.configRoot ?? policyOptions.repoRoot,\n policyOptions.homeDirectory,\n );\n return {\n ...requested,\n activeLayers: filterHookDisabledLayers(\n config,\n resolveLayers(config, requested.majorMode),\n policyOptions.hooks,\n ),\n };\n },\n onNotice: notice,\n };\n };\n\n mountSessionApis = (sessionOptions, host) =>\n serveSessionApis({\n sessionId: sessionOptions.sessionId,\n cwd: sessionOptions.cwd,\n environment: sessionOptions.environment,\n directEvents: hub.directEvents,\n requestApi: (mount, basePath, request) => hub.requestApi(mount, basePath, request),\n ...(computerUse === undefined\n ? {}\n : {\n computerUse: {\n get available() {\n return computerUse.available;\n },\n get enabled() {\n return computerUse.enabled === true;\n },\n authorize: (headers: Headers) => computerUse.authorize?.(headers) === true,\n claim: () => computerUse.claimSession?.(sessionOptions.sessionId),\n subscribe: (listener: () => void) => computerUse.subscribe?.(listener) ?? (() => undefined),\n },\n }),\n hubToken: token,\n sessionService: hub.sessionService,\n mediaArbitration,\n executionBudget,\n peerAgents,\n pluginRegistry: hub.pluginRegistry,\n apis: [],\n facets: pendingSessions.get(sessionOptions.sessionId)?.bundle.facets ?? [],\n workspaceId: sessionOptions.workspaceId,\n // The checkout, which MCP authorizes against; sessionContext carries both roots.\n workspaceRoot: sessionOptions.repoRoot,\n ...(host.sessionContext === undefined ? {} : { sessionContext: host.sessionContext }),\n homeDirectory,\n mountChannel: (channel) => {\n const dispose = hub.registerChannel(channel, { scope: 'session', sessionId: sessionOptions.sessionId });\n return { mounted: true, dispose };\n },\n prepareFacets: host.prepareFacets,\n activateFacets: host.activateFacets,\n canDispatch: host.canDispatch,\n telemetry,\n onNotice: notice,\n });\n\n requestSessionApi = async (scope, request) => {\n const session = hub.session(scope.sessionId);\n const artifacts = sessionArtifacts.get(scope.sessionId);\n if (session === undefined || session.cwd !== scope.cwd || artifacts === undefined)\n return Response.json({ error: 'Session not found.' }, { status: 404 });\n if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(request.basePath))\n return Response.json({ error: 'Invalid session API base path.' }, { status: 400 });\n if (!request.path.startsWith('/') || request.path.startsWith('//') || request.path.includes('#'))\n return Response.json({ error: 'Invalid session API path.' }, { status: 400 });\n const body = request.body === null || request.body === undefined ? undefined : request.body;\n return artifacts.apis.request(\n new Request(`http://doompi.local/api/plugins/${request.basePath}${request.path}`, {\n method: request.method,\n headers: request.headers,\n ...(body === undefined ? {} : { body }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n }),\n );\n };\n\n if (!options.noSession) {\n harnessContext = await buildHarnessContext(\n resolveHarnessOptions({ args: resolved.agentArgs, cwd: baseCwd, environment: baseEnvironment }),\n harnessTelemetry,\n );\n const activeHarnessContext = harnessContext;\n try {\n const initialWorkspace = await admitWorkspace(harnessContext.options.repoRoot);\n const initialRegistration = readSyncRegistration(initialWorkspace.root, homeDirectory);\n if (initialRegistration === undefined)\n throw new Error(`Run the scoped DoomPi sync for '${initialWorkspace.root}' before opening it.`);\n const initialBundle = await loadComposition(\n harnessContext.options.repoRoot,\n 'session',\n {\n root: harnessContext.options.repoRoot,\n majorMode: harnessContext.options.majorMode,\n activeLayers: harnessContext.selectedLayers,\n },\n initialRegistration,\n );\n const initialMcpBundle = await loadSessionMcp(\n harnessContext.options.repoRoot,\n {\n majorMode: harnessContext.options.majorMode,\n activeLayers: harnessContext.selectedLayers,\n },\n initialRegistration,\n );\n pendingSessions.set(resolved.identity.sessionId, {\n cleanup: () => activeHarnessContext.cleanup(),\n bundle: initialBundle,\n mcpBundle: initialMcpBundle,\n registration: initialRegistration,\n });\n await hub.create(\n sessionHostOptions(\n harnessContext,\n initialBundle,\n initialMcpBundle,\n initialRegistration,\n resolved.identity,\n initialWorkspace,\n ),\n );\n } catch (error) {\n pendingSessions.delete(resolved.identity.sessionId);\n await activeHarnessContext.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n throw error;\n }\n await bounded(harnessTelemetry.flush(), 'initial composition telemetry flush', notice);\n }\n\n const reservedOpens = new Map<string, Promise<DoomHubSessionScope>>();\n openSession = async (request, sessionId, pinnedArtifact, groupingWorkspaceId) => {\n request.signal?.throwIfAborted();\n if (request.reservationId !== undefined) {\n if (!request.parentSessionId || !cockpit) throw new Error('A reserved session requires its owning parent.');\n const prepared = await cockpit.sessionReservations.prepare(\n request.reservationId,\n request.parentSessionId,\n request.cwd,\n );\n if (sessionId !== undefined && sessionId !== prepared.sessionId)\n throw new Error('Reserved session identity cannot change.');\n sessionId = prepared.sessionId;\n const existing = hub.session(sessionId);\n if (existing) {\n if (existing.cwd !== prepared.cwd || existing.parentSessionId !== request.parentSessionId)\n throw new Error('Reserved session target does not match.');\n return { sessionId, cwd: existing.cwd, workspaceId: existing.workspaceId };\n }\n if (openSessions.list().some((record) => record.sessionId === sessionId))\n throw new Error('Resume the recorded session instead of recreating it.');\n const pending = reservedOpens.get(sessionId);\n if (pending) return pending;\n request = { ...request, cwd: prepared.cwd };\n }\n const identity = {\n sessionId: sessionId ?? crypto.randomUUID(),\n sessionName: request.name,\n parentSessionId: request.parentSessionId,\n sessionProvenance: request.sessionProvenance,\n };\n // Membership follows the parent link, whatever the session is called or wherever its\n // checkout lives. Without a known parent, the checkout's own identity decides.\n const inheritedWorkspaceId =\n groupingWorkspaceId ??\n (request.parentSessionId\n ? (hub.session(request.parentSessionId)?.workspaceId ??\n openSessions.list().find((record) => record.sessionId === request.parentSessionId)?.workspaceId)\n : undefined);\n const parentArtifact =\n request.parentSessionId === undefined\n ? undefined\n : (sessionArtifacts.get(request.parentSessionId)?.registration ??\n pendingSessions.get(request.parentSessionId)?.registration ??\n openSessions.list().find((record) => record.sessionId === request.parentSessionId)?.artifact);\n const explicit = sessionSelectionArgs(request);\n const start = (async (): Promise<DoomHubSessionScope> => {\n const childIdentity = resolveSessionIdentity([], identity);\n const childEnvironment = { ...baseEnvironment, ...request.environment };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete childEnvironment[key];\n // The workspace is settled first: a member checkout reads its workspace's configuration.\n const workspace =\n inheritedWorkspaceId === undefined\n ? await admitWorkspace(request.cwd)\n : hub\n .workspaces()\n .find((candidate) => candidate.id === inheritedWorkspaceId && candidate.available !== false);\n if (workspace === undefined) throw new Error('The session workspace is unavailable.');\n const member = isMemberCheckout(request.cwd, workspace);\n const childContext = await buildHarnessContext(\n resolveHarnessOptions({\n args: ['--cwd', request.cwd, ...childIdentity.agentArgs, ...explicit.args],\n cwd: request.cwd,\n environment: childEnvironment,\n ...(member ? { configRoot: workspace.root } : {}),\n }),\n harnessTelemetry,\n );\n try {\n const registration = await resolveSessionArtifact({\n member,\n pinned: pinnedArtifact,\n parent: parentArtifact,\n workspace: () => readSyncRegistration(workspace.root, homeDirectory),\n prepareCurrent: async () => {\n const current = readSyncRegistration(workspace.root, homeDirectory);\n if (current === undefined)\n throw new Error(`Run the scoped DoomPi sync for '${workspace.root}' before opening it.`);\n return current;\n },\n });\n const bundle = await loadComposition(\n childContext.options.repoRoot,\n 'session',\n {\n root: childContext.options.repoRoot,\n majorMode: childContext.options.majorMode,\n activeLayers: childContext.selectedLayers,\n },\n registration,\n );\n const mcpBundle = await loadSessionMcp(\n childContext.options.repoRoot,\n {\n majorMode: childContext.options.majorMode,\n activeLayers: childContext.selectedLayers,\n },\n registration,\n );\n request.signal?.throwIfAborted();\n pendingSessions.set(identity.sessionId, {\n cleanup: () => childContext.cleanup(),\n bundle,\n mcpBundle,\n registration,\n });\n const created = await hub.create(\n sessionHostOptions(childContext, bundle, mcpBundle, registration, identity, workspace, {\n pinned: explicit.pinned,\n ...(request.selection?.minorModes === undefined ? {} : { minorModes: request.selection.minorModes }),\n ...(request.tools === undefined ? {} : { allowedTools: request.tools }),\n }),\n );\n request.signal?.throwIfAborted();\n if (created.workspaceId !== undefined) {\n const saved = openSessions.add({\n sessionId: created.id,\n workspaceId: created.workspaceId,\n cwd: created.cwd,\n repoRoot: childContext.options.repoRoot,\n groupingRoot: workspace.root,\n name: created.name,\n createdAt: created.createdAt,\n ...(created.parentSessionId === undefined ? {} : { parentSessionId: created.parentSessionId }),\n ...(created.sessionProvenance === undefined ? {} : { sessionProvenance: created.sessionProvenance }),\n ...(member ? { artifact: registration } : {}),\n });\n if (saved === false) throw new Error('The new session could not be durably recorded.');\n }\n return { sessionId: identity.sessionId, cwd: childContext.options.cwd, workspaceId: created.workspaceId };\n } catch (error) {\n if (hub.session(identity.sessionId)) await hub.closeSession(identity.sessionId);\n else {\n pendingSessions.delete(identity.sessionId);\n await childContext.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n }\n throw error;\n }\n })();\n if (request.reservationId !== undefined) reservedOpens.set(identity.sessionId, start);\n try {\n return await start;\n } finally {\n if (reservedOpens.get(identity.sessionId) === start) reservedOpens.delete(identity.sessionId);\n }\n };\n });\n\n const workspaceResumes = new Map<string, Promise<string>>();\n const savedHistory = async (workspaceId: string) => {\n const root = hub\n .workspaces()\n .find((workspace) => workspace.id === workspaceId && workspace.available !== false)?.root;\n if (!root) throw new Error('Workspace not found.');\n return listSavedSessionRecords(\n path.join(serverDirectory, 'sessions'),\n root,\n new Set(hub.snapshot().map((active) => active.id)),\n workspaceId,\n );\n };\n const validatedExecution = (target: SavedSessionExecution, workspaceId: string): SyncRegistration | undefined => {\n const root = hub\n .workspaces()\n .find((workspace) => workspace.id === workspaceId && workspace.available !== false)?.root;\n if (!root || target.groupingRoot !== root || (target.workspaceId && target.workspaceId !== workspaceId))\n throw new Error('Saved session does not belong to this workspace.');\n if (fs.realpathSync(findRepositoryRoot(target.cwd)) !== target.repoRoot)\n throw new Error('Saved session checkout is unavailable.');\n // Only a member checkout records the workspace generation it ran.\n if (target.repoRoot === root) return undefined;\n if (target.inheritedArtifact === undefined) throw new Error('Saved member checkout generation is unavailable.');\n const artifact = parseSyncRegistration(target.inheritedArtifact, 'saved member checkout generation');\n validateSyncRegistration(artifact, resolveSyncLocation(artifact.root, homeDirectory));\n if (artifact.root !== root) throw new Error('Saved member checkout generation belongs to another workspace.');\n return artifact;\n };\n cockpit = await serveHeadlessServer({\n port: options.webPort,\n headlessHub: hub,\n token: attachToken,\n sessionMcpPublicOrigin: () => remoteRuntime?.remote.publicOrigin(),\n sessionMcpStateDir: serverDirectory,\n sessionMcpPublicOriginRevision: () => remoteRuntime?.remote.publicOriginRevision() ?? 0,\n isSessionPersisted: (sessionId, cwd) =>\n openSessions.list().some((record) => record.sessionId === sessionId && record.cwd === cwd),\n workspaceHistory: async (workspaceId) => (await savedHistory(workspaceId)).map((record) => record.summary),\n resumeWorkspaceSession: async (workspaceId, targetSessionId) => {\n const key = `${workspaceId}\\0${targetSessionId}`;\n const pending = workspaceResumes.get(key);\n if (pending) return pending;\n const resume = (async () => {\n const target = (await savedHistory(workspaceId)).find((item) => item.summary.id === targetSessionId);\n if (!target) throw new Error('Saved Pi thread not found in this workspace.');\n const artifact = validatedExecution(target.execution, workspaceId);\n await openSession(\n {\n cwd: target.execution.cwd,\n name: target.summary.name ?? 'untitled',\n ...(target.execution.parentSessionId ? { parentSessionId: target.execution.parentSessionId } : {}),\n ...(target.execution.sessionProvenance ? { sessionProvenance: target.execution.sessionProvenance } : {}),\n },\n target.summary.id,\n artifact,\n workspaceId,\n );\n return target.summary.id;\n })();\n workspaceResumes.set(key, resume);\n try {\n return await resume;\n } finally {\n workspaceResumes.delete(key);\n }\n },\n sessionHistory: (session) => {\n const workspaceRoot = hub.workspaces().find((workspace) => workspace.id === session.workspaceId)?.root;\n if (!workspaceRoot) throw new Error('Session workspace not found.');\n return listSavedSessions(\n path.join(piAgentDirectory(baseEnvironment), 'server', 'sessions'),\n workspaceRoot,\n new Set(hub.snapshot().map((active) => active.id)),\n session.workspaceId,\n );\n },\n readDormantTranscript: (record, request, context) => {\n const workspaceRoot = hub.workspaces().find((workspace) => workspace.id === record.workspaceId)?.root;\n if (!workspaceRoot || (record.groupingRoot !== undefined && record.groupingRoot !== workspaceRoot))\n throw new Error('Saved transcript unavailable.');\n const owner = fs.realpathSync(findRepositoryRoot(record.cwd));\n if (record.repoRoot !== undefined && record.repoRoot !== owner)\n throw new Error('Saved transcript checkout has changed.');\n return readSqliteTranscript(\n path.join(piAgentDirectory(baseEnvironment), 'server', 'sessions', `${record.sessionId}.sqlite`),\n request,\n context,\n {\n sessionId: record.sessionId,\n workspaceRoot: owner,\n workspaceId: record.workspaceId,\n groupingRoot: workspaceRoot,\n },\n );\n },\n restartSession: async (session) => {\n const record = openSessions.list().find((entry) => entry.sessionId === session.id);\n // Only a member checkout records an artifact; it restarts on its workspace's generation.\n const member = record?.artifact !== undefined;\n const ownership = member\n ? resolveWorktreeRestart({\n session,\n record,\n artifact: sessionArtifacts.get(session.id)?.registration,\n workspaces: hub.workspaces(),\n })\n : undefined;\n if (!member) {\n const workspaceRoot = hub.workspaces().find((workspace) => workspace.id === session.workspaceId)?.root;\n if (!workspaceRoot) throw new Error('Session workspace not found.');\n const syncEnvironment: NodeJS.ProcessEnv = { ...baseEnvironment, DOOMPI_ROOT: workspaceRoot };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete syncEnvironment[key];\n try {\n await syncWorkspace(workspaceRoot, syncEnvironment);\n } catch (error) {\n notice(`Workspace sync failed before restart: ${error instanceof Error ? error.message : String(error)}`);\n throw new Error('Workspace sync failed; the session is still running.', { cause: error });\n }\n }\n await hub.closeSession(session.id);\n try {\n await openSession(\n {\n cwd: session.cwd,\n name: session.name,\n ...(session.parentSessionId === undefined ? {} : { parentSessionId: session.parentSessionId }),\n ...(session.sessionProvenance === undefined ? {} : { sessionProvenance: session.sessionProvenance }),\n },\n session.id,\n ownership?.artifact,\n ownership?.workspaceId ?? session.workspaceId,\n );\n } catch (error) {\n // The journal lease allows one writer, so the new host cannot open before the old\n // one closes. Keep the closed session as dormant so it can be revived after a fix.\n if (record !== undefined) openSessions.add(record);\n throw error;\n }\n },\n resumeSession: async (session, targetSessionId) => {\n const workspaceId = session.workspaceId;\n if (!workspaceId || !hub.workspaces().some((workspace) => workspace.id === workspaceId))\n throw new Error('Session workspace not found.');\n const target = (await savedHistory(workspaceId)).find((item) => item.summary.id === targetSessionId);\n if (!target) throw new Error('Saved Pi thread not found in this workspace.');\n const artifact = validatedExecution(target.execution, workspaceId);\n const closedRecord = openSessions.list().find((entry) => entry.sessionId === session.id);\n await hub.closeSession(session.id);\n try {\n await openSession(\n {\n cwd: target.execution.cwd,\n name: target.summary.name ?? 'untitled',\n ...(target.execution.parentSessionId ? { parentSessionId: target.execution.parentSessionId } : {}),\n ...(target.execution.sessionProvenance ? { sessionProvenance: target.execution.sessionProvenance } : {}),\n },\n target.summary.id,\n artifact,\n workspaceId,\n );\n } catch (error) {\n // Same as restart: the session given up for the resume stays revivable.\n if (closedRecord !== undefined) openSessions.add(closedRecord);\n throw error;\n }\n return target.summary.id;\n },\n dormantSessions: () => openSessions.list(),\n removeDormantSession: (record: OpenSessionRecord) => openSessions.remove(record.sessionId),\n reviveSession: async (record: OpenSessionRecord) => {\n // A failed wake may be transient, for example while another server still\n // owns the journal. Keep the record so the user can retry after resolving\n // the conflict instead of losing the session from the cockpit.\n const groupingRoot = hub\n .workspaces()\n .find((workspace) => workspace.id === record.workspaceId && workspace.available !== false)?.root;\n if (!groupingRoot || (record.groupingRoot !== undefined && groupingRoot !== record.groupingRoot))\n throw new Error('The session workspace is unavailable.');\n if (record.repoRoot !== undefined && fs.realpathSync(findRepositoryRoot(record.cwd)) !== record.repoRoot)\n throw new Error('The session checkout has changed.');\n if (record.artifact !== undefined && record.artifact.root !== groupingRoot)\n throw new Error('The inherited workspace generation is unavailable.');\n await openSession(\n {\n cwd: record.cwd,\n name: record.name,\n ...(record.parentSessionId === undefined ? {} : { parentSessionId: record.parentSessionId }),\n ...(record.sessionProvenance === undefined ? {} : { sessionProvenance: record.sessionProvenance }),\n },\n record.sessionId,\n record.artifact,\n record.workspaceId,\n );\n },\n requestAsset: (request) => webCompositions?.request(request) ?? Promise.resolve(undefined),\n compositions: () => ({\n global: webCompositions?.get({ scope: 'global' }),\n publicKey: webCompositions?.publicKey(),\n shell: webCompositions?.shellTrust(),\n workspaces: hub.workspaces().map((workspace) => ({\n ...workspace,\n webComposition: webCompositions?.get({ scope: 'workspace', workspaceId: workspace.id }),\n })),\n }),\n telemetry,\n onNotice: notice,\n });\n notice(`protocol on ${cockpit.url}/api/ws`);\n let resolveShutdown!: (exitCode: number) => void;\n const shutdown = new Promise<number>((resolve) => {\n resolveShutdown = resolve;\n });\n const stop = (): void => resolveShutdown(0);\n signal.addEventListener('abort', stop, { once: true });\n if (signal.aborted) stop();\n try {\n return await shutdown;\n } finally {\n signal.removeEventListener('abort', stop);\n }\n } finally {\n shuttingDown = true;\n stopResourceMonitor();\n executionBudget.close();\n stopPersistSessionNames();\n clearInterval(eventLoopMonitor);\n await bounded(telemetry.recordEvent('doompi_server.shutdown'), 'shutdown telemetry', notice);\n await bounded(\n withShutdownDeadline(() => cockpit?.close(), 'listener shutdown'),\n 'listener shutdown',\n notice,\n );\n await bounded(remoteRuntime?.close() ?? Promise.resolve(), 'remote control shutdown', notice);\n // Session hooks and MCP owners must unwind before their shared hub services.\n // Each session phase has its own deadline, so one stalled session cannot block the rest.\n try {\n await sessionManager.close();\n } catch (error) {\n notice(error instanceof Error ? error.message : String(error));\n }\n await bounded(\n withShutdownDeadline(() => hub.close(), 'hub shutdown'),\n 'hub shutdown',\n notice,\n );\n await bounded(\n withShutdownDeadline(() => requestReceipts.close(), 'receipt shutdown'),\n 'receipt shutdown',\n notice,\n );\n await bounded(\n withShutdownDeadline(() => computerUse?.close?.(), 'computer use shutdown'),\n 'computer use shutdown',\n notice,\n );\n await bounded(\n withShutdownDeadline(() => webCompositions?.close(), 'web composition shutdown'),\n 'web composition shutdown',\n notice,\n );\n const pendingCleanups = [...pendingSessions.values()].map((setup) =>\n bounded(\n withShutdownDeadline(() => setup.cleanup(), 'pending session cleanup'),\n 'pending session cleanup',\n notice,\n ),\n );\n pendingSessions.clear();\n await Promise.allSettled(pendingCleanups);\n await bounded(harnessTelemetry.flush(), 'harness telemetry flush', notice);\n await bounded(harnessTelemetry.shutdown(), 'harness telemetry shutdown', notice);\n await bounded(telemetry.flush(), 'server telemetry flush', notice);\n await bounded(telemetry.shutdown(), 'server telemetry shutdown', notice);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,eAAe,QAAQ,WAA6B,OAAe,QAAkD;CACnH,IAAI;EACF,MAAMA,iBAAAA,2BAA2B,WAAW,KAAK;CACnD,SAAS,OAAO;EACd,OAAO,GAAG,MAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG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,GAAG,8BAA8B,MAAM;EAC/E,MAAM,QAAQ,UAAU,MAAM,GAAG,0BAA0B,MAAM;EACjE,MAAM,QAAQ,UAAU,SAAS,GAAG,6BAA6B,MAAM;CACzE;AACF"}
1
+ {"version":3,"file":"runtime.cjs","names":["withShutdownDeadline","createServerExecutionBudget","ensureGlobalLogSink","createServerTelemetry","os","path","piAgentDirectory","createRequestReceipts","createWorkspaceRegistry","createOpenSessionRegistry","createHarnessTelemetry","createHeadlessSessionManager","publishHeadlessSelectionStatus","readMinorModeCatalog","createComputerUseBinding","createHeadlessHub","resolveProfile","createDefaultWorkspaceFolder","checkoutWorkspaceId","monitorRuntimeResources","fs","resolveSessionIdentity","crypto","globalDoomConfigDirectory","createWebCompositions","readSyncRegistration","resolveServerBundleSource","loadMajorModesConfig","resolveLayers","loadServerBundle","loadMcpBundle","readSyncDrift","readSyncState","createRemoteRuntime","WebSocket","findRepositoryRoot","identifyWorkspace","readWorkspaceMarker","HARNESS_STATE_POINTER","HARNESS_STATE_KEYS","readRegisteredBootstrapStatus","filterHookDisabledLayers","serveSessionApis","buildHarnessContext","sessionSelectionArgs","resolveSessionArtifact","listSavedSessionRecords","parseSyncRegistration","resolveSyncLocation","serveHeadlessServer","listSavedSessions","readSqliteTranscript","resolveWorktreeRestart"],"sources":["../../../../src/builders/server/runtime.ts"],"sourcesContent":["import crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { globalDoomConfigDirectory } from '@agimon-ai/doompi-config/config';\nimport { filterHookDisabledLayers, loadMajorModesConfig, resolveLayers } from '@agimon-ai/doompi-config/majorModes';\nimport { resolveProfile } from '@agimon-ai/doompi-config/profiles';\nimport { createHeadlessHub, type HeadlessHub } from '@agimon-ai/doompi-core/headlessHub';\nimport { serveHeadlessServer } from '@agimon-ai/doompi-core/headlessServer';\nimport type { HeadlessSessionHost, HeadlessSessionHostOptions } from '@agimon-ai/doompi-core/headlessSessionHost';\nimport { createHeadlessSessionManager } from '@agimon-ai/doompi-core/headlessSessionManager';\nimport {\n createOpenSessionRegistry,\n createRequestReceipts,\n createWorkspaceRegistry,\n identifyWorkspace,\n listSavedSessionRecords,\n listSavedSessions,\n readSqliteTranscript,\n readWorkspaceMarker,\n writeWorkspaceMarker,\n} from '@agimon-ai/doompi-core/history';\nimport type { OpenSessionRecord, SavedSessionExecution } from '@agimon-ai/doompi-core/history';\nimport type {\n DoomHubSessionApiRequest,\n DoomHubSessionCreateRequest,\n DoomHubSessionScope,\n} from '@agimon-ai/doompi-core/hubChannel';\nimport { loadMcpBundle, type LoadedMcpBundle } from '@agimon-ai/doompi-core/mcpFacet';\nimport { createServerExecutionBudget } from '@agimon-ai/doompi-core/packageApi';\nimport type { DoomHostMediaArbitration, DoomPeerAgentRegistry } from '@agimon-ai/doompi-core/packageApi';\nimport { serveSessionApis, type PackageApiServer } from '@agimon-ai/doompi-core/packageApiServer';\nimport { piAgentDirectory } from '@agimon-ai/doompi-core/piSettings';\nimport { createRemoteRuntime, type RemoteRuntime } from '@agimon-ai/doompi-core/remoteRuntime';\nimport type {\n HeadlessSessionCloseOptions,\n HeadlessSessionManager,\n} from '@agimon-ai/doompi-core/runtimeHeadlessSessionManager';\nimport { createHarnessTelemetry } from '@agimon-ai/doompi-core/runtimeLogSinkTelemetry';\nimport { loadServerBundle, resolveServerBundleSource } from '@agimon-ai/doompi-core/serverFacet';\nimport { createServerTelemetry } from '@agimon-ai/doompi-core/serverTelemetry';\nimport { resolveSyncLocation } from '@agimon-ai/doompi-core/syncLocation';\nimport {\n parseSyncRegistration,\n readSyncRegistration,\n validateSyncRegistration,\n type SyncRegistration,\n} from '@agimon-ai/doompi-core/syncRegistration';\nimport { createWebCompositions } from '@agimon-ai/doompi-core/webCompositions';\nimport { readMinorModeCatalog } from '@agimon-ai/doompi-minor-mode';\nimport WebSocket from 'ws';\n\nimport { HARNESS_STATE_KEYS, HARNESS_STATE_POINTER } from '../../composition/harnessState';\nimport { findRepositoryRoot } from '../../composition/repository';\nimport { readSyncDrift } from '../../composition/syncDrift';\nimport { readSyncState } from '../../composition/syncState';\nimport { readRegisteredBootstrapStatus } from '../cli/bootstrapLocator';\nimport { buildHarnessContext } from '../cli/harnessContext';\nimport { createComputerUseBinding } from './computerUseBinding';\nimport { createDefaultWorkspaceFolder } from './defaultWorkspace';\nimport { ensureGlobalLogSink } from './logSink';\nimport { monitorRuntimeResources } from './runtimeResources';\nimport { publishHeadlessSelectionStatus } from './selectionStatus';\nimport { type PinnedSelectionAxis, resolveSessionIdentity, sessionSelectionArgs } from './sessionArguments';\nimport { resolveSessionArtifact, resolveWorktreeRestart } from './sessionArtifact';\nimport { withShutdownDeadline } from './shutdown';\nimport type { ServeOptions, ServerRuntimeEnvironment } from './types';\nimport { checkoutWorkspaceId } from './workspaceCheckout';\n\nasync function bounded(operation: Promise<unknown>, label: string, notice: (message: string) => void): Promise<void> {\n try {\n await withShutdownDeadline(() => operation, label);\n } catch (error) {\n notice(`${label} failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\nexport async function runServerRuntime(options: ServeOptions, runtime: ServerRuntimeEnvironment): Promise<number> {\n const {\n cwd: baseCwd,\n environment: incomingEnvironment,\n notice,\n resolveHarnessOptions,\n signal,\n syncWorkspace,\n } = runtime;\n // Keep this selection local to this server and its admitted sessions. The\n // process environment may also serve unrelated hosts and must not be changed.\n const baseEnvironment: NodeJS.ProcessEnv = { ...incomingEnvironment, LOG_SINK_INSTANCE: 'global' };\n const executionBudget = createServerExecutionBudget(baseEnvironment);\n await ensureGlobalLogSink({ cwd: baseCwd, env: baseEnvironment, notice }).catch((error: unknown) =>\n notice(`Global log sink unavailable: ${error instanceof Error ? error.message : String(error)}`),\n );\n const telemetry = createServerTelemetry({ cwd: baseCwd, env: baseEnvironment, warn: notice });\n const homeDirectory = baseEnvironment.HOME ?? os.homedir();\n const serverDirectory = path.join(piAgentDirectory(baseEnvironment), 'server');\n // This native history has no agent lane and is deliberately outside the session-history catalog.\n const requestReceipts = createRequestReceipts({ directory: path.join(serverDirectory, 'request-receipts') });\n const activeMedia = new Set<() => boolean>();\n const mediaArbitration: DoomHostMediaArbitration = {\n register(busy) {\n activeMedia.add(busy);\n return () => {\n activeMedia.delete(busy);\n };\n },\n available(busy) {\n return activeMedia.has(busy) && [...activeMedia].every((other) => other === busy || !other());\n },\n };\n const activePeerAgents = new Map<string, { fetch(request: Request): Promise<Response>; hubToken: string }>();\n const peerAgents: DoomPeerAgentRegistry = {\n register(sessionId, agent, hubToken) {\n if (activePeerAgents.has(sessionId)) throw new Error(`Voice peer agent '${sessionId}' is already registered.`);\n const entry = { fetch: (request: Request) => agent.fetch(request), hubToken };\n activePeerAgents.set(sessionId, entry);\n return () => {\n if (activePeerAgents.get(sessionId) === entry) activePeerAgents.delete(sessionId);\n };\n },\n get: (sessionId) => activePeerAgents.get(sessionId),\n };\n const workspaces = createWorkspaceRegistry({ directory: serverDirectory, onNotice: notice });\n // Beside the journals it names, because a record pointing at a sessions\n // directory it is not stored next to is a record that can outlive its target.\n const openSessions = createOpenSessionRegistry({\n directory: serverDirectory,\n homeDirectory,\n onNotice: notice,\n });\n let lastBudgetSnapshot = '';\n let nextEventLoopTick = performance.now() + 1_000;\n const eventLoopMonitor = setInterval(() => {\n const now = performance.now();\n const budget = executionBudget.getSnapshot();\n const snapshot = JSON.stringify(budget);\n if (snapshot !== lastBudgetSnapshot) {\n lastBudgetSnapshot = snapshot;\n void telemetry\n .recordEvent('doompi_server.execution_budget', {\n host_pid: process.pid,\n running_jobs: budget.running,\n queued_jobs: budget.queued,\n limit: budget.limit,\n })\n .catch((error: unknown) => notice(`execution budget telemetry failed: ${String(error)}`));\n }\n const delay = Math.max(0, now - nextEventLoopTick);\n nextEventLoopTick = now + 1_000;\n if (delay >= 100)\n void telemetry\n .recordEvent('doompi_server.event_loop_delay', { duration_ms: Math.round(delay) })\n .catch((error: unknown) => notice(`event loop telemetry failed: ${String(error)}`));\n }, 1_000);\n eventLoopMonitor.unref();\n const harnessTelemetry = createHarnessTelemetry({\n cwd: baseCwd,\n env: baseEnvironment,\n warn: notice,\n deferSpans: true,\n });\n const baseSessionManager = createHeadlessSessionManager({\n publishSelectionStatus: publishHeadlessSelectionStatus,\n contextGroups: (context) =>\n (readMinorModeCatalog(context)?.list() ?? [])\n .filter(({ state }) => state.activation === 'active')\n .map(({ descriptor }) => ({ id: descriptor.id, label: descriptor.label, kind: 'minor' })),\n });\n type SessionSetup = {\n cleanup: () => Promise<void>;\n bundle: Awaited<ReturnType<typeof loadServerBundle>>;\n mcpBundle: LoadedMcpBundle;\n registration: SyncRegistration;\n };\n type SessionArtifacts = SessionSetup & { apis: PackageApiServer };\n const pendingSessions = new Map<string, SessionSetup>();\n const sessionArtifacts = new Map<string, SessionArtifacts>();\n let mountSessionApis:\n | ((options: HeadlessSessionHostOptions, host: HeadlessSessionHost) => Promise<PackageApiServer>)\n | undefined;\n /**\n * Shutdown runs every session through the same close path a user-initiated\n * close uses, so without this the registry would be emptied by the very event\n * it exists to survive.\n */\n let shuttingDown = false;\n\n const closeManagedSession = async (sessionId: string, options?: HeadlessSessionCloseOptions): Promise<void> => {\n // A released session keeps its record, which is what lists it as dormant.\n if (!shuttingDown && options?.keepDormant !== true) openSessions.remove(sessionId);\n const artifacts = sessionArtifacts.get(sessionId);\n sessionArtifacts.delete(sessionId);\n webCompositions?.remove({ scope: 'session', sessionId });\n const failures: unknown[] = [];\n // The host goes first, as on the create-failure path: it stops the running turn and\n // dispatches session_shutdown while the facets that own those hooks are still installed.\n try {\n await withShutdownDeadline(\n () => baseSessionManager.closeSession(sessionId),\n `Session '${sessionId}' runtime shutdown`,\n );\n } catch (error) {\n failures.push(error);\n }\n try {\n await withShutdownDeadline(() => artifacts?.apis.close(), `Session '${sessionId}' API shutdown`);\n } catch (error) {\n failures.push(error);\n }\n try {\n await withShutdownDeadline(() => artifacts?.cleanup(), `Session '${sessionId}' artifact cleanup`);\n } catch (error) {\n failures.push(error);\n }\n if (failures.length > 0) throw new AggregateError(failures, `Session '${sessionId}' shutdown failed`);\n };\n\n const sessionManager: HeadlessSessionManager = {\n async create(sessionOptions) {\n const setup = pendingSessions.get(sessionOptions.sessionId);\n let host: HeadlessSessionHost;\n try {\n host = await baseSessionManager.create(sessionOptions);\n } catch (error) {\n if (setup !== undefined && pendingSessions.delete(sessionOptions.sessionId))\n await setup.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n throw error;\n }\n if (setup === undefined || mountSessionApis === undefined) return host;\n try {\n const apis = await mountSessionApis(sessionOptions, host);\n pendingSessions.delete(sessionOptions.sessionId);\n sessionArtifacts.set(sessionOptions.sessionId, { ...setup, apis });\n return host;\n } catch (error) {\n pendingSessions.delete(sessionOptions.sessionId);\n await baseSessionManager\n .closeSession(sessionOptions.sessionId)\n .catch((closeError: unknown) => notice(String(closeError)));\n await setup.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n throw error;\n }\n },\n get: (sessionId) => baseSessionManager.get(sessionId),\n sessions: () => baseSessionManager.sessions(),\n closeSession: closeManagedSession,\n async close() {\n const ids = baseSessionManager.sessions().map((session) => session.runtime.sessionId);\n const outcomes = await Promise.allSettled(ids.map((id) => closeManagedSession(id)));\n const failures = outcomes\n .filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')\n .map((outcome) => outcome.reason);\n if (failures.length > 0) throw new AggregateError(failures, 'Headless session shutdown failed');\n },\n };\n\n let requestSessionApi: (\n scope: DoomHubSessionScope,\n request: DoomHubSessionApiRequest,\n ) => Promise<Response> = async () => Response.json({ error: 'Session API unavailable.' }, { status: 404 });\n let openSession: (\n request: DoomHubSessionCreateRequest,\n sessionId?: string,\n pinnedArtifact?: SyncRegistration,\n groupingWorkspaceId?: string,\n ) => Promise<DoomHubSessionScope> = async () => {\n throw new Error('The cockpit session service is not ready.');\n };\n let admitWorkspace: (\n root: string,\n name?: string,\n ) => Promise<{ id: string; root: string; name?: string; available: boolean }> = async () => {\n throw new Error('Workspace admission is not ready.');\n };\n const computerUse = await createComputerUseBinding();\n let hub!: HeadlessHub;\n hub = createHeadlessHub({\n manager: sessionManager,\n // Throws for an unknown profile; the hub reports that and shows the session without an avatar.\n resolveProfileIdentity: (root, profile) => {\n const identity = resolveProfile(root, profile, homeDirectory).identity;\n return identity === undefined ? undefined : { displayName: identity.name, icon: identity.icon };\n },\n admitWorkspace: async ({ root, name }) =>\n admitWorkspace(\n root === undefined || root.trim() === '' ? await createDefaultWorkspaceFolder(name ?? '', homeDirectory) : root,\n name,\n ),\n onWorkspaceRemoved: (workspaceId) => {\n workspaces.remove(workspaceId);\n webCompositions?.remove({ scope: 'workspace', workspaceId });\n },\n createSession: async (request, placement) => {\n if (placement === undefined) return openSession(request);\n // A workspace package's top-level session must run in a checkout of that same workspace.\n if (checkoutWorkspaceId(workspaces.list(), request.cwd) !== placement.workspaceId)\n throw new Error('The session directory is outside this workspace.');\n return openSession(request, undefined, undefined, placement.workspaceId);\n },\n sessionReservations: {\n read(id, parentSessionId) {\n if (!cockpit) throw new Error('Session setup is not ready.');\n return cockpit.sessionReservations.read(id, parentSessionId);\n },\n async prepare(id, parentSessionId, cwd) {\n if (!cockpit) throw new Error('Session setup is not ready.');\n return cockpit.sessionReservations.prepare(id, parentSessionId, cwd);\n },\n async complete(id, parentSessionId) {\n if (!cockpit) throw new Error('Session setup is not ready.');\n return cockpit.sessionReservations.complete(id, parentSessionId);\n },\n },\n onNotice: notice,\n hubToken: () => attachToken,\n requestSessionApi: (scope, request) => requestSessionApi(scope, request),\n ...(computerUse === undefined ? {} : { computerUse }),\n });\n const stopPersistSessionNames = hub.onEvent((event) => {\n if (event.kind !== 'upsert') return;\n const record = openSessions.list().find((entry) => entry.sessionId === event.session.id);\n if (record === undefined || record.name === event.session.name) return;\n openSessions.add({ ...record, name: event.session.name });\n });\n let harnessContext: Awaited<ReturnType<typeof buildHarnessContext>> | undefined;\n let cockpit: Awaited<ReturnType<typeof serveHeadlessServer>> | undefined;\n let remoteRuntime: RemoteRuntime | undefined;\n let attachToken: string | undefined;\n let webCompositions: ReturnType<typeof createWebCompositions> | undefined;\n const stopResourceMonitor = monitorRuntimeResources({\n record: (attributes) => telemetry.recordEvent('doompi_server.resources', attributes),\n counts: () => {\n const budget = executionBudget.getSnapshot();\n return {\n sessions: sessionManager.sessions().length,\n running_jobs: budget.running,\n queued_jobs: budget.queued,\n job_limit: budget.limit,\n };\n },\n warn: notice,\n });\n\n try {\n await telemetry.runInSpan('doompi_server.startup', {}, async () => {\n const token = fs.readFileSync(options.tokenFile, 'utf8').trim();\n if (!token) throw new Error('The attach token file is empty.');\n attachToken = token;\n\n const resolved = resolveSessionIdentity(options.agentArgs, {\n sessionId: options.sessionId ?? crypto.randomUUID(),\n sessionName: options.sessionName,\n });\n\n const globalRoot = globalDoomConfigDirectory(homeDirectory);\n webCompositions = createWebCompositions(path.join(globalRoot, 'server'), notice);\n const loadComposition = async (\n root: string,\n scope: 'global' | 'workspace' | 'session',\n selection?: { root: string; majorMode: string; activeLayers: string[] },\n pinnedRegistration?: SyncRegistration,\n ) => {\n const registration = pinnedRegistration ?? readSyncRegistration(root, homeDirectory);\n const source = resolveServerBundleSource({ registration });\n if (source.kind !== 'descriptor')\n throw new Error(`Run the scoped DoomPi sync for '${root}' before opening it.`);\n const selected =\n selection ??\n (() => {\n const config = loadMajorModesConfig(root, homeDirectory);\n const majorMode = config.defaultMajorMode;\n return { root, majorMode, activeLayers: resolveLayers(config, majorMode) };\n })();\n return telemetry.runInSpan('doompi_server.composition_load', { scope }, () =>\n loadServerBundle(scope, {\n ...source,\n ...selected,\n retainCandidates: scope === 'session',\n onNotice: notice,\n }),\n );\n };\n const loadSessionMcp = async (\n root: string,\n selection: { majorMode: string; activeLayers: readonly string[] },\n pinnedRegistration?: SyncRegistration,\n ): Promise<LoadedMcpBundle> => {\n const registration = pinnedRegistration ?? readSyncRegistration(root, homeDirectory);\n if (registration?.mcpBundle === undefined)\n throw new Error(`Run the scoped DoomPi sync for '${root}' before opening its MCP runtime.`);\n const bundle = registration.mcpBundle;\n return telemetry.runInSpan('doompi_server.mcp_bundle_load', {}, () =>\n loadMcpBundle({\n directory: path.dirname(bundle.path),\n generation: registration.generation,\n fingerprint: bundle.fingerprint,\n descriptorSha256: bundle.sha256,\n majorMode: selection.majorMode,\n activeLayers: selection.activeLayers,\n retainCandidates: true,\n onNotice: notice,\n }),\n );\n };\n const sharedApiContext = {\n homeDirectory,\n environment: baseEnvironment,\n hubToken: token,\n sessionService: hub.sessionService,\n mediaArbitration,\n executionBudget,\n peerAgents,\n directEvents: hub.directEvents,\n requestApi: (mount: Parameters<HeadlessHub['requestApi']>[0], basePath: string, request: Request) =>\n hub.requestApi(mount, basePath, request),\n repositories: () =>\n hub.workspaces().map((workspace) => ({\n id: workspace.id,\n path: workspace.root,\n name: workspace.root.split('/').at(-1) ?? workspace.id,\n active: hub.snapshot().some((session) => session.workspaceId === workspace.id),\n })),\n resolveRepository: (id: string) => hub.workspaces().find((workspace) => workspace.id === id)?.root,\n readRepositorySync: (id: string) => {\n const root = hub.workspaces().find((workspace) => workspace.id === id)?.root;\n if (!root) return undefined;\n const drift = readSyncDrift({ repoRoot: root, homeDirectory, requireWebBundle: true });\n const state = readSyncState(root, homeDirectory);\n return { ...drift, mcpProjection: state?.fileState.mcpProjection };\n },\n onNotice: notice,\n };\n const globalBundle = await loadComposition(globalRoot, 'global');\n webCompositions.publishShell(readSyncRegistration(globalRoot, homeDirectory)!);\n remoteRuntime = createRemoteRuntime({\n homeDirectory,\n registrationToken: token,\n reservedPorts: () => [options.webPort],\n bundleTrust: () => webCompositions?.shellTrust(),\n onNotice: notice,\n forward: async (request) => {\n if (!cockpit || !attachToken)\n return Response.json({ error: 'The headless server is not ready.' }, { status: 503 });\n const from = new URL(request.url);\n const headers = new Headers(request.headers);\n headers.set('x-doompi-token', attachToken);\n return fetch(\n new URL(`${from.pathname}${from.search}`, cockpit.url),\n new Request(request, { headers, redirect: 'manual' }),\n );\n },\n connectProtocol: (pathname) => {\n if (!cockpit || !attachToken) throw new Error('The headless protocol listener is not ready.');\n const url = new URL(pathname, cockpit.url);\n url.protocol = 'ws:';\n return new WebSocket(url, { headers: { 'x-doompi-token': attachToken } });\n },\n });\n await hub.mountFacets(globalBundle.facets, {\n ...sharedApiContext,\n scope: 'global',\n requestReceipts: requestReceipts.receipts,\n remoteControl: { fetch: (request: Request) => remoteRuntime!.fetchLocal(request) },\n });\n webCompositions.publish(\n { scope: 'global' },\n readSyncRegistration(globalRoot, homeDirectory)!,\n hub.channelTypes(),\n );\n const admissions = new Map<string, Promise<{ id: string; root: string; name?: string; available: boolean }>>();\n // A member checkout is any checkout other than its workspace root, such as a worktree.\n const isMemberCheckout = (from: string, workspace: { root: string }): boolean =>\n fs.realpathSync(findRepositoryRoot(from)) !== workspace.root;\n admitWorkspace = async (from, requestedName) => {\n const checkoutRoot = fs.realpathSync(findRepositoryRoot(from));\n // Ids are persisted, never re-derived from the path: a checkout of an admitted repository\n // joins its workspace, and a repository that moved keeps its id and sessions.\n const { id, root, moved } = identifyWorkspace({\n records: workspaces.list(),\n checkoutRoot,\n marker: readWorkspaceMarker(checkoutRoot),\n });\n const record = workspaces.list().find((workspace) => workspace.id === id);\n // A name given now replaces the stored one; readmitting without a name keeps it.\n const name = requestedName?.trim() || record?.name;\n const named = name === undefined ? {} : { name };\n const renamed = record !== undefined && name !== record.name;\n const existing = hub.workspaces().find((workspace) => workspace.id === id);\n if (existing !== undefined && existing.available !== false && existing.root === root) {\n if (renamed) {\n workspaces.add({ id, root, ...named });\n hub.registerWorkspace({ ...existing, ...named, available: true });\n }\n return { ...existing, ...named, available: true };\n }\n const pending = admissions.get(id);\n if (pending) return pending;\n const wasRemembered = record !== undefined;\n if (!wasRemembered || moved || renamed) workspaces.add({ id, root, ...named });\n if (moved) notice(`Workspace '${id}' moved to '${root}'.`);\n hub.registerWorkspace({ id, root, ...named, available: false });\n const admission = (async () => {\n const syncEnvironment: NodeJS.ProcessEnv = { ...baseEnvironment, DOOMPI_ROOT: root };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete syncEnvironment[key];\n await syncWorkspace(root, syncEnvironment);\n const bundle = await loadComposition(root, 'workspace');\n await hub.mountFacets(bundle.facets, {\n ...sharedApiContext,\n scope: 'workspace',\n workspaceId: id,\n workspaceRoot: root,\n cwd: root,\n resolveRepository: (requestedId) => (requestedId === id ? root : undefined),\n });\n webCompositions?.publish(\n { scope: 'workspace', workspaceId: id },\n readSyncRegistration(root, homeDirectory)!,\n hub.channelTypes(),\n );\n try {\n if (readWorkspaceMarker(root) === undefined) writeWorkspaceMarker(root, id);\n } catch (error) {\n notice(\n `Workspace '${root}' id could not be recorded in its git data: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return { id, root, ...named, available: true };\n })();\n admissions.set(id, admission);\n try {\n return await admission;\n } catch (error) {\n if (!wasRemembered) {\n await hub.removeWorkspace(id);\n workspaces.remove(id);\n }\n throw error;\n } finally {\n admissions.delete(id);\n }\n };\n for (const record of openSessions.list()) {\n if (workspaces.list().some((workspace) => workspace.id === record.workspaceId)) continue;\n try {\n const candidate = record.groupingRoot ?? record.artifact?.root ?? record.cwd;\n const root = fs.realpathSync(findRepositoryRoot(candidate));\n // The recorded id is kept as is. It may be a legacy path hash, and journals, open-session\n // records and MCP audiences all refer to it.\n if (\n (record.groupingRoot === undefined || root === candidate) &&\n !workspaces.list().some((workspace) => workspace.root === root)\n )\n workspaces.add({ id: record.workspaceId, root });\n else\n notice(\n `Session '${record.sessionId}' no longer resolves to its recorded workspace; skipping registration.`,\n );\n } catch (error) {\n notice(\n `Session '${record.sessionId}' workspace could not be registered: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n for (const workspace of workspaces.list()) {\n hub.registerWorkspace({ ...workspace, available: false });\n try {\n const root = fs.realpathSync(findRepositoryRoot(workspace.root));\n if (root !== workspace.root) {\n notice(\n `Workspace '${workspace.root}' no longer resolves to its recorded identity; leaving it unavailable.`,\n );\n continue;\n }\n await admitWorkspace(workspace.root);\n } catch (error) {\n notice(\n `Workspace '${workspace.root}' could not be restored: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n const sessionHostOptions = (\n context: Awaited<ReturnType<typeof buildHarnessContext>>,\n bundle: Awaited<ReturnType<typeof loadServerBundle>>,\n mcpBundle: LoadedMcpBundle,\n registration: SyncRegistration,\n identity: {\n sessionId: string;\n sessionName: string;\n parentSessionId?: string;\n sessionProvenance?: string;\n },\n workspace: { id: string; root: string },\n explicit: {\n pinned: readonly PinnedSelectionAxis[];\n minorModes?: readonly string[];\n allowedTools?: readonly string[];\n } = { pinned: [] },\n ): HeadlessSessionHostOptions => {\n const policyOptions = context.options;\n const sessionSelection = {\n root: policyOptions.repoRoot,\n majorMode: policyOptions.majorMode,\n activeLayers: context.selectedLayers,\n domains: policyOptions.domains,\n profile: context.profile,\n state: { 'minor-mode': [...(explicit.minorModes ?? [])] },\n };\n const piBootstrap = readRegisteredBootstrapStatus(registration, undefined, homeDirectory);\n if (!piBootstrap.fresh || piBootstrap.bootstrap === undefined) {\n throw new Error(`The admitted DoomPi bootstrap for generation '${registration.generation}' is unavailable.`);\n }\n return {\n cwd: policyOptions.cwd,\n repoRoot: policyOptions.repoRoot,\n sessionId: identity.sessionId,\n workspaceId: workspace.id,\n groupingRoot: workspace.root,\n // A member checkout runs its workspace's compiled composition, not one of its own.\n ...(isMemberCheckout(policyOptions.repoRoot, workspace) ? { inheritedArtifact: registration } : {}),\n sessionName: identity.sessionName,\n webComposition: webCompositions?.publish(\n { scope: 'session', sessionId: identity.sessionId },\n registration,\n hub.channelTypes(),\n ),\n ...(identity.parentSessionId === undefined ? {} : { parentSessionId: identity.parentSessionId }),\n ...(identity.sessionProvenance === undefined ? {} : { sessionProvenance: identity.sessionProvenance }),\n agentArgs: policyOptions.piArgs,\n environment: Object.freeze({ ...context.environment }),\n piExtensionPaths: [piBootstrap.bootstrap],\n selection: sessionSelection,\n ...(explicit.allowedTools === undefined ? {} : { allowedTools: explicit.allowedTools }),\n selectionOverrides: (['majorMode', 'domains', 'profile'] as const).filter((axis) => {\n if (explicit.pinned.includes(axis)) return true;\n const flag = axis === 'majorMode' ? '--major-mode' : `--${axis}`;\n return (\n identity.sessionId === resolved.identity.sessionId &&\n resolved.agentArgs.some((arg) => arg === flag || arg.startsWith(`${flag}=`))\n );\n }),\n inheritedSelection: () => {\n const environment = { ...baseEnvironment };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete environment[key];\n const defaults = resolveHarnessOptions({\n args: ['--cwd', policyOptions.cwd],\n cwd: policyOptions.cwd,\n environment,\n ...(policyOptions.configRoot === undefined ? {} : { configRoot: policyOptions.configRoot }),\n });\n return { majorMode: defaults.majorMode, domains: defaults.domains, profile: defaults.profile };\n },\n candidates: bundle.descriptor.entries,\n mcpPlugins: mcpBundle.plugins,\n resolveSelection: (requested) => {\n const config = loadMajorModesConfig(\n policyOptions.configRoot ?? policyOptions.repoRoot,\n policyOptions.homeDirectory,\n );\n return {\n ...requested,\n activeLayers: filterHookDisabledLayers(\n config,\n resolveLayers(config, requested.majorMode),\n policyOptions.hooks,\n ),\n };\n },\n onNotice: notice,\n };\n };\n\n mountSessionApis = (sessionOptions, host) =>\n serveSessionApis({\n sessionId: sessionOptions.sessionId,\n cwd: sessionOptions.cwd,\n environment: sessionOptions.environment,\n directEvents: hub.directEvents,\n requestApi: (mount, basePath, request) => hub.requestApi(mount, basePath, request),\n publishActivity: (activity) => hub.setSessionActivity?.(sessionOptions.sessionId, activity),\n ...(computerUse === undefined\n ? {}\n : {\n computerUse: {\n get available() {\n return computerUse.available;\n },\n get enabled() {\n return computerUse.enabled === true;\n },\n authorize: (headers: Headers) => computerUse.authorize?.(headers) === true,\n claim: () => computerUse.claimSession?.(sessionOptions.sessionId),\n subscribe: (listener: () => void) => computerUse.subscribe?.(listener) ?? (() => undefined),\n },\n }),\n hubToken: token,\n sessionService: hub.sessionService,\n mediaArbitration,\n executionBudget,\n peerAgents,\n pluginRegistry: hub.pluginRegistry,\n apis: [],\n facets: pendingSessions.get(sessionOptions.sessionId)?.bundle.facets ?? [],\n workspaceId: sessionOptions.workspaceId,\n // The checkout, which MCP authorizes against; sessionContext carries both roots.\n workspaceRoot: sessionOptions.repoRoot,\n ...(host.sessionContext === undefined ? {} : { sessionContext: host.sessionContext }),\n homeDirectory,\n mountChannel: (channel) => {\n const dispose = hub.registerChannel(channel, { scope: 'session', sessionId: sessionOptions.sessionId });\n return { mounted: true, dispose };\n },\n prepareFacets: host.prepareFacets,\n activateFacets: host.activateFacets,\n canDispatch: host.canDispatch,\n telemetry,\n onNotice: notice,\n });\n\n requestSessionApi = async (scope, request) => {\n const session = hub.session(scope.sessionId);\n const artifacts = sessionArtifacts.get(scope.sessionId);\n if (session === undefined || session.cwd !== scope.cwd || artifacts === undefined)\n return Response.json({ error: 'Session not found.' }, { status: 404 });\n if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(request.basePath))\n return Response.json({ error: 'Invalid session API base path.' }, { status: 400 });\n if (!request.path.startsWith('/') || request.path.startsWith('//') || request.path.includes('#'))\n return Response.json({ error: 'Invalid session API path.' }, { status: 400 });\n const body = request.body === null || request.body === undefined ? undefined : request.body;\n return artifacts.apis.request(\n new Request(`http://doompi.local/api/plugins/${request.basePath}${request.path}`, {\n method: request.method,\n headers: request.headers,\n ...(body === undefined ? {} : { body }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n }),\n );\n };\n\n if (!options.noSession) {\n harnessContext = await buildHarnessContext(\n resolveHarnessOptions({ args: resolved.agentArgs, cwd: baseCwd, environment: baseEnvironment }),\n harnessTelemetry,\n );\n const activeHarnessContext = harnessContext;\n try {\n const initialWorkspace = await admitWorkspace(harnessContext.options.repoRoot);\n const initialRegistration = readSyncRegistration(initialWorkspace.root, homeDirectory);\n if (initialRegistration === undefined)\n throw new Error(`Run the scoped DoomPi sync for '${initialWorkspace.root}' before opening it.`);\n const initialBundle = await loadComposition(\n harnessContext.options.repoRoot,\n 'session',\n {\n root: harnessContext.options.repoRoot,\n majorMode: harnessContext.options.majorMode,\n activeLayers: harnessContext.selectedLayers,\n },\n initialRegistration,\n );\n const initialMcpBundle = await loadSessionMcp(\n harnessContext.options.repoRoot,\n {\n majorMode: harnessContext.options.majorMode,\n activeLayers: harnessContext.selectedLayers,\n },\n initialRegistration,\n );\n pendingSessions.set(resolved.identity.sessionId, {\n cleanup: () => activeHarnessContext.cleanup(),\n bundle: initialBundle,\n mcpBundle: initialMcpBundle,\n registration: initialRegistration,\n });\n await hub.create(\n sessionHostOptions(\n harnessContext,\n initialBundle,\n initialMcpBundle,\n initialRegistration,\n resolved.identity,\n initialWorkspace,\n ),\n );\n } catch (error) {\n pendingSessions.delete(resolved.identity.sessionId);\n await activeHarnessContext.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n throw error;\n }\n await bounded(harnessTelemetry.flush(), 'initial composition telemetry flush', notice);\n }\n\n const reservedOpens = new Map<string, Promise<DoomHubSessionScope>>();\n openSession = async (request, sessionId, pinnedArtifact, groupingWorkspaceId) => {\n request.signal?.throwIfAborted();\n if (request.reservationId !== undefined) {\n if (!request.parentSessionId || !cockpit) throw new Error('A reserved session requires its owning parent.');\n const prepared = await cockpit.sessionReservations.prepare(\n request.reservationId,\n request.parentSessionId,\n request.cwd,\n );\n if (sessionId !== undefined && sessionId !== prepared.sessionId)\n throw new Error('Reserved session identity cannot change.');\n sessionId = prepared.sessionId;\n const existing = hub.session(sessionId);\n if (existing) {\n if (existing.cwd !== prepared.cwd || existing.parentSessionId !== request.parentSessionId)\n throw new Error('Reserved session target does not match.');\n return { sessionId, cwd: existing.cwd, workspaceId: existing.workspaceId };\n }\n if (openSessions.list().some((record) => record.sessionId === sessionId))\n throw new Error('Resume the recorded session instead of recreating it.');\n const pending = reservedOpens.get(sessionId);\n if (pending) return pending;\n request = { ...request, cwd: prepared.cwd };\n }\n const identity = {\n sessionId: sessionId ?? crypto.randomUUID(),\n sessionName: request.name,\n parentSessionId: request.parentSessionId,\n sessionProvenance: request.sessionProvenance,\n };\n // Membership follows the parent link, whatever the session is called or wherever its\n // checkout lives. Without a known parent, the checkout's own identity decides.\n const inheritedWorkspaceId =\n groupingWorkspaceId ??\n (request.parentSessionId\n ? (hub.session(request.parentSessionId)?.workspaceId ??\n openSessions.list().find((record) => record.sessionId === request.parentSessionId)?.workspaceId)\n : undefined);\n const parentArtifact =\n request.parentSessionId === undefined\n ? undefined\n : (sessionArtifacts.get(request.parentSessionId)?.registration ??\n pendingSessions.get(request.parentSessionId)?.registration ??\n openSessions.list().find((record) => record.sessionId === request.parentSessionId)?.artifact);\n const explicit = sessionSelectionArgs(request);\n const start = (async (): Promise<DoomHubSessionScope> => {\n const childIdentity = resolveSessionIdentity([], identity);\n const childEnvironment = { ...baseEnvironment, ...request.environment };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete childEnvironment[key];\n // The workspace is settled first: a member checkout reads its workspace's configuration.\n const workspace =\n inheritedWorkspaceId === undefined\n ? await admitWorkspace(request.cwd)\n : hub\n .workspaces()\n .find((candidate) => candidate.id === inheritedWorkspaceId && candidate.available !== false);\n if (workspace === undefined) throw new Error('The session workspace is unavailable.');\n const member = isMemberCheckout(request.cwd, workspace);\n const childContext = await buildHarnessContext(\n resolveHarnessOptions({\n args: ['--cwd', request.cwd, ...childIdentity.agentArgs, ...explicit.args],\n cwd: request.cwd,\n environment: childEnvironment,\n ...(member ? { configRoot: workspace.root } : {}),\n }),\n harnessTelemetry,\n );\n try {\n const registration = await resolveSessionArtifact({\n member,\n pinned: pinnedArtifact,\n parent: parentArtifact,\n workspace: () => readSyncRegistration(workspace.root, homeDirectory),\n prepareCurrent: async () => {\n const current = readSyncRegistration(workspace.root, homeDirectory);\n if (current === undefined)\n throw new Error(`Run the scoped DoomPi sync for '${workspace.root}' before opening it.`);\n return current;\n },\n });\n const bundle = await loadComposition(\n childContext.options.repoRoot,\n 'session',\n {\n root: childContext.options.repoRoot,\n majorMode: childContext.options.majorMode,\n activeLayers: childContext.selectedLayers,\n },\n registration,\n );\n const mcpBundle = await loadSessionMcp(\n childContext.options.repoRoot,\n {\n majorMode: childContext.options.majorMode,\n activeLayers: childContext.selectedLayers,\n },\n registration,\n );\n request.signal?.throwIfAborted();\n pendingSessions.set(identity.sessionId, {\n cleanup: () => childContext.cleanup(),\n bundle,\n mcpBundle,\n registration,\n });\n const created = await hub.create(\n sessionHostOptions(childContext, bundle, mcpBundle, registration, identity, workspace, {\n pinned: explicit.pinned,\n ...(request.selection?.minorModes === undefined ? {} : { minorModes: request.selection.minorModes }),\n ...(request.tools === undefined ? {} : { allowedTools: request.tools }),\n }),\n );\n request.signal?.throwIfAborted();\n if (created.workspaceId !== undefined) {\n const saved = openSessions.add({\n sessionId: created.id,\n workspaceId: created.workspaceId,\n cwd: created.cwd,\n repoRoot: childContext.options.repoRoot,\n groupingRoot: workspace.root,\n name: created.name,\n createdAt: created.createdAt,\n ...(created.parentSessionId === undefined ? {} : { parentSessionId: created.parentSessionId }),\n ...(created.sessionProvenance === undefined ? {} : { sessionProvenance: created.sessionProvenance }),\n ...(member ? { artifact: registration } : {}),\n });\n if (saved === false) throw new Error('The new session could not be durably recorded.');\n }\n return { sessionId: identity.sessionId, cwd: childContext.options.cwd, workspaceId: created.workspaceId };\n } catch (error) {\n if (hub.session(identity.sessionId)) await hub.closeSession(identity.sessionId);\n else {\n pendingSessions.delete(identity.sessionId);\n await childContext.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n }\n throw error;\n }\n })();\n if (request.reservationId !== undefined) reservedOpens.set(identity.sessionId, start);\n try {\n return await start;\n } finally {\n if (reservedOpens.get(identity.sessionId) === start) reservedOpens.delete(identity.sessionId);\n }\n };\n });\n\n const workspaceResumes = new Map<string, Promise<string>>();\n const savedHistory = async (workspaceId: string) => {\n const root = hub\n .workspaces()\n .find((workspace) => workspace.id === workspaceId && workspace.available !== false)?.root;\n if (!root) throw new Error('Workspace not found.');\n return listSavedSessionRecords(\n path.join(serverDirectory, 'sessions'),\n root,\n new Set(hub.snapshot().map((active) => active.id)),\n workspaceId,\n );\n };\n const validatedExecution = (target: SavedSessionExecution, workspaceId: string): SyncRegistration | undefined => {\n const root = hub\n .workspaces()\n .find((workspace) => workspace.id === workspaceId && workspace.available !== false)?.root;\n if (!root || target.groupingRoot !== root || (target.workspaceId && target.workspaceId !== workspaceId))\n throw new Error('Saved session does not belong to this workspace.');\n if (fs.realpathSync(findRepositoryRoot(target.cwd)) !== target.repoRoot)\n throw new Error('Saved session checkout is unavailable.');\n // Only a member checkout records the workspace generation it ran.\n if (target.repoRoot === root) return undefined;\n if (target.inheritedArtifact === undefined) throw new Error('Saved member checkout generation is unavailable.');\n const artifact = parseSyncRegistration(target.inheritedArtifact, 'saved member checkout generation');\n validateSyncRegistration(artifact, resolveSyncLocation(artifact.root, homeDirectory));\n if (artifact.root !== root) throw new Error('Saved member checkout generation belongs to another workspace.');\n return artifact;\n };\n cockpit = await serveHeadlessServer({\n port: options.webPort,\n headlessHub: hub,\n token: attachToken,\n sessionMcpPublicOrigin: () => remoteRuntime?.remote.publicOrigin(),\n sessionMcpStateDir: serverDirectory,\n sessionMcpPublicOriginRevision: () => remoteRuntime?.remote.publicOriginRevision() ?? 0,\n isSessionPersisted: (sessionId, cwd) =>\n openSessions.list().some((record) => record.sessionId === sessionId && record.cwd === cwd),\n workspaceHistory: async (workspaceId) => (await savedHistory(workspaceId)).map((record) => record.summary),\n resumeWorkspaceSession: async (workspaceId, targetSessionId) => {\n const key = `${workspaceId}\\0${targetSessionId}`;\n const pending = workspaceResumes.get(key);\n if (pending) return pending;\n const resume = (async () => {\n const target = (await savedHistory(workspaceId)).find((item) => item.summary.id === targetSessionId);\n if (!target) throw new Error('Saved Pi thread not found in this workspace.');\n const artifact = validatedExecution(target.execution, workspaceId);\n await openSession(\n {\n cwd: target.execution.cwd,\n name: target.summary.name ?? 'untitled',\n ...(target.execution.parentSessionId ? { parentSessionId: target.execution.parentSessionId } : {}),\n ...(target.execution.sessionProvenance ? { sessionProvenance: target.execution.sessionProvenance } : {}),\n },\n target.summary.id,\n artifact,\n workspaceId,\n );\n return target.summary.id;\n })();\n workspaceResumes.set(key, resume);\n try {\n return await resume;\n } finally {\n workspaceResumes.delete(key);\n }\n },\n sessionHistory: (session) => {\n const workspaceRoot = hub.workspaces().find((workspace) => workspace.id === session.workspaceId)?.root;\n if (!workspaceRoot) throw new Error('Session workspace not found.');\n return listSavedSessions(\n path.join(piAgentDirectory(baseEnvironment), 'server', 'sessions'),\n workspaceRoot,\n new Set(hub.snapshot().map((active) => active.id)),\n session.workspaceId,\n );\n },\n readDormantTranscript: (record, request, context) => {\n const workspaceRoot = hub.workspaces().find((workspace) => workspace.id === record.workspaceId)?.root;\n if (!workspaceRoot || (record.groupingRoot !== undefined && record.groupingRoot !== workspaceRoot))\n throw new Error('Saved transcript unavailable.');\n const owner = fs.realpathSync(findRepositoryRoot(record.cwd));\n if (record.repoRoot !== undefined && record.repoRoot !== owner)\n throw new Error('Saved transcript checkout has changed.');\n return readSqliteTranscript(\n path.join(piAgentDirectory(baseEnvironment), 'server', 'sessions', `${record.sessionId}.sqlite`),\n request,\n context,\n {\n sessionId: record.sessionId,\n workspaceRoot: owner,\n workspaceId: record.workspaceId,\n groupingRoot: workspaceRoot,\n },\n );\n },\n restartSession: async (session) => {\n const record = openSessions.list().find((entry) => entry.sessionId === session.id);\n // Only a member checkout records an artifact; it restarts on its workspace's generation.\n const member = record?.artifact !== undefined;\n const ownership = member\n ? resolveWorktreeRestart({\n session,\n record,\n artifact: sessionArtifacts.get(session.id)?.registration,\n workspaces: hub.workspaces(),\n })\n : undefined;\n if (!member) {\n const workspaceRoot = hub.workspaces().find((workspace) => workspace.id === session.workspaceId)?.root;\n if (!workspaceRoot) throw new Error('Session workspace not found.');\n const syncEnvironment: NodeJS.ProcessEnv = { ...baseEnvironment, DOOMPI_ROOT: workspaceRoot };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete syncEnvironment[key];\n try {\n await syncWorkspace(workspaceRoot, syncEnvironment);\n } catch (error) {\n notice(`Workspace sync failed before restart: ${error instanceof Error ? error.message : String(error)}`);\n throw new Error('Workspace sync failed; the session is still running.', { cause: error });\n }\n }\n await hub.closeSession(session.id);\n try {\n await openSession(\n {\n cwd: session.cwd,\n name: session.name,\n ...(session.parentSessionId === undefined ? {} : { parentSessionId: session.parentSessionId }),\n ...(session.sessionProvenance === undefined ? {} : { sessionProvenance: session.sessionProvenance }),\n },\n session.id,\n ownership?.artifact,\n ownership?.workspaceId ?? session.workspaceId,\n );\n } catch (error) {\n // The journal lease allows one writer, so the new host cannot open before the old\n // one closes. Keep the closed session as dormant so it can be revived after a fix.\n if (record !== undefined) openSessions.add(record);\n throw error;\n }\n },\n resumeSession: async (session, targetSessionId) => {\n const workspaceId = session.workspaceId;\n if (!workspaceId || !hub.workspaces().some((workspace) => workspace.id === workspaceId))\n throw new Error('Session workspace not found.');\n const target = (await savedHistory(workspaceId)).find((item) => item.summary.id === targetSessionId);\n if (!target) throw new Error('Saved Pi thread not found in this workspace.');\n const artifact = validatedExecution(target.execution, workspaceId);\n const closedRecord = openSessions.list().find((entry) => entry.sessionId === session.id);\n await hub.closeSession(session.id);\n try {\n await openSession(\n {\n cwd: target.execution.cwd,\n name: target.summary.name ?? 'untitled',\n ...(target.execution.parentSessionId ? { parentSessionId: target.execution.parentSessionId } : {}),\n ...(target.execution.sessionProvenance ? { sessionProvenance: target.execution.sessionProvenance } : {}),\n },\n target.summary.id,\n artifact,\n workspaceId,\n );\n } catch (error) {\n // Same as restart: the session given up for the resume stays revivable.\n if (closedRecord !== undefined) openSessions.add(closedRecord);\n throw error;\n }\n return target.summary.id;\n },\n dormantSessions: () => openSessions.list(),\n removeDormantSession: (record: OpenSessionRecord) => openSessions.remove(record.sessionId),\n reviveSession: async (record: OpenSessionRecord) => {\n // A failed wake may be transient, for example while another server still\n // owns the journal. Keep the record so the user can retry after resolving\n // the conflict instead of losing the session from the cockpit.\n const groupingRoot = hub\n .workspaces()\n .find((workspace) => workspace.id === record.workspaceId && workspace.available !== false)?.root;\n if (!groupingRoot || (record.groupingRoot !== undefined && groupingRoot !== record.groupingRoot))\n throw new Error('The session workspace is unavailable.');\n if (record.repoRoot !== undefined && fs.realpathSync(findRepositoryRoot(record.cwd)) !== record.repoRoot)\n throw new Error('The session checkout has changed.');\n if (record.artifact !== undefined && record.artifact.root !== groupingRoot)\n throw new Error('The inherited workspace generation is unavailable.');\n await openSession(\n {\n cwd: record.cwd,\n name: record.name,\n ...(record.parentSessionId === undefined ? {} : { parentSessionId: record.parentSessionId }),\n ...(record.sessionProvenance === undefined ? {} : { sessionProvenance: record.sessionProvenance }),\n },\n record.sessionId,\n record.artifact,\n record.workspaceId,\n );\n },\n requestAsset: (request) => webCompositions?.request(request) ?? Promise.resolve(undefined),\n compositions: () => ({\n global: webCompositions?.get({ scope: 'global' }),\n publicKey: webCompositions?.publicKey(),\n shell: webCompositions?.shellTrust(),\n workspaces: hub.workspaces().map((workspace) => ({\n ...workspace,\n webComposition: webCompositions?.get({ scope: 'workspace', workspaceId: workspace.id }),\n })),\n }),\n telemetry,\n onNotice: notice,\n });\n notice(`protocol on ${cockpit.url}/api/ws`);\n let resolveShutdown!: (exitCode: number) => void;\n const shutdown = new Promise<number>((resolve) => {\n resolveShutdown = resolve;\n });\n const stop = (): void => resolveShutdown(0);\n signal.addEventListener('abort', stop, { once: true });\n if (signal.aborted) stop();\n try {\n return await shutdown;\n } finally {\n signal.removeEventListener('abort', stop);\n }\n } finally {\n shuttingDown = true;\n stopResourceMonitor();\n executionBudget.close();\n stopPersistSessionNames();\n clearInterval(eventLoopMonitor);\n await bounded(telemetry.recordEvent('doompi_server.shutdown'), 'shutdown telemetry', notice);\n await bounded(\n withShutdownDeadline(() => cockpit?.close(), 'listener shutdown'),\n 'listener shutdown',\n notice,\n );\n await bounded(remoteRuntime?.close() ?? Promise.resolve(), 'remote control shutdown', notice);\n // Session hooks and MCP owners must unwind before their shared hub services.\n // Each session phase has its own deadline, so one stalled session cannot block the rest.\n try {\n await sessionManager.close();\n } catch (error) {\n notice(error instanceof Error ? error.message : String(error));\n }\n await bounded(\n withShutdownDeadline(() => hub.close(), 'hub shutdown'),\n 'hub shutdown',\n notice,\n );\n await bounded(\n withShutdownDeadline(() => requestReceipts.close(), 'receipt shutdown'),\n 'receipt shutdown',\n notice,\n );\n await bounded(\n withShutdownDeadline(() => computerUse?.close?.(), 'computer use shutdown'),\n 'computer use shutdown',\n notice,\n );\n await bounded(\n withShutdownDeadline(() => webCompositions?.close(), 'web composition shutdown'),\n 'web composition shutdown',\n notice,\n );\n const pendingCleanups = [...pendingSessions.values()].map((setup) =>\n bounded(\n withShutdownDeadline(() => setup.cleanup(), 'pending session cleanup'),\n 'pending session cleanup',\n notice,\n ),\n );\n pendingSessions.clear();\n await Promise.allSettled(pendingCleanups);\n await bounded(harnessTelemetry.flush(), 'harness telemetry flush', notice);\n await bounded(harnessTelemetry.shutdown(), 'harness telemetry shutdown', notice);\n await bounded(telemetry.flush(), 'server telemetry flush', notice);\n await bounded(telemetry.shutdown(), 'server telemetry shutdown', notice);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,eAAe,QAAQ,WAA6B,OAAe,QAAkD;CACnH,IAAI;EACF,MAAMA,iBAAAA,2BAA2B,WAAW,KAAK;CACnD,SAAS,OAAO;EACd,OAAO,GAAG,MAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;CACrF;AACF;AAEA,eAAsB,iBAAiB,SAAuB,SAAoD;CAChH,MAAM,EACJ,KAAK,SACL,aAAa,qBACb,QACA,uBACA,QACA,kBACE;CAGJ,MAAM,kBAAqC;EAAE,GAAG;EAAqB,mBAAmB;CAAS;CACjG,MAAM,mBAAA,GAAkBC,kCAAAA,4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 +588,7 @@ async function runServerRuntime(options, runtime) {
588
588
  environment: sessionOptions.environment,
589
589
  directEvents: hub.directEvents,
590
590
  requestApi: (mount, basePath, request) => hub.requestApi(mount, basePath, request),
591
+ publishActivity: (activity) => hub.setSessionActivity?.(sessionOptions.sessionId, activity),
591
592
  ...computerUse === void 0 ? {} : { computerUse: {
592
593
  get available() {
593
594
  return computerUse.available;
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.mjs","names":[],"sources":["../../../../src/builders/server/runtime.ts"],"sourcesContent":["import crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { globalDoomConfigDirectory } from '@agimon-ai/doompi-config/config';\nimport { filterHookDisabledLayers, loadMajorModesConfig, resolveLayers } from '@agimon-ai/doompi-config/majorModes';\nimport { resolveProfile } from '@agimon-ai/doompi-config/profiles';\nimport { createHeadlessHub, type HeadlessHub } from '@agimon-ai/doompi-core/headlessHub';\nimport { serveHeadlessServer } from '@agimon-ai/doompi-core/headlessServer';\nimport type { HeadlessSessionHost, HeadlessSessionHostOptions } from '@agimon-ai/doompi-core/headlessSessionHost';\nimport { createHeadlessSessionManager } from '@agimon-ai/doompi-core/headlessSessionManager';\nimport {\n createOpenSessionRegistry,\n createRequestReceipts,\n createWorkspaceRegistry,\n identifyWorkspace,\n listSavedSessionRecords,\n listSavedSessions,\n readSqliteTranscript,\n readWorkspaceMarker,\n writeWorkspaceMarker,\n} from '@agimon-ai/doompi-core/history';\nimport type { OpenSessionRecord, SavedSessionExecution } from '@agimon-ai/doompi-core/history';\nimport type {\n DoomHubSessionApiRequest,\n DoomHubSessionCreateRequest,\n DoomHubSessionScope,\n} from '@agimon-ai/doompi-core/hubChannel';\nimport { loadMcpBundle, type LoadedMcpBundle } from '@agimon-ai/doompi-core/mcpFacet';\nimport { createServerExecutionBudget } from '@agimon-ai/doompi-core/packageApi';\nimport type { DoomHostMediaArbitration, DoomPeerAgentRegistry } from '@agimon-ai/doompi-core/packageApi';\nimport { serveSessionApis, type PackageApiServer } from '@agimon-ai/doompi-core/packageApiServer';\nimport { piAgentDirectory } from '@agimon-ai/doompi-core/piSettings';\nimport { createRemoteRuntime, type RemoteRuntime } from '@agimon-ai/doompi-core/remoteRuntime';\nimport type {\n HeadlessSessionCloseOptions,\n HeadlessSessionManager,\n} from '@agimon-ai/doompi-core/runtimeHeadlessSessionManager';\nimport { createHarnessTelemetry } from '@agimon-ai/doompi-core/runtimeLogSinkTelemetry';\nimport { loadServerBundle, resolveServerBundleSource } from '@agimon-ai/doompi-core/serverFacet';\nimport { createServerTelemetry } from '@agimon-ai/doompi-core/serverTelemetry';\nimport { resolveSyncLocation } from '@agimon-ai/doompi-core/syncLocation';\nimport {\n parseSyncRegistration,\n readSyncRegistration,\n validateSyncRegistration,\n type SyncRegistration,\n} from '@agimon-ai/doompi-core/syncRegistration';\nimport { createWebCompositions } from '@agimon-ai/doompi-core/webCompositions';\nimport { readMinorModeCatalog } from '@agimon-ai/doompi-minor-mode';\nimport WebSocket from 'ws';\n\nimport { HARNESS_STATE_KEYS, HARNESS_STATE_POINTER } from '../../composition/harnessState';\nimport { findRepositoryRoot } from '../../composition/repository';\nimport { readSyncDrift } from '../../composition/syncDrift';\nimport { readSyncState } from '../../composition/syncState';\nimport { readRegisteredBootstrapStatus } from '../cli/bootstrapLocator';\nimport { buildHarnessContext } from '../cli/harnessContext';\nimport { createComputerUseBinding } from './computerUseBinding';\nimport { createDefaultWorkspaceFolder } from './defaultWorkspace';\nimport { ensureGlobalLogSink } from './logSink';\nimport { monitorRuntimeResources } from './runtimeResources';\nimport { publishHeadlessSelectionStatus } from './selectionStatus';\nimport { type PinnedSelectionAxis, resolveSessionIdentity, sessionSelectionArgs } from './sessionArguments';\nimport { resolveSessionArtifact, resolveWorktreeRestart } from './sessionArtifact';\nimport { withShutdownDeadline } from './shutdown';\nimport type { ServeOptions, ServerRuntimeEnvironment } from './types';\nimport { checkoutWorkspaceId } from './workspaceCheckout';\n\nasync function bounded(operation: Promise<unknown>, label: string, notice: (message: string) => void): Promise<void> {\n try {\n await withShutdownDeadline(() => operation, label);\n } catch (error) {\n notice(`${label} failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\nexport async function runServerRuntime(options: ServeOptions, runtime: ServerRuntimeEnvironment): Promise<number> {\n const {\n cwd: baseCwd,\n environment: incomingEnvironment,\n notice,\n resolveHarnessOptions,\n signal,\n syncWorkspace,\n } = runtime;\n // Keep this selection local to this server and its admitted sessions. The\n // process environment may also serve unrelated hosts and must not be changed.\n const baseEnvironment: NodeJS.ProcessEnv = { ...incomingEnvironment, LOG_SINK_INSTANCE: 'global' };\n const executionBudget = createServerExecutionBudget(baseEnvironment);\n await ensureGlobalLogSink({ cwd: baseCwd, env: baseEnvironment, notice }).catch((error: unknown) =>\n notice(`Global log sink unavailable: ${error instanceof Error ? error.message : String(error)}`),\n );\n const telemetry = createServerTelemetry({ cwd: baseCwd, env: baseEnvironment, warn: notice });\n const homeDirectory = baseEnvironment.HOME ?? os.homedir();\n const serverDirectory = path.join(piAgentDirectory(baseEnvironment), 'server');\n // This native history has no agent lane and is deliberately outside the session-history catalog.\n const requestReceipts = createRequestReceipts({ directory: path.join(serverDirectory, 'request-receipts') });\n const activeMedia = new Set<() => boolean>();\n const mediaArbitration: DoomHostMediaArbitration = {\n register(busy) {\n activeMedia.add(busy);\n return () => {\n activeMedia.delete(busy);\n };\n },\n available(busy) {\n return activeMedia.has(busy) && [...activeMedia].every((other) => other === busy || !other());\n },\n };\n const activePeerAgents = new Map<string, { fetch(request: Request): Promise<Response>; hubToken: string }>();\n const peerAgents: DoomPeerAgentRegistry = {\n register(sessionId, agent, hubToken) {\n if (activePeerAgents.has(sessionId)) throw new Error(`Voice peer agent '${sessionId}' is already registered.`);\n const entry = { fetch: (request: Request) => agent.fetch(request), hubToken };\n activePeerAgents.set(sessionId, entry);\n return () => {\n if (activePeerAgents.get(sessionId) === entry) activePeerAgents.delete(sessionId);\n };\n },\n get: (sessionId) => activePeerAgents.get(sessionId),\n };\n const workspaces = createWorkspaceRegistry({ directory: serverDirectory, onNotice: notice });\n // Beside the journals it names, because a record pointing at a sessions\n // directory it is not stored next to is a record that can outlive its target.\n const openSessions = createOpenSessionRegistry({\n directory: serverDirectory,\n homeDirectory,\n onNotice: notice,\n });\n let lastBudgetSnapshot = '';\n let nextEventLoopTick = performance.now() + 1_000;\n const eventLoopMonitor = setInterval(() => {\n const now = performance.now();\n const budget = executionBudget.getSnapshot();\n const snapshot = JSON.stringify(budget);\n if (snapshot !== lastBudgetSnapshot) {\n lastBudgetSnapshot = snapshot;\n void telemetry\n .recordEvent('doompi_server.execution_budget', {\n host_pid: process.pid,\n running_jobs: budget.running,\n queued_jobs: budget.queued,\n limit: budget.limit,\n })\n .catch((error: unknown) => notice(`execution budget telemetry failed: ${String(error)}`));\n }\n const delay = Math.max(0, now - nextEventLoopTick);\n nextEventLoopTick = now + 1_000;\n if (delay >= 100)\n void telemetry\n .recordEvent('doompi_server.event_loop_delay', { duration_ms: Math.round(delay) })\n .catch((error: unknown) => notice(`event loop telemetry failed: ${String(error)}`));\n }, 1_000);\n eventLoopMonitor.unref();\n const harnessTelemetry = createHarnessTelemetry({\n cwd: baseCwd,\n env: baseEnvironment,\n warn: notice,\n deferSpans: true,\n });\n const baseSessionManager = createHeadlessSessionManager({\n publishSelectionStatus: publishHeadlessSelectionStatus,\n contextGroups: (context) =>\n (readMinorModeCatalog(context)?.list() ?? [])\n .filter(({ state }) => state.activation === 'active')\n .map(({ descriptor }) => ({ id: descriptor.id, label: descriptor.label, kind: 'minor' })),\n });\n type SessionSetup = {\n cleanup: () => Promise<void>;\n bundle: Awaited<ReturnType<typeof loadServerBundle>>;\n mcpBundle: LoadedMcpBundle;\n registration: SyncRegistration;\n };\n type SessionArtifacts = SessionSetup & { apis: PackageApiServer };\n const pendingSessions = new Map<string, SessionSetup>();\n const sessionArtifacts = new Map<string, SessionArtifacts>();\n let mountSessionApis:\n | ((options: HeadlessSessionHostOptions, host: HeadlessSessionHost) => Promise<PackageApiServer>)\n | undefined;\n /**\n * Shutdown runs every session through the same close path a user-initiated\n * close uses, so without this the registry would be emptied by the very event\n * it exists to survive.\n */\n let shuttingDown = false;\n\n const closeManagedSession = async (sessionId: string, options?: HeadlessSessionCloseOptions): Promise<void> => {\n // A released session keeps its record, which is what lists it as dormant.\n if (!shuttingDown && options?.keepDormant !== true) openSessions.remove(sessionId);\n const artifacts = sessionArtifacts.get(sessionId);\n sessionArtifacts.delete(sessionId);\n webCompositions?.remove({ scope: 'session', sessionId });\n const failures: unknown[] = [];\n // The host goes first, as on the create-failure path: it stops the running turn and\n // dispatches session_shutdown while the facets that own those hooks are still installed.\n try {\n await withShutdownDeadline(\n () => baseSessionManager.closeSession(sessionId),\n `Session '${sessionId}' runtime shutdown`,\n );\n } catch (error) {\n failures.push(error);\n }\n try {\n await withShutdownDeadline(() => artifacts?.apis.close(), `Session '${sessionId}' API shutdown`);\n } catch (error) {\n failures.push(error);\n }\n try {\n await withShutdownDeadline(() => artifacts?.cleanup(), `Session '${sessionId}' artifact cleanup`);\n } catch (error) {\n failures.push(error);\n }\n if (failures.length > 0) throw new AggregateError(failures, `Session '${sessionId}' shutdown failed`);\n };\n\n const sessionManager: HeadlessSessionManager = {\n async create(sessionOptions) {\n const setup = pendingSessions.get(sessionOptions.sessionId);\n let host: HeadlessSessionHost;\n try {\n host = await baseSessionManager.create(sessionOptions);\n } catch (error) {\n if (setup !== undefined && pendingSessions.delete(sessionOptions.sessionId))\n await setup.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n throw error;\n }\n if (setup === undefined || mountSessionApis === undefined) return host;\n try {\n const apis = await mountSessionApis(sessionOptions, host);\n pendingSessions.delete(sessionOptions.sessionId);\n sessionArtifacts.set(sessionOptions.sessionId, { ...setup, apis });\n return host;\n } catch (error) {\n pendingSessions.delete(sessionOptions.sessionId);\n await baseSessionManager\n .closeSession(sessionOptions.sessionId)\n .catch((closeError: unknown) => notice(String(closeError)));\n await setup.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n throw error;\n }\n },\n get: (sessionId) => baseSessionManager.get(sessionId),\n sessions: () => baseSessionManager.sessions(),\n closeSession: closeManagedSession,\n async close() {\n const ids = baseSessionManager.sessions().map((session) => session.runtime.sessionId);\n const outcomes = await Promise.allSettled(ids.map((id) => closeManagedSession(id)));\n const failures = outcomes\n .filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')\n .map((outcome) => outcome.reason);\n if (failures.length > 0) throw new AggregateError(failures, 'Headless session shutdown failed');\n },\n };\n\n let requestSessionApi: (\n scope: DoomHubSessionScope,\n request: DoomHubSessionApiRequest,\n ) => Promise<Response> = async () => Response.json({ error: 'Session API unavailable.' }, { status: 404 });\n let openSession: (\n request: DoomHubSessionCreateRequest,\n sessionId?: string,\n pinnedArtifact?: SyncRegistration,\n groupingWorkspaceId?: string,\n ) => Promise<DoomHubSessionScope> = async () => {\n throw new Error('The cockpit session service is not ready.');\n };\n let admitWorkspace: (\n root: string,\n name?: string,\n ) => Promise<{ id: string; root: string; name?: string; available: boolean }> = async () => {\n throw new Error('Workspace admission is not ready.');\n };\n const computerUse = await createComputerUseBinding();\n let hub!: HeadlessHub;\n hub = createHeadlessHub({\n manager: sessionManager,\n // Throws for an unknown profile; the hub reports that and shows the session without an avatar.\n resolveProfileIdentity: (root, profile) => {\n const identity = resolveProfile(root, profile, homeDirectory).identity;\n return identity === undefined ? undefined : { displayName: identity.name, icon: identity.icon };\n },\n admitWorkspace: async ({ root, name }) =>\n admitWorkspace(\n root === undefined || root.trim() === '' ? await createDefaultWorkspaceFolder(name ?? '', homeDirectory) : root,\n name,\n ),\n onWorkspaceRemoved: (workspaceId) => {\n workspaces.remove(workspaceId);\n webCompositions?.remove({ scope: 'workspace', workspaceId });\n },\n createSession: async (request, placement) => {\n if (placement === undefined) return openSession(request);\n // A workspace package's top-level session must run in a checkout of that same workspace.\n if (checkoutWorkspaceId(workspaces.list(), request.cwd) !== placement.workspaceId)\n throw new Error('The session directory is outside this workspace.');\n return openSession(request, undefined, undefined, placement.workspaceId);\n },\n sessionReservations: {\n read(id, parentSessionId) {\n if (!cockpit) throw new Error('Session setup is not ready.');\n return cockpit.sessionReservations.read(id, parentSessionId);\n },\n async prepare(id, parentSessionId, cwd) {\n if (!cockpit) throw new Error('Session setup is not ready.');\n return cockpit.sessionReservations.prepare(id, parentSessionId, cwd);\n },\n async complete(id, parentSessionId) {\n if (!cockpit) throw new Error('Session setup is not ready.');\n return cockpit.sessionReservations.complete(id, parentSessionId);\n },\n },\n onNotice: notice,\n hubToken: () => attachToken,\n requestSessionApi: (scope, request) => requestSessionApi(scope, request),\n ...(computerUse === undefined ? {} : { computerUse }),\n });\n const stopPersistSessionNames = hub.onEvent((event) => {\n if (event.kind !== 'upsert') return;\n const record = openSessions.list().find((entry) => entry.sessionId === event.session.id);\n if (record === undefined || record.name === event.session.name) return;\n openSessions.add({ ...record, name: event.session.name });\n });\n let harnessContext: Awaited<ReturnType<typeof buildHarnessContext>> | undefined;\n let cockpit: Awaited<ReturnType<typeof serveHeadlessServer>> | undefined;\n let remoteRuntime: RemoteRuntime | undefined;\n let attachToken: string | undefined;\n let webCompositions: ReturnType<typeof createWebCompositions> | undefined;\n const stopResourceMonitor = monitorRuntimeResources({\n record: (attributes) => telemetry.recordEvent('doompi_server.resources', attributes),\n counts: () => {\n const budget = executionBudget.getSnapshot();\n return {\n sessions: sessionManager.sessions().length,\n running_jobs: budget.running,\n queued_jobs: budget.queued,\n job_limit: budget.limit,\n };\n },\n warn: notice,\n });\n\n try {\n await telemetry.runInSpan('doompi_server.startup', {}, async () => {\n const token = fs.readFileSync(options.tokenFile, 'utf8').trim();\n if (!token) throw new Error('The attach token file is empty.');\n attachToken = token;\n\n const resolved = resolveSessionIdentity(options.agentArgs, {\n sessionId: options.sessionId ?? crypto.randomUUID(),\n sessionName: options.sessionName,\n });\n\n const globalRoot = globalDoomConfigDirectory(homeDirectory);\n webCompositions = createWebCompositions(path.join(globalRoot, 'server'), notice);\n const loadComposition = async (\n root: string,\n scope: 'global' | 'workspace' | 'session',\n selection?: { root: string; majorMode: string; activeLayers: string[] },\n pinnedRegistration?: SyncRegistration,\n ) => {\n const registration = pinnedRegistration ?? readSyncRegistration(root, homeDirectory);\n const source = resolveServerBundleSource({ registration });\n if (source.kind !== 'descriptor')\n throw new Error(`Run the scoped DoomPi sync for '${root}' before opening it.`);\n const selected =\n selection ??\n (() => {\n const config = loadMajorModesConfig(root, homeDirectory);\n const majorMode = config.defaultMajorMode;\n return { root, majorMode, activeLayers: resolveLayers(config, majorMode) };\n })();\n return telemetry.runInSpan('doompi_server.composition_load', { scope }, () =>\n loadServerBundle(scope, {\n ...source,\n ...selected,\n retainCandidates: scope === 'session',\n onNotice: notice,\n }),\n );\n };\n const loadSessionMcp = async (\n root: string,\n selection: { majorMode: string; activeLayers: readonly string[] },\n pinnedRegistration?: SyncRegistration,\n ): Promise<LoadedMcpBundle> => {\n const registration = pinnedRegistration ?? readSyncRegistration(root, homeDirectory);\n if (registration?.mcpBundle === undefined)\n throw new Error(`Run the scoped DoomPi sync for '${root}' before opening its MCP runtime.`);\n const bundle = registration.mcpBundle;\n return telemetry.runInSpan('doompi_server.mcp_bundle_load', {}, () =>\n loadMcpBundle({\n directory: path.dirname(bundle.path),\n generation: registration.generation,\n fingerprint: bundle.fingerprint,\n descriptorSha256: bundle.sha256,\n majorMode: selection.majorMode,\n activeLayers: selection.activeLayers,\n retainCandidates: true,\n onNotice: notice,\n }),\n );\n };\n const sharedApiContext = {\n homeDirectory,\n environment: baseEnvironment,\n hubToken: token,\n sessionService: hub.sessionService,\n mediaArbitration,\n executionBudget,\n peerAgents,\n directEvents: hub.directEvents,\n requestApi: (mount: Parameters<HeadlessHub['requestApi']>[0], basePath: string, request: Request) =>\n hub.requestApi(mount, basePath, request),\n repositories: () =>\n hub.workspaces().map((workspace) => ({\n id: workspace.id,\n path: workspace.root,\n name: workspace.root.split('/').at(-1) ?? workspace.id,\n active: hub.snapshot().some((session) => session.workspaceId === workspace.id),\n })),\n resolveRepository: (id: string) => hub.workspaces().find((workspace) => workspace.id === id)?.root,\n readRepositorySync: (id: string) => {\n const root = hub.workspaces().find((workspace) => workspace.id === id)?.root;\n if (!root) return undefined;\n const drift = readSyncDrift({ repoRoot: root, homeDirectory, requireWebBundle: true });\n const state = readSyncState(root, homeDirectory);\n return { ...drift, mcpProjection: state?.fileState.mcpProjection };\n },\n onNotice: notice,\n };\n const globalBundle = await loadComposition(globalRoot, 'global');\n webCompositions.publishShell(readSyncRegistration(globalRoot, homeDirectory)!);\n remoteRuntime = createRemoteRuntime({\n homeDirectory,\n registrationToken: token,\n reservedPorts: () => [options.webPort],\n bundleTrust: () => webCompositions?.shellTrust(),\n onNotice: notice,\n forward: async (request) => {\n if (!cockpit || !attachToken)\n return Response.json({ error: 'The headless server is not ready.' }, { status: 503 });\n const from = new URL(request.url);\n const headers = new Headers(request.headers);\n headers.set('x-doompi-token', attachToken);\n return fetch(\n new URL(`${from.pathname}${from.search}`, cockpit.url),\n new Request(request, { headers, redirect: 'manual' }),\n );\n },\n connectProtocol: (pathname) => {\n if (!cockpit || !attachToken) throw new Error('The headless protocol listener is not ready.');\n const url = new URL(pathname, cockpit.url);\n url.protocol = 'ws:';\n return new WebSocket(url, { headers: { 'x-doompi-token': attachToken } });\n },\n });\n await hub.mountFacets(globalBundle.facets, {\n ...sharedApiContext,\n scope: 'global',\n requestReceipts: requestReceipts.receipts,\n remoteControl: { fetch: (request: Request) => remoteRuntime!.fetchLocal(request) },\n });\n webCompositions.publish(\n { scope: 'global' },\n readSyncRegistration(globalRoot, homeDirectory)!,\n hub.channelTypes(),\n );\n const admissions = new Map<string, Promise<{ id: string; root: string; name?: string; available: boolean }>>();\n // A member checkout is any checkout other than its workspace root, such as a worktree.\n const isMemberCheckout = (from: string, workspace: { root: string }): boolean =>\n fs.realpathSync(findRepositoryRoot(from)) !== workspace.root;\n admitWorkspace = async (from, requestedName) => {\n const checkoutRoot = fs.realpathSync(findRepositoryRoot(from));\n // Ids are persisted, never re-derived from the path: a checkout of an admitted repository\n // joins its workspace, and a repository that moved keeps its id and sessions.\n const { id, root, moved } = identifyWorkspace({\n records: workspaces.list(),\n checkoutRoot,\n marker: readWorkspaceMarker(checkoutRoot),\n });\n const record = workspaces.list().find((workspace) => workspace.id === id);\n // A name given now replaces the stored one; readmitting without a name keeps it.\n const name = requestedName?.trim() || record?.name;\n const named = name === undefined ? {} : { name };\n const renamed = record !== undefined && name !== record.name;\n const existing = hub.workspaces().find((workspace) => workspace.id === id);\n if (existing !== undefined && existing.available !== false && existing.root === root) {\n if (renamed) {\n workspaces.add({ id, root, ...named });\n hub.registerWorkspace({ ...existing, ...named, available: true });\n }\n return { ...existing, ...named, available: true };\n }\n const pending = admissions.get(id);\n if (pending) return pending;\n const wasRemembered = record !== undefined;\n if (!wasRemembered || moved || renamed) workspaces.add({ id, root, ...named });\n if (moved) notice(`Workspace '${id}' moved to '${root}'.`);\n hub.registerWorkspace({ id, root, ...named, available: false });\n const admission = (async () => {\n const syncEnvironment: NodeJS.ProcessEnv = { ...baseEnvironment, DOOMPI_ROOT: root };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete syncEnvironment[key];\n await syncWorkspace(root, syncEnvironment);\n const bundle = await loadComposition(root, 'workspace');\n await hub.mountFacets(bundle.facets, {\n ...sharedApiContext,\n scope: 'workspace',\n workspaceId: id,\n workspaceRoot: root,\n cwd: root,\n resolveRepository: (requestedId) => (requestedId === id ? root : undefined),\n });\n webCompositions?.publish(\n { scope: 'workspace', workspaceId: id },\n readSyncRegistration(root, homeDirectory)!,\n hub.channelTypes(),\n );\n try {\n if (readWorkspaceMarker(root) === undefined) writeWorkspaceMarker(root, id);\n } catch (error) {\n notice(\n `Workspace '${root}' id could not be recorded in its git data: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return { id, root, ...named, available: true };\n })();\n admissions.set(id, admission);\n try {\n return await admission;\n } catch (error) {\n if (!wasRemembered) {\n await hub.removeWorkspace(id);\n workspaces.remove(id);\n }\n throw error;\n } finally {\n admissions.delete(id);\n }\n };\n for (const record of openSessions.list()) {\n if (workspaces.list().some((workspace) => workspace.id === record.workspaceId)) continue;\n try {\n const candidate = record.groupingRoot ?? record.artifact?.root ?? record.cwd;\n const root = fs.realpathSync(findRepositoryRoot(candidate));\n // The recorded id is kept as is. It may be a legacy path hash, and journals, open-session\n // records and MCP audiences all refer to it.\n if (\n (record.groupingRoot === undefined || root === candidate) &&\n !workspaces.list().some((workspace) => workspace.root === root)\n )\n workspaces.add({ id: record.workspaceId, root });\n else\n notice(\n `Session '${record.sessionId}' no longer resolves to its recorded workspace; skipping registration.`,\n );\n } catch (error) {\n notice(\n `Session '${record.sessionId}' workspace could not be registered: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n for (const workspace of workspaces.list()) {\n hub.registerWorkspace({ ...workspace, available: false });\n try {\n const root = fs.realpathSync(findRepositoryRoot(workspace.root));\n if (root !== workspace.root) {\n notice(\n `Workspace '${workspace.root}' no longer resolves to its recorded identity; leaving it unavailable.`,\n );\n continue;\n }\n await admitWorkspace(workspace.root);\n } catch (error) {\n notice(\n `Workspace '${workspace.root}' could not be restored: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n const sessionHostOptions = (\n context: Awaited<ReturnType<typeof buildHarnessContext>>,\n bundle: Awaited<ReturnType<typeof loadServerBundle>>,\n mcpBundle: LoadedMcpBundle,\n registration: SyncRegistration,\n identity: {\n sessionId: string;\n sessionName: string;\n parentSessionId?: string;\n sessionProvenance?: string;\n },\n workspace: { id: string; root: string },\n explicit: {\n pinned: readonly PinnedSelectionAxis[];\n minorModes?: readonly string[];\n allowedTools?: readonly string[];\n } = { pinned: [] },\n ): HeadlessSessionHostOptions => {\n const policyOptions = context.options;\n const sessionSelection = {\n root: policyOptions.repoRoot,\n majorMode: policyOptions.majorMode,\n activeLayers: context.selectedLayers,\n domains: policyOptions.domains,\n profile: context.profile,\n state: { 'minor-mode': [...(explicit.minorModes ?? [])] },\n };\n const piBootstrap = readRegisteredBootstrapStatus(registration, undefined, homeDirectory);\n if (!piBootstrap.fresh || piBootstrap.bootstrap === undefined) {\n throw new Error(`The admitted DoomPi bootstrap for generation '${registration.generation}' is unavailable.`);\n }\n return {\n cwd: policyOptions.cwd,\n repoRoot: policyOptions.repoRoot,\n sessionId: identity.sessionId,\n workspaceId: workspace.id,\n groupingRoot: workspace.root,\n // A member checkout runs its workspace's compiled composition, not one of its own.\n ...(isMemberCheckout(policyOptions.repoRoot, workspace) ? { inheritedArtifact: registration } : {}),\n sessionName: identity.sessionName,\n webComposition: webCompositions?.publish(\n { scope: 'session', sessionId: identity.sessionId },\n registration,\n hub.channelTypes(),\n ),\n ...(identity.parentSessionId === undefined ? {} : { parentSessionId: identity.parentSessionId }),\n ...(identity.sessionProvenance === undefined ? {} : { sessionProvenance: identity.sessionProvenance }),\n agentArgs: policyOptions.piArgs,\n environment: Object.freeze({ ...context.environment }),\n piExtensionPaths: [piBootstrap.bootstrap],\n selection: sessionSelection,\n ...(explicit.allowedTools === undefined ? {} : { allowedTools: explicit.allowedTools }),\n selectionOverrides: (['majorMode', 'domains', 'profile'] as const).filter((axis) => {\n if (explicit.pinned.includes(axis)) return true;\n const flag = axis === 'majorMode' ? '--major-mode' : `--${axis}`;\n return (\n identity.sessionId === resolved.identity.sessionId &&\n resolved.agentArgs.some((arg) => arg === flag || arg.startsWith(`${flag}=`))\n );\n }),\n inheritedSelection: () => {\n const environment = { ...baseEnvironment };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete environment[key];\n const defaults = resolveHarnessOptions({\n args: ['--cwd', policyOptions.cwd],\n cwd: policyOptions.cwd,\n environment,\n ...(policyOptions.configRoot === undefined ? {} : { configRoot: policyOptions.configRoot }),\n });\n return { majorMode: defaults.majorMode, domains: defaults.domains, profile: defaults.profile };\n },\n candidates: bundle.descriptor.entries,\n mcpPlugins: mcpBundle.plugins,\n resolveSelection: (requested) => {\n const config = loadMajorModesConfig(\n policyOptions.configRoot ?? policyOptions.repoRoot,\n policyOptions.homeDirectory,\n );\n return {\n ...requested,\n activeLayers: filterHookDisabledLayers(\n config,\n resolveLayers(config, requested.majorMode),\n policyOptions.hooks,\n ),\n };\n },\n onNotice: notice,\n };\n };\n\n mountSessionApis = (sessionOptions, host) =>\n serveSessionApis({\n sessionId: sessionOptions.sessionId,\n cwd: sessionOptions.cwd,\n environment: sessionOptions.environment,\n directEvents: hub.directEvents,\n requestApi: (mount, basePath, request) => hub.requestApi(mount, basePath, request),\n ...(computerUse === undefined\n ? {}\n : {\n computerUse: {\n get available() {\n return computerUse.available;\n },\n get enabled() {\n return computerUse.enabled === true;\n },\n authorize: (headers: Headers) => computerUse.authorize?.(headers) === true,\n claim: () => computerUse.claimSession?.(sessionOptions.sessionId),\n subscribe: (listener: () => void) => computerUse.subscribe?.(listener) ?? (() => undefined),\n },\n }),\n hubToken: token,\n sessionService: hub.sessionService,\n mediaArbitration,\n executionBudget,\n peerAgents,\n pluginRegistry: hub.pluginRegistry,\n apis: [],\n facets: pendingSessions.get(sessionOptions.sessionId)?.bundle.facets ?? [],\n workspaceId: sessionOptions.workspaceId,\n // The checkout, which MCP authorizes against; sessionContext carries both roots.\n workspaceRoot: sessionOptions.repoRoot,\n ...(host.sessionContext === undefined ? {} : { sessionContext: host.sessionContext }),\n homeDirectory,\n mountChannel: (channel) => {\n const dispose = hub.registerChannel(channel, { scope: 'session', sessionId: sessionOptions.sessionId });\n return { mounted: true, dispose };\n },\n prepareFacets: host.prepareFacets,\n activateFacets: host.activateFacets,\n canDispatch: host.canDispatch,\n telemetry,\n onNotice: notice,\n });\n\n requestSessionApi = async (scope, request) => {\n const session = hub.session(scope.sessionId);\n const artifacts = sessionArtifacts.get(scope.sessionId);\n if (session === undefined || session.cwd !== scope.cwd || artifacts === undefined)\n return Response.json({ error: 'Session not found.' }, { status: 404 });\n if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(request.basePath))\n return Response.json({ error: 'Invalid session API base path.' }, { status: 400 });\n if (!request.path.startsWith('/') || request.path.startsWith('//') || request.path.includes('#'))\n return Response.json({ error: 'Invalid session API path.' }, { status: 400 });\n const body = request.body === null || request.body === undefined ? undefined : request.body;\n return artifacts.apis.request(\n new Request(`http://doompi.local/api/plugins/${request.basePath}${request.path}`, {\n method: request.method,\n headers: request.headers,\n ...(body === undefined ? {} : { body }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n }),\n );\n };\n\n if (!options.noSession) {\n harnessContext = await buildHarnessContext(\n resolveHarnessOptions({ args: resolved.agentArgs, cwd: baseCwd, environment: baseEnvironment }),\n harnessTelemetry,\n );\n const activeHarnessContext = harnessContext;\n try {\n const initialWorkspace = await admitWorkspace(harnessContext.options.repoRoot);\n const initialRegistration = readSyncRegistration(initialWorkspace.root, homeDirectory);\n if (initialRegistration === undefined)\n throw new Error(`Run the scoped DoomPi sync for '${initialWorkspace.root}' before opening it.`);\n const initialBundle = await loadComposition(\n harnessContext.options.repoRoot,\n 'session',\n {\n root: harnessContext.options.repoRoot,\n majorMode: harnessContext.options.majorMode,\n activeLayers: harnessContext.selectedLayers,\n },\n initialRegistration,\n );\n const initialMcpBundle = await loadSessionMcp(\n harnessContext.options.repoRoot,\n {\n majorMode: harnessContext.options.majorMode,\n activeLayers: harnessContext.selectedLayers,\n },\n initialRegistration,\n );\n pendingSessions.set(resolved.identity.sessionId, {\n cleanup: () => activeHarnessContext.cleanup(),\n bundle: initialBundle,\n mcpBundle: initialMcpBundle,\n registration: initialRegistration,\n });\n await hub.create(\n sessionHostOptions(\n harnessContext,\n initialBundle,\n initialMcpBundle,\n initialRegistration,\n resolved.identity,\n initialWorkspace,\n ),\n );\n } catch (error) {\n pendingSessions.delete(resolved.identity.sessionId);\n await activeHarnessContext.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n throw error;\n }\n await bounded(harnessTelemetry.flush(), 'initial composition telemetry flush', notice);\n }\n\n const reservedOpens = new Map<string, Promise<DoomHubSessionScope>>();\n openSession = async (request, sessionId, pinnedArtifact, groupingWorkspaceId) => {\n request.signal?.throwIfAborted();\n if (request.reservationId !== undefined) {\n if (!request.parentSessionId || !cockpit) throw new Error('A reserved session requires its owning parent.');\n const prepared = await cockpit.sessionReservations.prepare(\n request.reservationId,\n request.parentSessionId,\n request.cwd,\n );\n if (sessionId !== undefined && sessionId !== prepared.sessionId)\n throw new Error('Reserved session identity cannot change.');\n sessionId = prepared.sessionId;\n const existing = hub.session(sessionId);\n if (existing) {\n if (existing.cwd !== prepared.cwd || existing.parentSessionId !== request.parentSessionId)\n throw new Error('Reserved session target does not match.');\n return { sessionId, cwd: existing.cwd, workspaceId: existing.workspaceId };\n }\n if (openSessions.list().some((record) => record.sessionId === sessionId))\n throw new Error('Resume the recorded session instead of recreating it.');\n const pending = reservedOpens.get(sessionId);\n if (pending) return pending;\n request = { ...request, cwd: prepared.cwd };\n }\n const identity = {\n sessionId: sessionId ?? crypto.randomUUID(),\n sessionName: request.name,\n parentSessionId: request.parentSessionId,\n sessionProvenance: request.sessionProvenance,\n };\n // Membership follows the parent link, whatever the session is called or wherever its\n // checkout lives. Without a known parent, the checkout's own identity decides.\n const inheritedWorkspaceId =\n groupingWorkspaceId ??\n (request.parentSessionId\n ? (hub.session(request.parentSessionId)?.workspaceId ??\n openSessions.list().find((record) => record.sessionId === request.parentSessionId)?.workspaceId)\n : undefined);\n const parentArtifact =\n request.parentSessionId === undefined\n ? undefined\n : (sessionArtifacts.get(request.parentSessionId)?.registration ??\n pendingSessions.get(request.parentSessionId)?.registration ??\n openSessions.list().find((record) => record.sessionId === request.parentSessionId)?.artifact);\n const explicit = sessionSelectionArgs(request);\n const start = (async (): Promise<DoomHubSessionScope> => {\n const childIdentity = resolveSessionIdentity([], identity);\n const childEnvironment = { ...baseEnvironment, ...request.environment };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete childEnvironment[key];\n // The workspace is settled first: a member checkout reads its workspace's configuration.\n const workspace =\n inheritedWorkspaceId === undefined\n ? await admitWorkspace(request.cwd)\n : hub\n .workspaces()\n .find((candidate) => candidate.id === inheritedWorkspaceId && candidate.available !== false);\n if (workspace === undefined) throw new Error('The session workspace is unavailable.');\n const member = isMemberCheckout(request.cwd, workspace);\n const childContext = await buildHarnessContext(\n resolveHarnessOptions({\n args: ['--cwd', request.cwd, ...childIdentity.agentArgs, ...explicit.args],\n cwd: request.cwd,\n environment: childEnvironment,\n ...(member ? { configRoot: workspace.root } : {}),\n }),\n harnessTelemetry,\n );\n try {\n const registration = await resolveSessionArtifact({\n member,\n pinned: pinnedArtifact,\n parent: parentArtifact,\n workspace: () => readSyncRegistration(workspace.root, homeDirectory),\n prepareCurrent: async () => {\n const current = readSyncRegistration(workspace.root, homeDirectory);\n if (current === undefined)\n throw new Error(`Run the scoped DoomPi sync for '${workspace.root}' before opening it.`);\n return current;\n },\n });\n const bundle = await loadComposition(\n childContext.options.repoRoot,\n 'session',\n {\n root: childContext.options.repoRoot,\n majorMode: childContext.options.majorMode,\n activeLayers: childContext.selectedLayers,\n },\n registration,\n );\n const mcpBundle = await loadSessionMcp(\n childContext.options.repoRoot,\n {\n majorMode: childContext.options.majorMode,\n activeLayers: childContext.selectedLayers,\n },\n registration,\n );\n request.signal?.throwIfAborted();\n pendingSessions.set(identity.sessionId, {\n cleanup: () => childContext.cleanup(),\n bundle,\n mcpBundle,\n registration,\n });\n const created = await hub.create(\n sessionHostOptions(childContext, bundle, mcpBundle, registration, identity, workspace, {\n pinned: explicit.pinned,\n ...(request.selection?.minorModes === undefined ? {} : { minorModes: request.selection.minorModes }),\n ...(request.tools === undefined ? {} : { allowedTools: request.tools }),\n }),\n );\n request.signal?.throwIfAborted();\n if (created.workspaceId !== undefined) {\n const saved = openSessions.add({\n sessionId: created.id,\n workspaceId: created.workspaceId,\n cwd: created.cwd,\n repoRoot: childContext.options.repoRoot,\n groupingRoot: workspace.root,\n name: created.name,\n createdAt: created.createdAt,\n ...(created.parentSessionId === undefined ? {} : { parentSessionId: created.parentSessionId }),\n ...(created.sessionProvenance === undefined ? {} : { sessionProvenance: created.sessionProvenance }),\n ...(member ? { artifact: registration } : {}),\n });\n if (saved === false) throw new Error('The new session could not be durably recorded.');\n }\n return { sessionId: identity.sessionId, cwd: childContext.options.cwd, workspaceId: created.workspaceId };\n } catch (error) {\n if (hub.session(identity.sessionId)) await hub.closeSession(identity.sessionId);\n else {\n pendingSessions.delete(identity.sessionId);\n await childContext.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n }\n throw error;\n }\n })();\n if (request.reservationId !== undefined) reservedOpens.set(identity.sessionId, start);\n try {\n return await start;\n } finally {\n if (reservedOpens.get(identity.sessionId) === start) reservedOpens.delete(identity.sessionId);\n }\n };\n });\n\n const workspaceResumes = new Map<string, Promise<string>>();\n const savedHistory = async (workspaceId: string) => {\n const root = hub\n .workspaces()\n .find((workspace) => workspace.id === workspaceId && workspace.available !== false)?.root;\n if (!root) throw new Error('Workspace not found.');\n return listSavedSessionRecords(\n path.join(serverDirectory, 'sessions'),\n root,\n new Set(hub.snapshot().map((active) => active.id)),\n workspaceId,\n );\n };\n const validatedExecution = (target: SavedSessionExecution, workspaceId: string): SyncRegistration | undefined => {\n const root = hub\n .workspaces()\n .find((workspace) => workspace.id === workspaceId && workspace.available !== false)?.root;\n if (!root || target.groupingRoot !== root || (target.workspaceId && target.workspaceId !== workspaceId))\n throw new Error('Saved session does not belong to this workspace.');\n if (fs.realpathSync(findRepositoryRoot(target.cwd)) !== target.repoRoot)\n throw new Error('Saved session checkout is unavailable.');\n // Only a member checkout records the workspace generation it ran.\n if (target.repoRoot === root) return undefined;\n if (target.inheritedArtifact === undefined) throw new Error('Saved member checkout generation is unavailable.');\n const artifact = parseSyncRegistration(target.inheritedArtifact, 'saved member checkout generation');\n validateSyncRegistration(artifact, resolveSyncLocation(artifact.root, homeDirectory));\n if (artifact.root !== root) throw new Error('Saved member checkout generation belongs to another workspace.');\n return artifact;\n };\n cockpit = await serveHeadlessServer({\n port: options.webPort,\n headlessHub: hub,\n token: attachToken,\n sessionMcpPublicOrigin: () => remoteRuntime?.remote.publicOrigin(),\n sessionMcpStateDir: serverDirectory,\n sessionMcpPublicOriginRevision: () => remoteRuntime?.remote.publicOriginRevision() ?? 0,\n isSessionPersisted: (sessionId, cwd) =>\n openSessions.list().some((record) => record.sessionId === sessionId && record.cwd === cwd),\n workspaceHistory: async (workspaceId) => (await savedHistory(workspaceId)).map((record) => record.summary),\n resumeWorkspaceSession: async (workspaceId, targetSessionId) => {\n const key = `${workspaceId}\\0${targetSessionId}`;\n const pending = workspaceResumes.get(key);\n if (pending) return pending;\n const resume = (async () => {\n const target = (await savedHistory(workspaceId)).find((item) => item.summary.id === targetSessionId);\n if (!target) throw new Error('Saved Pi thread not found in this workspace.');\n const artifact = validatedExecution(target.execution, workspaceId);\n await openSession(\n {\n cwd: target.execution.cwd,\n name: target.summary.name ?? 'untitled',\n ...(target.execution.parentSessionId ? { parentSessionId: target.execution.parentSessionId } : {}),\n ...(target.execution.sessionProvenance ? { sessionProvenance: target.execution.sessionProvenance } : {}),\n },\n target.summary.id,\n artifact,\n workspaceId,\n );\n return target.summary.id;\n })();\n workspaceResumes.set(key, resume);\n try {\n return await resume;\n } finally {\n workspaceResumes.delete(key);\n }\n },\n sessionHistory: (session) => {\n const workspaceRoot = hub.workspaces().find((workspace) => workspace.id === session.workspaceId)?.root;\n if (!workspaceRoot) throw new Error('Session workspace not found.');\n return listSavedSessions(\n path.join(piAgentDirectory(baseEnvironment), 'server', 'sessions'),\n workspaceRoot,\n new Set(hub.snapshot().map((active) => active.id)),\n session.workspaceId,\n );\n },\n readDormantTranscript: (record, request, context) => {\n const workspaceRoot = hub.workspaces().find((workspace) => workspace.id === record.workspaceId)?.root;\n if (!workspaceRoot || (record.groupingRoot !== undefined && record.groupingRoot !== workspaceRoot))\n throw new Error('Saved transcript unavailable.');\n const owner = fs.realpathSync(findRepositoryRoot(record.cwd));\n if (record.repoRoot !== undefined && record.repoRoot !== owner)\n throw new Error('Saved transcript checkout has changed.');\n return readSqliteTranscript(\n path.join(piAgentDirectory(baseEnvironment), 'server', 'sessions', `${record.sessionId}.sqlite`),\n request,\n context,\n {\n sessionId: record.sessionId,\n workspaceRoot: owner,\n workspaceId: record.workspaceId,\n groupingRoot: workspaceRoot,\n },\n );\n },\n restartSession: async (session) => {\n const record = openSessions.list().find((entry) => entry.sessionId === session.id);\n // Only a member checkout records an artifact; it restarts on its workspace's generation.\n const member = record?.artifact !== undefined;\n const ownership = member\n ? resolveWorktreeRestart({\n session,\n record,\n artifact: sessionArtifacts.get(session.id)?.registration,\n workspaces: hub.workspaces(),\n })\n : undefined;\n if (!member) {\n const workspaceRoot = hub.workspaces().find((workspace) => workspace.id === session.workspaceId)?.root;\n if (!workspaceRoot) throw new Error('Session workspace not found.');\n const syncEnvironment: NodeJS.ProcessEnv = { ...baseEnvironment, DOOMPI_ROOT: workspaceRoot };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete syncEnvironment[key];\n try {\n await syncWorkspace(workspaceRoot, syncEnvironment);\n } catch (error) {\n notice(`Workspace sync failed before restart: ${error instanceof Error ? error.message : String(error)}`);\n throw new Error('Workspace sync failed; the session is still running.', { cause: error });\n }\n }\n await hub.closeSession(session.id);\n try {\n await openSession(\n {\n cwd: session.cwd,\n name: session.name,\n ...(session.parentSessionId === undefined ? {} : { parentSessionId: session.parentSessionId }),\n ...(session.sessionProvenance === undefined ? {} : { sessionProvenance: session.sessionProvenance }),\n },\n session.id,\n ownership?.artifact,\n ownership?.workspaceId ?? session.workspaceId,\n );\n } catch (error) {\n // The journal lease allows one writer, so the new host cannot open before the old\n // one closes. Keep the closed session as dormant so it can be revived after a fix.\n if (record !== undefined) openSessions.add(record);\n throw error;\n }\n },\n resumeSession: async (session, targetSessionId) => {\n const workspaceId = session.workspaceId;\n if (!workspaceId || !hub.workspaces().some((workspace) => workspace.id === workspaceId))\n throw new Error('Session workspace not found.');\n const target = (await savedHistory(workspaceId)).find((item) => item.summary.id === targetSessionId);\n if (!target) throw new Error('Saved Pi thread not found in this workspace.');\n const artifact = validatedExecution(target.execution, workspaceId);\n const closedRecord = openSessions.list().find((entry) => entry.sessionId === session.id);\n await hub.closeSession(session.id);\n try {\n await openSession(\n {\n cwd: target.execution.cwd,\n name: target.summary.name ?? 'untitled',\n ...(target.execution.parentSessionId ? { parentSessionId: target.execution.parentSessionId } : {}),\n ...(target.execution.sessionProvenance ? { sessionProvenance: target.execution.sessionProvenance } : {}),\n },\n target.summary.id,\n artifact,\n workspaceId,\n );\n } catch (error) {\n // Same as restart: the session given up for the resume stays revivable.\n if (closedRecord !== undefined) openSessions.add(closedRecord);\n throw error;\n }\n return target.summary.id;\n },\n dormantSessions: () => openSessions.list(),\n removeDormantSession: (record: OpenSessionRecord) => openSessions.remove(record.sessionId),\n reviveSession: async (record: OpenSessionRecord) => {\n // A failed wake may be transient, for example while another server still\n // owns the journal. Keep the record so the user can retry after resolving\n // the conflict instead of losing the session from the cockpit.\n const groupingRoot = hub\n .workspaces()\n .find((workspace) => workspace.id === record.workspaceId && workspace.available !== false)?.root;\n if (!groupingRoot || (record.groupingRoot !== undefined && groupingRoot !== record.groupingRoot))\n throw new Error('The session workspace is unavailable.');\n if (record.repoRoot !== undefined && fs.realpathSync(findRepositoryRoot(record.cwd)) !== record.repoRoot)\n throw new Error('The session checkout has changed.');\n if (record.artifact !== undefined && record.artifact.root !== groupingRoot)\n throw new Error('The inherited workspace generation is unavailable.');\n await openSession(\n {\n cwd: record.cwd,\n name: record.name,\n ...(record.parentSessionId === undefined ? {} : { parentSessionId: record.parentSessionId }),\n ...(record.sessionProvenance === undefined ? {} : { sessionProvenance: record.sessionProvenance }),\n },\n record.sessionId,\n record.artifact,\n record.workspaceId,\n );\n },\n requestAsset: (request) => webCompositions?.request(request) ?? Promise.resolve(undefined),\n compositions: () => ({\n global: webCompositions?.get({ scope: 'global' }),\n publicKey: webCompositions?.publicKey(),\n shell: webCompositions?.shellTrust(),\n workspaces: hub.workspaces().map((workspace) => ({\n ...workspace,\n webComposition: webCompositions?.get({ scope: 'workspace', workspaceId: workspace.id }),\n })),\n }),\n telemetry,\n onNotice: notice,\n });\n notice(`protocol on ${cockpit.url}/api/ws`);\n let resolveShutdown!: (exitCode: number) => void;\n const shutdown = new Promise<number>((resolve) => {\n resolveShutdown = resolve;\n });\n const stop = (): void => resolveShutdown(0);\n signal.addEventListener('abort', stop, { once: true });\n if (signal.aborted) stop();\n try {\n return await shutdown;\n } finally {\n signal.removeEventListener('abort', stop);\n }\n } finally {\n shuttingDown = true;\n stopResourceMonitor();\n executionBudget.close();\n stopPersistSessionNames();\n clearInterval(eventLoopMonitor);\n await bounded(telemetry.recordEvent('doompi_server.shutdown'), 'shutdown telemetry', notice);\n await bounded(\n withShutdownDeadline(() => cockpit?.close(), 'listener shutdown'),\n 'listener shutdown',\n notice,\n );\n await bounded(remoteRuntime?.close() ?? Promise.resolve(), 'remote control shutdown', notice);\n // Session hooks and MCP owners must unwind before their shared hub services.\n // Each session phase has its own deadline, so one stalled session cannot block the rest.\n try {\n await sessionManager.close();\n } catch (error) {\n notice(error instanceof Error ? error.message : String(error));\n }\n await bounded(\n withShutdownDeadline(() => hub.close(), 'hub shutdown'),\n 'hub shutdown',\n notice,\n );\n await bounded(\n withShutdownDeadline(() => requestReceipts.close(), 'receipt shutdown'),\n 'receipt shutdown',\n notice,\n );\n await bounded(\n withShutdownDeadline(() => computerUse?.close?.(), 'computer use shutdown'),\n 'computer use shutdown',\n notice,\n );\n await bounded(\n withShutdownDeadline(() => webCompositions?.close(), 'web composition shutdown'),\n 'web composition shutdown',\n notice,\n );\n const pendingCleanups = [...pendingSessions.values()].map((setup) =>\n bounded(\n withShutdownDeadline(() => setup.cleanup(), 'pending session cleanup'),\n 'pending session cleanup',\n notice,\n ),\n );\n pendingSessions.clear();\n await Promise.allSettled(pendingCleanups);\n await bounded(harnessTelemetry.flush(), 'harness telemetry flush', notice);\n await bounded(harnessTelemetry.shutdown(), 'harness telemetry shutdown', notice);\n await bounded(telemetry.flush(), 'server telemetry flush', notice);\n await bounded(telemetry.shutdown(), 'server telemetry shutdown', notice);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,eAAe,QAAQ,WAA6B,OAAe,QAAkD;CACnH,IAAI;EACF,MAAM,2BAA2B,WAAW,KAAK;CACnD,SAAS,OAAO;EACd,OAAO,GAAG,MAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;CACrF;AACF;AAEA,eAAsB,iBAAiB,SAAuB,SAAoD;CAChH,MAAM,EACJ,KAAK,SACL,aAAa,qBACb,QACA,uBACA,QACA,kBACE;CAGJ,MAAM,kBAAqC;EAAE,GAAG;EAAqB,mBAAmB;CAAS;CACjG,MAAM,kBAAkB,4BAA4B,eAAe;CACnE,MAAM,oBAAoB;EAAE,KAAK;EAAS,KAAK;EAAiB;CAAO,CAAC,CAAC,CAAC,OAAO,UAC/E,OAAO,gCAAgC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,CACjG;CACA,MAAM,YAAY,sBAAsB;EAAE,KAAK;EAAS,KAAK;EAAiB,MAAM;CAAO,CAAC;CAC5F,MAAM,gBAAgB,gBAAgB,QAAQ,GAAG,QAAQ;CACzD,MAAM,kBAAkB,KAAK,KAAK,iBAAiB,eAAe,GAAG,QAAQ;CAE7E,MAAM,kBAAkB,sBAAsB,EAAE,WAAW,KAAK,KAAK,iBAAiB,kBAAkB,EAAE,CAAC;CAC3G,MAAM,8BAAc,IAAI,IAAmB;CAC3C,MAAM,mBAA6C;EACjD,SAAS,MAAM;GACb,YAAY,IAAI,IAAI;GACpB,aAAa;IACX,YAAY,OAAO,IAAI;GACzB;EACF;EACA,UAAU,MAAM;G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AAgB,MAAM;EACtB,MAAM,QAAQ,WAAW,eAAe;EACxC,MAAM,QAAQ,iBAAiB,MAAM,GAAG,2BAA2B,MAAM;EACzE,MAAM,QAAQ,iBAAiB,SAAS,GAAG,8BAA8B,MAAM;EAC/E,MAAM,QAAQ,UAAU,MAAM,GAAG,0BAA0B,MAAM;EACjE,MAAM,QAAQ,UAAU,SAAS,GAAG,6BAA6B,MAAM;CACzE;AACF"}
1
+ {"version":3,"file":"runtime.mjs","names":[],"sources":["../../../../src/builders/server/runtime.ts"],"sourcesContent":["import crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { globalDoomConfigDirectory } from '@agimon-ai/doompi-config/config';\nimport { filterHookDisabledLayers, loadMajorModesConfig, resolveLayers } from '@agimon-ai/doompi-config/majorModes';\nimport { resolveProfile } from '@agimon-ai/doompi-config/profiles';\nimport { createHeadlessHub, type HeadlessHub } from '@agimon-ai/doompi-core/headlessHub';\nimport { serveHeadlessServer } from '@agimon-ai/doompi-core/headlessServer';\nimport type { HeadlessSessionHost, HeadlessSessionHostOptions } from '@agimon-ai/doompi-core/headlessSessionHost';\nimport { createHeadlessSessionManager } from '@agimon-ai/doompi-core/headlessSessionManager';\nimport {\n createOpenSessionRegistry,\n createRequestReceipts,\n createWorkspaceRegistry,\n identifyWorkspace,\n listSavedSessionRecords,\n listSavedSessions,\n readSqliteTranscript,\n readWorkspaceMarker,\n writeWorkspaceMarker,\n} from '@agimon-ai/doompi-core/history';\nimport type { OpenSessionRecord, SavedSessionExecution } from '@agimon-ai/doompi-core/history';\nimport type {\n DoomHubSessionApiRequest,\n DoomHubSessionCreateRequest,\n DoomHubSessionScope,\n} from '@agimon-ai/doompi-core/hubChannel';\nimport { loadMcpBundle, type LoadedMcpBundle } from '@agimon-ai/doompi-core/mcpFacet';\nimport { createServerExecutionBudget } from '@agimon-ai/doompi-core/packageApi';\nimport type { DoomHostMediaArbitration, DoomPeerAgentRegistry } from '@agimon-ai/doompi-core/packageApi';\nimport { serveSessionApis, type PackageApiServer } from '@agimon-ai/doompi-core/packageApiServer';\nimport { piAgentDirectory } from '@agimon-ai/doompi-core/piSettings';\nimport { createRemoteRuntime, type RemoteRuntime } from '@agimon-ai/doompi-core/remoteRuntime';\nimport type {\n HeadlessSessionCloseOptions,\n HeadlessSessionManager,\n} from '@agimon-ai/doompi-core/runtimeHeadlessSessionManager';\nimport { createHarnessTelemetry } from '@agimon-ai/doompi-core/runtimeLogSinkTelemetry';\nimport { loadServerBundle, resolveServerBundleSource } from '@agimon-ai/doompi-core/serverFacet';\nimport { createServerTelemetry } from '@agimon-ai/doompi-core/serverTelemetry';\nimport { resolveSyncLocation } from '@agimon-ai/doompi-core/syncLocation';\nimport {\n parseSyncRegistration,\n readSyncRegistration,\n validateSyncRegistration,\n type SyncRegistration,\n} from '@agimon-ai/doompi-core/syncRegistration';\nimport { createWebCompositions } from '@agimon-ai/doompi-core/webCompositions';\nimport { readMinorModeCatalog } from '@agimon-ai/doompi-minor-mode';\nimport WebSocket from 'ws';\n\nimport { HARNESS_STATE_KEYS, HARNESS_STATE_POINTER } from '../../composition/harnessState';\nimport { findRepositoryRoot } from '../../composition/repository';\nimport { readSyncDrift } from '../../composition/syncDrift';\nimport { readSyncState } from '../../composition/syncState';\nimport { readRegisteredBootstrapStatus } from '../cli/bootstrapLocator';\nimport { buildHarnessContext } from '../cli/harnessContext';\nimport { createComputerUseBinding } from './computerUseBinding';\nimport { createDefaultWorkspaceFolder } from './defaultWorkspace';\nimport { ensureGlobalLogSink } from './logSink';\nimport { monitorRuntimeResources } from './runtimeResources';\nimport { publishHeadlessSelectionStatus } from './selectionStatus';\nimport { type PinnedSelectionAxis, resolveSessionIdentity, sessionSelectionArgs } from './sessionArguments';\nimport { resolveSessionArtifact, resolveWorktreeRestart } from './sessionArtifact';\nimport { withShutdownDeadline } from './shutdown';\nimport type { ServeOptions, ServerRuntimeEnvironment } from './types';\nimport { checkoutWorkspaceId } from './workspaceCheckout';\n\nasync function bounded(operation: Promise<unknown>, label: string, notice: (message: string) => void): Promise<void> {\n try {\n await withShutdownDeadline(() => operation, label);\n } catch (error) {\n notice(`${label} failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\nexport async function runServerRuntime(options: ServeOptions, runtime: ServerRuntimeEnvironment): Promise<number> {\n const {\n cwd: baseCwd,\n environment: incomingEnvironment,\n notice,\n resolveHarnessOptions,\n signal,\n syncWorkspace,\n } = runtime;\n // Keep this selection local to this server and its admitted sessions. The\n // process environment may also serve unrelated hosts and must not be changed.\n const baseEnvironment: NodeJS.ProcessEnv = { ...incomingEnvironment, LOG_SINK_INSTANCE: 'global' };\n const executionBudget = createServerExecutionBudget(baseEnvironment);\n await ensureGlobalLogSink({ cwd: baseCwd, env: baseEnvironment, notice }).catch((error: unknown) =>\n notice(`Global log sink unavailable: ${error instanceof Error ? error.message : String(error)}`),\n );\n const telemetry = createServerTelemetry({ cwd: baseCwd, env: baseEnvironment, warn: notice });\n const homeDirectory = baseEnvironment.HOME ?? os.homedir();\n const serverDirectory = path.join(piAgentDirectory(baseEnvironment), 'server');\n // This native history has no agent lane and is deliberately outside the session-history catalog.\n const requestReceipts = createRequestReceipts({ directory: path.join(serverDirectory, 'request-receipts') });\n const activeMedia = new Set<() => boolean>();\n const mediaArbitration: DoomHostMediaArbitration = {\n register(busy) {\n activeMedia.add(busy);\n return () => {\n activeMedia.delete(busy);\n };\n },\n available(busy) {\n return activeMedia.has(busy) && [...activeMedia].every((other) => other === busy || !other());\n },\n };\n const activePeerAgents = new Map<string, { fetch(request: Request): Promise<Response>; hubToken: string }>();\n const peerAgents: DoomPeerAgentRegistry = {\n register(sessionId, agent, hubToken) {\n if (activePeerAgents.has(sessionId)) throw new Error(`Voice peer agent '${sessionId}' is already registered.`);\n const entry = { fetch: (request: Request) => agent.fetch(request), hubToken };\n activePeerAgents.set(sessionId, entry);\n return () => {\n if (activePeerAgents.get(sessionId) === entry) activePeerAgents.delete(sessionId);\n };\n },\n get: (sessionId) => activePeerAgents.get(sessionId),\n };\n const workspaces = createWorkspaceRegistry({ directory: serverDirectory, onNotice: notice });\n // Beside the journals it names, because a record pointing at a sessions\n // directory it is not stored next to is a record that can outlive its target.\n const openSessions = createOpenSessionRegistry({\n directory: serverDirectory,\n homeDirectory,\n onNotice: notice,\n });\n let lastBudgetSnapshot = '';\n let nextEventLoopTick = performance.now() + 1_000;\n const eventLoopMonitor = setInterval(() => {\n const now = performance.now();\n const budget = executionBudget.getSnapshot();\n const snapshot = JSON.stringify(budget);\n if (snapshot !== lastBudgetSnapshot) {\n lastBudgetSnapshot = snapshot;\n void telemetry\n .recordEvent('doompi_server.execution_budget', {\n host_pid: process.pid,\n running_jobs: budget.running,\n queued_jobs: budget.queued,\n limit: budget.limit,\n })\n .catch((error: unknown) => notice(`execution budget telemetry failed: ${String(error)}`));\n }\n const delay = Math.max(0, now - nextEventLoopTick);\n nextEventLoopTick = now + 1_000;\n if (delay >= 100)\n void telemetry\n .recordEvent('doompi_server.event_loop_delay', { duration_ms: Math.round(delay) })\n .catch((error: unknown) => notice(`event loop telemetry failed: ${String(error)}`));\n }, 1_000);\n eventLoopMonitor.unref();\n const harnessTelemetry = createHarnessTelemetry({\n cwd: baseCwd,\n env: baseEnvironment,\n warn: notice,\n deferSpans: true,\n });\n const baseSessionManager = createHeadlessSessionManager({\n publishSelectionStatus: publishHeadlessSelectionStatus,\n contextGroups: (context) =>\n (readMinorModeCatalog(context)?.list() ?? [])\n .filter(({ state }) => state.activation === 'active')\n .map(({ descriptor }) => ({ id: descriptor.id, label: descriptor.label, kind: 'minor' })),\n });\n type SessionSetup = {\n cleanup: () => Promise<void>;\n bundle: Awaited<ReturnType<typeof loadServerBundle>>;\n mcpBundle: LoadedMcpBundle;\n registration: SyncRegistration;\n };\n type SessionArtifacts = SessionSetup & { apis: PackageApiServer };\n const pendingSessions = new Map<string, SessionSetup>();\n const sessionArtifacts = new Map<string, SessionArtifacts>();\n let mountSessionApis:\n | ((options: HeadlessSessionHostOptions, host: HeadlessSessionHost) => Promise<PackageApiServer>)\n | undefined;\n /**\n * Shutdown runs every session through the same close path a user-initiated\n * close uses, so without this the registry would be emptied by the very event\n * it exists to survive.\n */\n let shuttingDown = false;\n\n const closeManagedSession = async (sessionId: string, options?: HeadlessSessionCloseOptions): Promise<void> => {\n // A released session keeps its record, which is what lists it as dormant.\n if (!shuttingDown && options?.keepDormant !== true) openSessions.remove(sessionId);\n const artifacts = sessionArtifacts.get(sessionId);\n sessionArtifacts.delete(sessionId);\n webCompositions?.remove({ scope: 'session', sessionId });\n const failures: unknown[] = [];\n // The host goes first, as on the create-failure path: it stops the running turn and\n // dispatches session_shutdown while the facets that own those hooks are still installed.\n try {\n await withShutdownDeadline(\n () => baseSessionManager.closeSession(sessionId),\n `Session '${sessionId}' runtime shutdown`,\n );\n } catch (error) {\n failures.push(error);\n }\n try {\n await withShutdownDeadline(() => artifacts?.apis.close(), `Session '${sessionId}' API shutdown`);\n } catch (error) {\n failures.push(error);\n }\n try {\n await withShutdownDeadline(() => artifacts?.cleanup(), `Session '${sessionId}' artifact cleanup`);\n } catch (error) {\n failures.push(error);\n }\n if (failures.length > 0) throw new AggregateError(failures, `Session '${sessionId}' shutdown failed`);\n };\n\n const sessionManager: HeadlessSessionManager = {\n async create(sessionOptions) {\n const setup = pendingSessions.get(sessionOptions.sessionId);\n let host: HeadlessSessionHost;\n try {\n host = await baseSessionManager.create(sessionOptions);\n } catch (error) {\n if (setup !== undefined && pendingSessions.delete(sessionOptions.sessionId))\n await setup.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n throw error;\n }\n if (setup === undefined || mountSessionApis === undefined) return host;\n try {\n const apis = await mountSessionApis(sessionOptions, host);\n pendingSessions.delete(sessionOptions.sessionId);\n sessionArtifacts.set(sessionOptions.sessionId, { ...setup, apis });\n return host;\n } catch (error) {\n pendingSessions.delete(sessionOptions.sessionId);\n await baseSessionManager\n .closeSession(sessionOptions.sessionId)\n .catch((closeError: unknown) => notice(String(closeError)));\n await setup.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n throw error;\n }\n },\n get: (sessionId) => baseSessionManager.get(sessionId),\n sessions: () => baseSessionManager.sessions(),\n closeSession: closeManagedSession,\n async close() {\n const ids = baseSessionManager.sessions().map((session) => session.runtime.sessionId);\n const outcomes = await Promise.allSettled(ids.map((id) => closeManagedSession(id)));\n const failures = outcomes\n .filter((outcome): outcome is PromiseRejectedResult => outcome.status === 'rejected')\n .map((outcome) => outcome.reason);\n if (failures.length > 0) throw new AggregateError(failures, 'Headless session shutdown failed');\n },\n };\n\n let requestSessionApi: (\n scope: DoomHubSessionScope,\n request: DoomHubSessionApiRequest,\n ) => Promise<Response> = async () => Response.json({ error: 'Session API unavailable.' }, { status: 404 });\n let openSession: (\n request: DoomHubSessionCreateRequest,\n sessionId?: string,\n pinnedArtifact?: SyncRegistration,\n groupingWorkspaceId?: string,\n ) => Promise<DoomHubSessionScope> = async () => {\n throw new Error('The cockpit session service is not ready.');\n };\n let admitWorkspace: (\n root: string,\n name?: string,\n ) => Promise<{ id: string; root: string; name?: string; available: boolean }> = async () => {\n throw new Error('Workspace admission is not ready.');\n };\n const computerUse = await createComputerUseBinding();\n let hub!: HeadlessHub;\n hub = createHeadlessHub({\n manager: sessionManager,\n // Throws for an unknown profile; the hub reports that and shows the session without an avatar.\n resolveProfileIdentity: (root, profile) => {\n const identity = resolveProfile(root, profile, homeDirectory).identity;\n return identity === undefined ? undefined : { displayName: identity.name, icon: identity.icon };\n },\n admitWorkspace: async ({ root, name }) =>\n admitWorkspace(\n root === undefined || root.trim() === '' ? await createDefaultWorkspaceFolder(name ?? '', homeDirectory) : root,\n name,\n ),\n onWorkspaceRemoved: (workspaceId) => {\n workspaces.remove(workspaceId);\n webCompositions?.remove({ scope: 'workspace', workspaceId });\n },\n createSession: async (request, placement) => {\n if (placement === undefined) return openSession(request);\n // A workspace package's top-level session must run in a checkout of that same workspace.\n if (checkoutWorkspaceId(workspaces.list(), request.cwd) !== placement.workspaceId)\n throw new Error('The session directory is outside this workspace.');\n return openSession(request, undefined, undefined, placement.workspaceId);\n },\n sessionReservations: {\n read(id, parentSessionId) {\n if (!cockpit) throw new Error('Session setup is not ready.');\n return cockpit.sessionReservations.read(id, parentSessionId);\n },\n async prepare(id, parentSessionId, cwd) {\n if (!cockpit) throw new Error('Session setup is not ready.');\n return cockpit.sessionReservations.prepare(id, parentSessionId, cwd);\n },\n async complete(id, parentSessionId) {\n if (!cockpit) throw new Error('Session setup is not ready.');\n return cockpit.sessionReservations.complete(id, parentSessionId);\n },\n },\n onNotice: notice,\n hubToken: () => attachToken,\n requestSessionApi: (scope, request) => requestSessionApi(scope, request),\n ...(computerUse === undefined ? {} : { computerUse }),\n });\n const stopPersistSessionNames = hub.onEvent((event) => {\n if (event.kind !== 'upsert') return;\n const record = openSessions.list().find((entry) => entry.sessionId === event.session.id);\n if (record === undefined || record.name === event.session.name) return;\n openSessions.add({ ...record, name: event.session.name });\n });\n let harnessContext: Awaited<ReturnType<typeof buildHarnessContext>> | undefined;\n let cockpit: Awaited<ReturnType<typeof serveHeadlessServer>> | undefined;\n let remoteRuntime: RemoteRuntime | undefined;\n let attachToken: string | undefined;\n let webCompositions: ReturnType<typeof createWebCompositions> | undefined;\n const stopResourceMonitor = monitorRuntimeResources({\n record: (attributes) => telemetry.recordEvent('doompi_server.resources', attributes),\n counts: () => {\n const budget = executionBudget.getSnapshot();\n return {\n sessions: sessionManager.sessions().length,\n running_jobs: budget.running,\n queued_jobs: budget.queued,\n job_limit: budget.limit,\n };\n },\n warn: notice,\n });\n\n try {\n await telemetry.runInSpan('doompi_server.startup', {}, async () => {\n const token = fs.readFileSync(options.tokenFile, 'utf8').trim();\n if (!token) throw new Error('The attach token file is empty.');\n attachToken = token;\n\n const resolved = resolveSessionIdentity(options.agentArgs, {\n sessionId: options.sessionId ?? crypto.randomUUID(),\n sessionName: options.sessionName,\n });\n\n const globalRoot = globalDoomConfigDirectory(homeDirectory);\n webCompositions = createWebCompositions(path.join(globalRoot, 'server'), notice);\n const loadComposition = async (\n root: string,\n scope: 'global' | 'workspace' | 'session',\n selection?: { root: string; majorMode: string; activeLayers: string[] },\n pinnedRegistration?: SyncRegistration,\n ) => {\n const registration = pinnedRegistration ?? readSyncRegistration(root, homeDirectory);\n const source = resolveServerBundleSource({ registration });\n if (source.kind !== 'descriptor')\n throw new Error(`Run the scoped DoomPi sync for '${root}' before opening it.`);\n const selected =\n selection ??\n (() => {\n const config = loadMajorModesConfig(root, homeDirectory);\n const majorMode = config.defaultMajorMode;\n return { root, majorMode, activeLayers: resolveLayers(config, majorMode) };\n })();\n return telemetry.runInSpan('doompi_server.composition_load', { scope }, () =>\n loadServerBundle(scope, {\n ...source,\n ...selected,\n retainCandidates: scope === 'session',\n onNotice: notice,\n }),\n );\n };\n const loadSessionMcp = async (\n root: string,\n selection: { majorMode: string; activeLayers: readonly string[] },\n pinnedRegistration?: SyncRegistration,\n ): Promise<LoadedMcpBundle> => {\n const registration = pinnedRegistration ?? readSyncRegistration(root, homeDirectory);\n if (registration?.mcpBundle === undefined)\n throw new Error(`Run the scoped DoomPi sync for '${root}' before opening its MCP runtime.`);\n const bundle = registration.mcpBundle;\n return telemetry.runInSpan('doompi_server.mcp_bundle_load', {}, () =>\n loadMcpBundle({\n directory: path.dirname(bundle.path),\n generation: registration.generation,\n fingerprint: bundle.fingerprint,\n descriptorSha256: bundle.sha256,\n majorMode: selection.majorMode,\n activeLayers: selection.activeLayers,\n retainCandidates: true,\n onNotice: notice,\n }),\n );\n };\n const sharedApiContext = {\n homeDirectory,\n environment: baseEnvironment,\n hubToken: token,\n sessionService: hub.sessionService,\n mediaArbitration,\n executionBudget,\n peerAgents,\n directEvents: hub.directEvents,\n requestApi: (mount: Parameters<HeadlessHub['requestApi']>[0], basePath: string, request: Request) =>\n hub.requestApi(mount, basePath, request),\n repositories: () =>\n hub.workspaces().map((workspace) => ({\n id: workspace.id,\n path: workspace.root,\n name: workspace.root.split('/').at(-1) ?? workspace.id,\n active: hub.snapshot().some((session) => session.workspaceId === workspace.id),\n })),\n resolveRepository: (id: string) => hub.workspaces().find((workspace) => workspace.id === id)?.root,\n readRepositorySync: (id: string) => {\n const root = hub.workspaces().find((workspace) => workspace.id === id)?.root;\n if (!root) return undefined;\n const drift = readSyncDrift({ repoRoot: root, homeDirectory, requireWebBundle: true });\n const state = readSyncState(root, homeDirectory);\n return { ...drift, mcpProjection: state?.fileState.mcpProjection };\n },\n onNotice: notice,\n };\n const globalBundle = await loadComposition(globalRoot, 'global');\n webCompositions.publishShell(readSyncRegistration(globalRoot, homeDirectory)!);\n remoteRuntime = createRemoteRuntime({\n homeDirectory,\n registrationToken: token,\n reservedPorts: () => [options.webPort],\n bundleTrust: () => webCompositions?.shellTrust(),\n onNotice: notice,\n forward: async (request) => {\n if (!cockpit || !attachToken)\n return Response.json({ error: 'The headless server is not ready.' }, { status: 503 });\n const from = new URL(request.url);\n const headers = new Headers(request.headers);\n headers.set('x-doompi-token', attachToken);\n return fetch(\n new URL(`${from.pathname}${from.search}`, cockpit.url),\n new Request(request, { headers, redirect: 'manual' }),\n );\n },\n connectProtocol: (pathname) => {\n if (!cockpit || !attachToken) throw new Error('The headless protocol listener is not ready.');\n const url = new URL(pathname, cockpit.url);\n url.protocol = 'ws:';\n return new WebSocket(url, { headers: { 'x-doompi-token': attachToken } });\n },\n });\n await hub.mountFacets(globalBundle.facets, {\n ...sharedApiContext,\n scope: 'global',\n requestReceipts: requestReceipts.receipts,\n remoteControl: { fetch: (request: Request) => remoteRuntime!.fetchLocal(request) },\n });\n webCompositions.publish(\n { scope: 'global' },\n readSyncRegistration(globalRoot, homeDirectory)!,\n hub.channelTypes(),\n );\n const admissions = new Map<string, Promise<{ id: string; root: string; name?: string; available: boolean }>>();\n // A member checkout is any checkout other than its workspace root, such as a worktree.\n const isMemberCheckout = (from: string, workspace: { root: string }): boolean =>\n fs.realpathSync(findRepositoryRoot(from)) !== workspace.root;\n admitWorkspace = async (from, requestedName) => {\n const checkoutRoot = fs.realpathSync(findRepositoryRoot(from));\n // Ids are persisted, never re-derived from the path: a checkout of an admitted repository\n // joins its workspace, and a repository that moved keeps its id and sessions.\n const { id, root, moved } = identifyWorkspace({\n records: workspaces.list(),\n checkoutRoot,\n marker: readWorkspaceMarker(checkoutRoot),\n });\n const record = workspaces.list().find((workspace) => workspace.id === id);\n // A name given now replaces the stored one; readmitting without a name keeps it.\n const name = requestedName?.trim() || record?.name;\n const named = name === undefined ? {} : { name };\n const renamed = record !== undefined && name !== record.name;\n const existing = hub.workspaces().find((workspace) => workspace.id === id);\n if (existing !== undefined && existing.available !== false && existing.root === root) {\n if (renamed) {\n workspaces.add({ id, root, ...named });\n hub.registerWorkspace({ ...existing, ...named, available: true });\n }\n return { ...existing, ...named, available: true };\n }\n const pending = admissions.get(id);\n if (pending) return pending;\n const wasRemembered = record !== undefined;\n if (!wasRemembered || moved || renamed) workspaces.add({ id, root, ...named });\n if (moved) notice(`Workspace '${id}' moved to '${root}'.`);\n hub.registerWorkspace({ id, root, ...named, available: false });\n const admission = (async () => {\n const syncEnvironment: NodeJS.ProcessEnv = { ...baseEnvironment, DOOMPI_ROOT: root };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete syncEnvironment[key];\n await syncWorkspace(root, syncEnvironment);\n const bundle = await loadComposition(root, 'workspace');\n await hub.mountFacets(bundle.facets, {\n ...sharedApiContext,\n scope: 'workspace',\n workspaceId: id,\n workspaceRoot: root,\n cwd: root,\n resolveRepository: (requestedId) => (requestedId === id ? root : undefined),\n });\n webCompositions?.publish(\n { scope: 'workspace', workspaceId: id },\n readSyncRegistration(root, homeDirectory)!,\n hub.channelTypes(),\n );\n try {\n if (readWorkspaceMarker(root) === undefined) writeWorkspaceMarker(root, id);\n } catch (error) {\n notice(\n `Workspace '${root}' id could not be recorded in its git data: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return { id, root, ...named, available: true };\n })();\n admissions.set(id, admission);\n try {\n return await admission;\n } catch (error) {\n if (!wasRemembered) {\n await hub.removeWorkspace(id);\n workspaces.remove(id);\n }\n throw error;\n } finally {\n admissions.delete(id);\n }\n };\n for (const record of openSessions.list()) {\n if (workspaces.list().some((workspace) => workspace.id === record.workspaceId)) continue;\n try {\n const candidate = record.groupingRoot ?? record.artifact?.root ?? record.cwd;\n const root = fs.realpathSync(findRepositoryRoot(candidate));\n // The recorded id is kept as is. It may be a legacy path hash, and journals, open-session\n // records and MCP audiences all refer to it.\n if (\n (record.groupingRoot === undefined || root === candidate) &&\n !workspaces.list().some((workspace) => workspace.root === root)\n )\n workspaces.add({ id: record.workspaceId, root });\n else\n notice(\n `Session '${record.sessionId}' no longer resolves to its recorded workspace; skipping registration.`,\n );\n } catch (error) {\n notice(\n `Session '${record.sessionId}' workspace could not be registered: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n for (const workspace of workspaces.list()) {\n hub.registerWorkspace({ ...workspace, available: false });\n try {\n const root = fs.realpathSync(findRepositoryRoot(workspace.root));\n if (root !== workspace.root) {\n notice(\n `Workspace '${workspace.root}' no longer resolves to its recorded identity; leaving it unavailable.`,\n );\n continue;\n }\n await admitWorkspace(workspace.root);\n } catch (error) {\n notice(\n `Workspace '${workspace.root}' could not be restored: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n\n const sessionHostOptions = (\n context: Awaited<ReturnType<typeof buildHarnessContext>>,\n bundle: Awaited<ReturnType<typeof loadServerBundle>>,\n mcpBundle: LoadedMcpBundle,\n registration: SyncRegistration,\n identity: {\n sessionId: string;\n sessionName: string;\n parentSessionId?: string;\n sessionProvenance?: string;\n },\n workspace: { id: string; root: string },\n explicit: {\n pinned: readonly PinnedSelectionAxis[];\n minorModes?: readonly string[];\n allowedTools?: readonly string[];\n } = { pinned: [] },\n ): HeadlessSessionHostOptions => {\n const policyOptions = context.options;\n const sessionSelection = {\n root: policyOptions.repoRoot,\n majorMode: policyOptions.majorMode,\n activeLayers: context.selectedLayers,\n domains: policyOptions.domains,\n profile: context.profile,\n state: { 'minor-mode': [...(explicit.minorModes ?? [])] },\n };\n const piBootstrap = readRegisteredBootstrapStatus(registration, undefined, homeDirectory);\n if (!piBootstrap.fresh || piBootstrap.bootstrap === undefined) {\n throw new Error(`The admitted DoomPi bootstrap for generation '${registration.generation}' is unavailable.`);\n }\n return {\n cwd: policyOptions.cwd,\n repoRoot: policyOptions.repoRoot,\n sessionId: identity.sessionId,\n workspaceId: workspace.id,\n groupingRoot: workspace.root,\n // A member checkout runs its workspace's compiled composition, not one of its own.\n ...(isMemberCheckout(policyOptions.repoRoot, workspace) ? { inheritedArtifact: registration } : {}),\n sessionName: identity.sessionName,\n webComposition: webCompositions?.publish(\n { scope: 'session', sessionId: identity.sessionId },\n registration,\n hub.channelTypes(),\n ),\n ...(identity.parentSessionId === undefined ? {} : { parentSessionId: identity.parentSessionId }),\n ...(identity.sessionProvenance === undefined ? {} : { sessionProvenance: identity.sessionProvenance }),\n agentArgs: policyOptions.piArgs,\n environment: Object.freeze({ ...context.environment }),\n piExtensionPaths: [piBootstrap.bootstrap],\n selection: sessionSelection,\n ...(explicit.allowedTools === undefined ? {} : { allowedTools: explicit.allowedTools }),\n selectionOverrides: (['majorMode', 'domains', 'profile'] as const).filter((axis) => {\n if (explicit.pinned.includes(axis)) return true;\n const flag = axis === 'majorMode' ? '--major-mode' : `--${axis}`;\n return (\n identity.sessionId === resolved.identity.sessionId &&\n resolved.agentArgs.some((arg) => arg === flag || arg.startsWith(`${flag}=`))\n );\n }),\n inheritedSelection: () => {\n const environment = { ...baseEnvironment };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete environment[key];\n const defaults = resolveHarnessOptions({\n args: ['--cwd', policyOptions.cwd],\n cwd: policyOptions.cwd,\n environment,\n ...(policyOptions.configRoot === undefined ? {} : { configRoot: policyOptions.configRoot }),\n });\n return { majorMode: defaults.majorMode, domains: defaults.domains, profile: defaults.profile };\n },\n candidates: bundle.descriptor.entries,\n mcpPlugins: mcpBundle.plugins,\n resolveSelection: (requested) => {\n const config = loadMajorModesConfig(\n policyOptions.configRoot ?? policyOptions.repoRoot,\n policyOptions.homeDirectory,\n );\n return {\n ...requested,\n activeLayers: filterHookDisabledLayers(\n config,\n resolveLayers(config, requested.majorMode),\n policyOptions.hooks,\n ),\n };\n },\n onNotice: notice,\n };\n };\n\n mountSessionApis = (sessionOptions, host) =>\n serveSessionApis({\n sessionId: sessionOptions.sessionId,\n cwd: sessionOptions.cwd,\n environment: sessionOptions.environment,\n directEvents: hub.directEvents,\n requestApi: (mount, basePath, request) => hub.requestApi(mount, basePath, request),\n publishActivity: (activity) => hub.setSessionActivity?.(sessionOptions.sessionId, activity),\n ...(computerUse === undefined\n ? {}\n : {\n computerUse: {\n get available() {\n return computerUse.available;\n },\n get enabled() {\n return computerUse.enabled === true;\n },\n authorize: (headers: Headers) => computerUse.authorize?.(headers) === true,\n claim: () => computerUse.claimSession?.(sessionOptions.sessionId),\n subscribe: (listener: () => void) => computerUse.subscribe?.(listener) ?? (() => undefined),\n },\n }),\n hubToken: token,\n sessionService: hub.sessionService,\n mediaArbitration,\n executionBudget,\n peerAgents,\n pluginRegistry: hub.pluginRegistry,\n apis: [],\n facets: pendingSessions.get(sessionOptions.sessionId)?.bundle.facets ?? [],\n workspaceId: sessionOptions.workspaceId,\n // The checkout, which MCP authorizes against; sessionContext carries both roots.\n workspaceRoot: sessionOptions.repoRoot,\n ...(host.sessionContext === undefined ? {} : { sessionContext: host.sessionContext }),\n homeDirectory,\n mountChannel: (channel) => {\n const dispose = hub.registerChannel(channel, { scope: 'session', sessionId: sessionOptions.sessionId });\n return { mounted: true, dispose };\n },\n prepareFacets: host.prepareFacets,\n activateFacets: host.activateFacets,\n canDispatch: host.canDispatch,\n telemetry,\n onNotice: notice,\n });\n\n requestSessionApi = async (scope, request) => {\n const session = hub.session(scope.sessionId);\n const artifacts = sessionArtifacts.get(scope.sessionId);\n if (session === undefined || session.cwd !== scope.cwd || artifacts === undefined)\n return Response.json({ error: 'Session not found.' }, { status: 404 });\n if (!/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u.test(request.basePath))\n return Response.json({ error: 'Invalid session API base path.' }, { status: 400 });\n if (!request.path.startsWith('/') || request.path.startsWith('//') || request.path.includes('#'))\n return Response.json({ error: 'Invalid session API path.' }, { status: 400 });\n const body = request.body === null || request.body === undefined ? undefined : request.body;\n return artifacts.apis.request(\n new Request(`http://doompi.local/api/plugins/${request.basePath}${request.path}`, {\n method: request.method,\n headers: request.headers,\n ...(body === undefined ? {} : { body }),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n }),\n );\n };\n\n if (!options.noSession) {\n harnessContext = await buildHarnessContext(\n resolveHarnessOptions({ args: resolved.agentArgs, cwd: baseCwd, environment: baseEnvironment }),\n harnessTelemetry,\n );\n const activeHarnessContext = harnessContext;\n try {\n const initialWorkspace = await admitWorkspace(harnessContext.options.repoRoot);\n const initialRegistration = readSyncRegistration(initialWorkspace.root, homeDirectory);\n if (initialRegistration === undefined)\n throw new Error(`Run the scoped DoomPi sync for '${initialWorkspace.root}' before opening it.`);\n const initialBundle = await loadComposition(\n harnessContext.options.repoRoot,\n 'session',\n {\n root: harnessContext.options.repoRoot,\n majorMode: harnessContext.options.majorMode,\n activeLayers: harnessContext.selectedLayers,\n },\n initialRegistration,\n );\n const initialMcpBundle = await loadSessionMcp(\n harnessContext.options.repoRoot,\n {\n majorMode: harnessContext.options.majorMode,\n activeLayers: harnessContext.selectedLayers,\n },\n initialRegistration,\n );\n pendingSessions.set(resolved.identity.sessionId, {\n cleanup: () => activeHarnessContext.cleanup(),\n bundle: initialBundle,\n mcpBundle: initialMcpBundle,\n registration: initialRegistration,\n });\n await hub.create(\n sessionHostOptions(\n harnessContext,\n initialBundle,\n initialMcpBundle,\n initialRegistration,\n resolved.identity,\n initialWorkspace,\n ),\n );\n } catch (error) {\n pendingSessions.delete(resolved.identity.sessionId);\n await activeHarnessContext.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n throw error;\n }\n await bounded(harnessTelemetry.flush(), 'initial composition telemetry flush', notice);\n }\n\n const reservedOpens = new Map<string, Promise<DoomHubSessionScope>>();\n openSession = async (request, sessionId, pinnedArtifact, groupingWorkspaceId) => {\n request.signal?.throwIfAborted();\n if (request.reservationId !== undefined) {\n if (!request.parentSessionId || !cockpit) throw new Error('A reserved session requires its owning parent.');\n const prepared = await cockpit.sessionReservations.prepare(\n request.reservationId,\n request.parentSessionId,\n request.cwd,\n );\n if (sessionId !== undefined && sessionId !== prepared.sessionId)\n throw new Error('Reserved session identity cannot change.');\n sessionId = prepared.sessionId;\n const existing = hub.session(sessionId);\n if (existing) {\n if (existing.cwd !== prepared.cwd || existing.parentSessionId !== request.parentSessionId)\n throw new Error('Reserved session target does not match.');\n return { sessionId, cwd: existing.cwd, workspaceId: existing.workspaceId };\n }\n if (openSessions.list().some((record) => record.sessionId === sessionId))\n throw new Error('Resume the recorded session instead of recreating it.');\n const pending = reservedOpens.get(sessionId);\n if (pending) return pending;\n request = { ...request, cwd: prepared.cwd };\n }\n const identity = {\n sessionId: sessionId ?? crypto.randomUUID(),\n sessionName: request.name,\n parentSessionId: request.parentSessionId,\n sessionProvenance: request.sessionProvenance,\n };\n // Membership follows the parent link, whatever the session is called or wherever its\n // checkout lives. Without a known parent, the checkout's own identity decides.\n const inheritedWorkspaceId =\n groupingWorkspaceId ??\n (request.parentSessionId\n ? (hub.session(request.parentSessionId)?.workspaceId ??\n openSessions.list().find((record) => record.sessionId === request.parentSessionId)?.workspaceId)\n : undefined);\n const parentArtifact =\n request.parentSessionId === undefined\n ? undefined\n : (sessionArtifacts.get(request.parentSessionId)?.registration ??\n pendingSessions.get(request.parentSessionId)?.registration ??\n openSessions.list().find((record) => record.sessionId === request.parentSessionId)?.artifact);\n const explicit = sessionSelectionArgs(request);\n const start = (async (): Promise<DoomHubSessionScope> => {\n const childIdentity = resolveSessionIdentity([], identity);\n const childEnvironment = { ...baseEnvironment, ...request.environment };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete childEnvironment[key];\n // The workspace is settled first: a member checkout reads its workspace's configuration.\n const workspace =\n inheritedWorkspaceId === undefined\n ? await admitWorkspace(request.cwd)\n : hub\n .workspaces()\n .find((candidate) => candidate.id === inheritedWorkspaceId && candidate.available !== false);\n if (workspace === undefined) throw new Error('The session workspace is unavailable.');\n const member = isMemberCheckout(request.cwd, workspace);\n const childContext = await buildHarnessContext(\n resolveHarnessOptions({\n args: ['--cwd', request.cwd, ...childIdentity.agentArgs, ...explicit.args],\n cwd: request.cwd,\n environment: childEnvironment,\n ...(member ? { configRoot: workspace.root } : {}),\n }),\n harnessTelemetry,\n );\n try {\n const registration = await resolveSessionArtifact({\n member,\n pinned: pinnedArtifact,\n parent: parentArtifact,\n workspace: () => readSyncRegistration(workspace.root, homeDirectory),\n prepareCurrent: async () => {\n const current = readSyncRegistration(workspace.root, homeDirectory);\n if (current === undefined)\n throw new Error(`Run the scoped DoomPi sync for '${workspace.root}' before opening it.`);\n return current;\n },\n });\n const bundle = await loadComposition(\n childContext.options.repoRoot,\n 'session',\n {\n root: childContext.options.repoRoot,\n majorMode: childContext.options.majorMode,\n activeLayers: childContext.selectedLayers,\n },\n registration,\n );\n const mcpBundle = await loadSessionMcp(\n childContext.options.repoRoot,\n {\n majorMode: childContext.options.majorMode,\n activeLayers: childContext.selectedLayers,\n },\n registration,\n );\n request.signal?.throwIfAborted();\n pendingSessions.set(identity.sessionId, {\n cleanup: () => childContext.cleanup(),\n bundle,\n mcpBundle,\n registration,\n });\n const created = await hub.create(\n sessionHostOptions(childContext, bundle, mcpBundle, registration, identity, workspace, {\n pinned: explicit.pinned,\n ...(request.selection?.minorModes === undefined ? {} : { minorModes: request.selection.minorModes }),\n ...(request.tools === undefined ? {} : { allowedTools: request.tools }),\n }),\n );\n request.signal?.throwIfAborted();\n if (created.workspaceId !== undefined) {\n const saved = openSessions.add({\n sessionId: created.id,\n workspaceId: created.workspaceId,\n cwd: created.cwd,\n repoRoot: childContext.options.repoRoot,\n groupingRoot: workspace.root,\n name: created.name,\n createdAt: created.createdAt,\n ...(created.parentSessionId === undefined ? {} : { parentSessionId: created.parentSessionId }),\n ...(created.sessionProvenance === undefined ? {} : { sessionProvenance: created.sessionProvenance }),\n ...(member ? { artifact: registration } : {}),\n });\n if (saved === false) throw new Error('The new session could not be durably recorded.');\n }\n return { sessionId: identity.sessionId, cwd: childContext.options.cwd, workspaceId: created.workspaceId };\n } catch (error) {\n if (hub.session(identity.sessionId)) await hub.closeSession(identity.sessionId);\n else {\n pendingSessions.delete(identity.sessionId);\n await childContext.cleanup().catch((cleanupError: unknown) => notice(String(cleanupError)));\n }\n throw error;\n }\n })();\n if (request.reservationId !== undefined) reservedOpens.set(identity.sessionId, start);\n try {\n return await start;\n } finally {\n if (reservedOpens.get(identity.sessionId) === start) reservedOpens.delete(identity.sessionId);\n }\n };\n });\n\n const workspaceResumes = new Map<string, Promise<string>>();\n const savedHistory = async (workspaceId: string) => {\n const root = hub\n .workspaces()\n .find((workspace) => workspace.id === workspaceId && workspace.available !== false)?.root;\n if (!root) throw new Error('Workspace not found.');\n return listSavedSessionRecords(\n path.join(serverDirectory, 'sessions'),\n root,\n new Set(hub.snapshot().map((active) => active.id)),\n workspaceId,\n );\n };\n const validatedExecution = (target: SavedSessionExecution, workspaceId: string): SyncRegistration | undefined => {\n const root = hub\n .workspaces()\n .find((workspace) => workspace.id === workspaceId && workspace.available !== false)?.root;\n if (!root || target.groupingRoot !== root || (target.workspaceId && target.workspaceId !== workspaceId))\n throw new Error('Saved session does not belong to this workspace.');\n if (fs.realpathSync(findRepositoryRoot(target.cwd)) !== target.repoRoot)\n throw new Error('Saved session checkout is unavailable.');\n // Only a member checkout records the workspace generation it ran.\n if (target.repoRoot === root) return undefined;\n if (target.inheritedArtifact === undefined) throw new Error('Saved member checkout generation is unavailable.');\n const artifact = parseSyncRegistration(target.inheritedArtifact, 'saved member checkout generation');\n validateSyncRegistration(artifact, resolveSyncLocation(artifact.root, homeDirectory));\n if (artifact.root !== root) throw new Error('Saved member checkout generation belongs to another workspace.');\n return artifact;\n };\n cockpit = await serveHeadlessServer({\n port: options.webPort,\n headlessHub: hub,\n token: attachToken,\n sessionMcpPublicOrigin: () => remoteRuntime?.remote.publicOrigin(),\n sessionMcpStateDir: serverDirectory,\n sessionMcpPublicOriginRevision: () => remoteRuntime?.remote.publicOriginRevision() ?? 0,\n isSessionPersisted: (sessionId, cwd) =>\n openSessions.list().some((record) => record.sessionId === sessionId && record.cwd === cwd),\n workspaceHistory: async (workspaceId) => (await savedHistory(workspaceId)).map((record) => record.summary),\n resumeWorkspaceSession: async (workspaceId, targetSessionId) => {\n const key = `${workspaceId}\\0${targetSessionId}`;\n const pending = workspaceResumes.get(key);\n if (pending) return pending;\n const resume = (async () => {\n const target = (await savedHistory(workspaceId)).find((item) => item.summary.id === targetSessionId);\n if (!target) throw new Error('Saved Pi thread not found in this workspace.');\n const artifact = validatedExecution(target.execution, workspaceId);\n await openSession(\n {\n cwd: target.execution.cwd,\n name: target.summary.name ?? 'untitled',\n ...(target.execution.parentSessionId ? { parentSessionId: target.execution.parentSessionId } : {}),\n ...(target.execution.sessionProvenance ? { sessionProvenance: target.execution.sessionProvenance } : {}),\n },\n target.summary.id,\n artifact,\n workspaceId,\n );\n return target.summary.id;\n })();\n workspaceResumes.set(key, resume);\n try {\n return await resume;\n } finally {\n workspaceResumes.delete(key);\n }\n },\n sessionHistory: (session) => {\n const workspaceRoot = hub.workspaces().find((workspace) => workspace.id === session.workspaceId)?.root;\n if (!workspaceRoot) throw new Error('Session workspace not found.');\n return listSavedSessions(\n path.join(piAgentDirectory(baseEnvironment), 'server', 'sessions'),\n workspaceRoot,\n new Set(hub.snapshot().map((active) => active.id)),\n session.workspaceId,\n );\n },\n readDormantTranscript: (record, request, context) => {\n const workspaceRoot = hub.workspaces().find((workspace) => workspace.id === record.workspaceId)?.root;\n if (!workspaceRoot || (record.groupingRoot !== undefined && record.groupingRoot !== workspaceRoot))\n throw new Error('Saved transcript unavailable.');\n const owner = fs.realpathSync(findRepositoryRoot(record.cwd));\n if (record.repoRoot !== undefined && record.repoRoot !== owner)\n throw new Error('Saved transcript checkout has changed.');\n return readSqliteTranscript(\n path.join(piAgentDirectory(baseEnvironment), 'server', 'sessions', `${record.sessionId}.sqlite`),\n request,\n context,\n {\n sessionId: record.sessionId,\n workspaceRoot: owner,\n workspaceId: record.workspaceId,\n groupingRoot: workspaceRoot,\n },\n );\n },\n restartSession: async (session) => {\n const record = openSessions.list().find((entry) => entry.sessionId === session.id);\n // Only a member checkout records an artifact; it restarts on its workspace's generation.\n const member = record?.artifact !== undefined;\n const ownership = member\n ? resolveWorktreeRestart({\n session,\n record,\n artifact: sessionArtifacts.get(session.id)?.registration,\n workspaces: hub.workspaces(),\n })\n : undefined;\n if (!member) {\n const workspaceRoot = hub.workspaces().find((workspace) => workspace.id === session.workspaceId)?.root;\n if (!workspaceRoot) throw new Error('Session workspace not found.');\n const syncEnvironment: NodeJS.ProcessEnv = { ...baseEnvironment, DOOMPI_ROOT: workspaceRoot };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete syncEnvironment[key];\n try {\n await syncWorkspace(workspaceRoot, syncEnvironment);\n } catch (error) {\n notice(`Workspace sync failed before restart: ${error instanceof Error ? error.message : String(error)}`);\n throw new Error('Workspace sync failed; the session is still running.', { cause: error });\n }\n }\n await hub.closeSession(session.id);\n try {\n await openSession(\n {\n cwd: session.cwd,\n name: session.name,\n ...(session.parentSessionId === undefined ? {} : { parentSessionId: session.parentSessionId }),\n ...(session.sessionProvenance === undefined ? {} : { sessionProvenance: session.sessionProvenance }),\n },\n session.id,\n ownership?.artifact,\n ownership?.workspaceId ?? session.workspaceId,\n );\n } catch (error) {\n // The journal lease allows one writer, so the new host cannot open before the old\n // one closes. Keep the closed session as dormant so it can be revived after a fix.\n if (record !== undefined) openSessions.add(record);\n throw error;\n }\n },\n resumeSession: async (session, targetSessionId) => {\n const workspaceId = session.workspaceId;\n if (!workspaceId || !hub.workspaces().some((workspace) => workspace.id === workspaceId))\n throw new Error('Session workspace not found.');\n const target = (await savedHistory(workspaceId)).find((item) => item.summary.id === targetSessionId);\n if (!target) throw new Error('Saved Pi thread not found in this workspace.');\n const artifact = validatedExecution(target.execution, workspaceId);\n const closedRecord = openSessions.list().find((entry) => entry.sessionId === session.id);\n await hub.closeSession(session.id);\n try {\n await openSession(\n {\n cwd: target.execution.cwd,\n name: target.summary.name ?? 'untitled',\n ...(target.execution.parentSessionId ? { parentSessionId: target.execution.parentSessionId } : {}),\n ...(target.execution.sessionProvenance ? { sessionProvenance: target.execution.sessionProvenance } : {}),\n },\n target.summary.id,\n artifact,\n workspaceId,\n );\n } catch (error) {\n // Same as restart: the session given up for the resume stays revivable.\n if (closedRecord !== undefined) openSessions.add(closedRecord);\n throw error;\n }\n return target.summary.id;\n },\n dormantSessions: () => openSessions.list(),\n removeDormantSession: (record: OpenSessionRecord) => openSessions.remove(record.sessionId),\n reviveSession: async (record: OpenSessionRecord) => {\n // A failed wake may be transient, for example while another server still\n // owns the journal. Keep the record so the user can retry after resolving\n // the conflict instead of losing the session from the cockpit.\n const groupingRoot = hub\n .workspaces()\n .find((workspace) => workspace.id === record.workspaceId && workspace.available !== false)?.root;\n if (!groupingRoot || (record.groupingRoot !== undefined && groupingRoot !== record.groupingRoot))\n throw new Error('The session workspace is unavailable.');\n if (record.repoRoot !== undefined && fs.realpathSync(findRepositoryRoot(record.cwd)) !== record.repoRoot)\n throw new Error('The session checkout has changed.');\n if (record.artifact !== undefined && record.artifact.root !== groupingRoot)\n throw new Error('The inherited workspace generation is unavailable.');\n await openSession(\n {\n cwd: record.cwd,\n name: record.name,\n ...(record.parentSessionId === undefined ? {} : { parentSessionId: record.parentSessionId }),\n ...(record.sessionProvenance === undefined ? {} : { sessionProvenance: record.sessionProvenance }),\n },\n record.sessionId,\n record.artifact,\n record.workspaceId,\n );\n },\n requestAsset: (request) => webCompositions?.request(request) ?? Promise.resolve(undefined),\n compositions: () => ({\n global: webCompositions?.get({ scope: 'global' }),\n publicKey: webCompositions?.publicKey(),\n shell: webCompositions?.shellTrust(),\n workspaces: hub.workspaces().map((workspace) => ({\n ...workspace,\n webComposition: webCompositions?.get({ scope: 'workspace', workspaceId: workspace.id }),\n })),\n }),\n telemetry,\n onNotice: notice,\n });\n notice(`protocol on ${cockpit.url}/api/ws`);\n let resolveShutdown!: (exitCode: number) => void;\n const shutdown = new Promise<number>((resolve) => {\n resolveShutdown = resolve;\n });\n const stop = (): void => resolveShutdown(0);\n signal.addEventListener('abort', stop, { once: true });\n if (signal.aborted) stop();\n try {\n return await shutdown;\n } finally {\n signal.removeEventListener('abort', stop);\n }\n } finally {\n shuttingDown = true;\n stopResourceMonitor();\n executionBudget.close();\n stopPersistSessionNames();\n clearInterval(eventLoopMonitor);\n await bounded(telemetry.recordEvent('doompi_server.shutdown'), 'shutdown telemetry', notice);\n await bounded(\n withShutdownDeadline(() => cockpit?.close(), 'listener shutdown'),\n 'listener shutdown',\n notice,\n );\n await bounded(remoteRuntime?.close() ?? Promise.resolve(), 'remote control shutdown', notice);\n // Session hooks and MCP owners must unwind before their shared hub services.\n // Each session phase has its own deadline, so one stalled session cannot block the rest.\n try {\n await sessionManager.close();\n } catch (error) {\n notice(error instanceof Error ? error.message : String(error));\n }\n await bounded(\n withShutdownDeadline(() => hub.close(), 'hub shutdown'),\n 'hub shutdown',\n notice,\n );\n await bounded(\n withShutdownDeadline(() => requestReceipts.close(), 'receipt shutdown'),\n 'receipt shutdown',\n notice,\n );\n await bounded(\n withShutdownDeadline(() => computerUse?.close?.(), 'computer use shutdown'),\n 'computer use shutdown',\n notice,\n );\n await bounded(\n withShutdownDeadline(() => webCompositions?.close(), 'web composition shutdown'),\n 'web composition shutdown',\n notice,\n );\n const pendingCleanups = [...pendingSessions.values()].map((setup) =>\n bounded(\n withShutdownDeadline(() => setup.cleanup(), 'pending session cleanup'),\n 'pending session cleanup',\n notice,\n ),\n );\n pendingSessions.clear();\n await Promise.allSettled(pendingCleanups);\n await bounded(harnessTelemetry.flush(), 'harness telemetry flush', notice);\n await bounded(harnessTelemetry.shutdown(), 'harness telemetry shutdown', notice);\n await bounded(telemetry.flush(), 'server telemetry flush', notice);\n await bounded(telemetry.shutdown(), 'server telemetry shutdown', notice);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,eAAe,QAAQ,WAA6B,OAAe,QAAkD;CACnH,IAAI;EACF,MAAM,2BAA2B,WAAW,KAAK;CACnD,SAAS,OAAO;EACd,OAAO,GAAG,MAAM,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG;CACrF;AACF;AAEA,eAAsB,iBAAiB,SAAuB,SAAoD;CAChH,MAAM,EACJ,KAAK,SACL,aAAa,qBACb,QACA,uBACA,QACA,kBACE;CAGJ,MAAM,kBAAqC;EAAE,GAAG;EAAqB,mBAAmB;CAAS;CACjG,MAAM,kBAAkB,4BAA4B,eAAe;CACnE,MAAM,oBAAoB;EAAE,KAAK;EAAS,KAAK;EAAiB;CAAO,CAAC,CAAC,CAAC,OAAO,UAC/E,OAAO,gCAAgC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GAAG,CACjG;CACA,MAAM,YAAY,sBAAsB;EAAE,KAAK;EAAS,KAAK;EAAiB,MAAM;CAAO,CAAC;CAC5F,MAAM,gBAAgB,gBAAgB,QAAQ,GAAG,QAAQ;CACzD,MAAM,kBAAkB,KAAK,KAAK,iBAAiB,eAAe,GAAG,QAAQ;CAE7E,MAAM,kBAAkB,sBAAsB,EAAE,WAAW,KAAK,KAAK,iBAAiB,kBAAkB,EAAE,CAAC;CAC3G,MAAM,8BAAc,IAAI,IAAmB;CAC3C,MAAM,mBAA6C;EACjD,SAAS,MAAM;GACb,YAAY,IAAI,IAAI;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AAG,gBAAgB,OAAO,CAAC,CAAC,CAAC,KAAK,UACzD,QACE,2BAA2B,MAAM,QAAQ,GAAG,yBAAyB,GACrE,2BACA,MACF,CACF;EACA,gBAAgB,MAAM;EACtB,MAAM,QAAQ,WAAW,eAAe;EACxC,MAAM,QAAQ,iBAAiB,MAAM,GAAG,2BAA2B,MAAM;EACzE,MAAM,QAAQ,iBAAiB,SAAS,GAAG,8BAA8B,MAAM;EAC/E,MAAM,QAAQ,UAAU,MAAM,GAAG,0BAA0B,MAAM;EACjE,MAAM,QAAQ,UAAU,SAAS,GAAG,6BAA6B,MAAM;CACzE;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/doompi",
3
- "version": "0.0.1-alpha.106",
3
+ "version": "0.0.1-alpha.108",
4
4
  "description": "Opinionated, composable Pi distribution for scoped agent tools, skills, MCP servers, and developer workflows.",
5
5
  "keywords": [
6
6
  "ai",
@@ -277,20 +277,20 @@
277
277
  "registry": "https://registry.npmjs.org/"
278
278
  },
279
279
  "dependencies": {
280
- "@agimon-ai/doompi-autostop": "0.0.1-alpha.79",
281
- "@agimon-ai/doompi-cache": "0.0.1-alpha.68",
282
- "@agimon-ai/doompi-config": "0.0.1-alpha.101",
283
- "@agimon-ai/doompi-core": "0.0.1-alpha.102",
284
- "@agimon-ai/doompi-domain": "0.0.1-alpha.80",
285
- "@agimon-ai/doompi-major-mode": "0.0.1-alpha.80",
286
- "@agimon-ai/doompi-minor-mode": "0.0.1-alpha.102",
287
- "@agimon-ai/doompi-notification": "0.0.1-alpha.79",
288
- "@agimon-ai/doompi-profile": "0.0.1-alpha.80",
289
- "@agimon-ai/doompi-session": "0.0.1-alpha.26",
290
- "@agimon-ai/doompi-skill": "0.0.1-alpha.80",
280
+ "@agimon-ai/doompi-autostop": "0.0.1-alpha.81",
281
+ "@agimon-ai/doompi-cache": "0.0.1-alpha.70",
282
+ "@agimon-ai/doompi-config": "0.0.1-alpha.103",
283
+ "@agimon-ai/doompi-core": "0.0.1-alpha.104",
284
+ "@agimon-ai/doompi-domain": "0.0.1-alpha.82",
285
+ "@agimon-ai/doompi-major-mode": "0.0.1-alpha.82",
286
+ "@agimon-ai/doompi-minor-mode": "0.0.1-alpha.104",
287
+ "@agimon-ai/doompi-notification": "0.0.1-alpha.81",
288
+ "@agimon-ai/doompi-profile": "0.0.1-alpha.82",
289
+ "@agimon-ai/doompi-session": "0.0.1-alpha.28",
290
+ "@agimon-ai/doompi-skill": "0.0.1-alpha.82",
291
291
  "@agimon-ai/doompi-telemetry": "0.0.1-alpha.92",
292
- "@agimon-ai/doompi-ui": "0.0.1-alpha.102",
293
- "@agimon-ai/doompi-web-components": "0.0.1-alpha.60",
292
+ "@agimon-ai/doompi-ui": "0.0.1-alpha.104",
293
+ "@agimon-ai/doompi-web-components": "0.0.1-alpha.62",
294
294
  "@agimon-ai/doompi-web-security": "0.0.1-alpha.55",
295
295
  "@agimon-ai/log-sink-mcp": "0.29.35",
296
296
  "@deepseek-ai/cordis": "4.0.2",
@@ -317,7 +317,7 @@
317
317
  "yaml": "2.9.1"
318
318
  },
319
319
  "devDependencies": {
320
- "@agimon-ai/doompi-runner": "0.0.1-alpha.103",
320
+ "@agimon-ai/doompi-runner": "0.0.1-alpha.105",
321
321
  "@agimon-ai/vibe-lint-plugin-doom-cli": "0.0.1-alpha.27",
322
322
  "@earendil-works/pi-ai": "0.99.1",
323
323
  "@earendil-works/pi-client": "0.99.1",