@agimon-ai/po 0.0.0-alpha.48 → 0.0.0-alpha.49

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.
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.cjs","names":["net","path","withShutdownDeadline","createServerExecutionBudget","ensureGlobalLogSink","createServerTelemetry","os","piAgentDirectory","createNodePlatform","createNodeIsolate","createNodeNpm","poHomeDirectory","createWatcherService","BACKGROUND_CONTEXT","globalPoConfigDirectory","createBundlerService","poPackageRoot","outsideNodeModules","createRequestReceipts","createWorkspaceRegistry","resolveWorkspaceRoot","createWorkspaceSandboxRegistry","createOpenSessionRegistry","readRecycleState","prepareSessionRestore","takeTunnelIntent","createHarnessTelemetry","createHeadlessSessionManager","publishHeadlessSelectionStatus","readMinorModeCatalog","HARNESS_STATE_POINTER","HARNESS_STATE_KEYS","writeRecycleFile","readSessionFileDirectories","removeSessionFiles","handoffProvider","createComputerUseBinding","createPoNotificationEntryData","PO_NOTIFICATION_ENTRY_TYPE","createHeadlessHub","resolveProfile","createDefaultWorkspaceFolder","checkoutWorkspaceId","createModelGatewayContainer","createSandboxRouter","createHostModelGateway","createSandboxSessionHandoff","listSavedSessionRecords","createIdleRestart","testIdleRestartOverrides","readPoBackgroundWorkService","holdsRestart","monitorRuntimeResources","getOrThrow","resolveSessionIdentity","crypto","reapAbandonedPublications","processIsAlive","createWebCompositions","nodeHost","createBackgroundSync","createSyncCheckpoints","syncPointerPath","unslottedWebPackages","compositionPackageRoots","unsyncedSelectors","mountWebPluginSlots","mountNativePluginIds","createKeyedPickup","readGlobalWebBuildRecord","readGlobalNativeBuildRecord","globalWebPluginRoots","readGlobalWebBuildStatus","readGlobalNativeBuildStatus","readSyncPointer","syncedBuildKeys","newestGlobalWebBuildKey","NATIVE_APP_PLATFORMS","readNativeAppBuild","loadServerPackages","readMcpAppBuild","loadMcpPlugins","mcpUiResource","loadMajorModesConfig","missingLayerPackageSpecifiers","createLayerResolvers","buildHarnessContext","createSettingsApi","pathExists","createRemoteRuntime","loadNativePushCredentials","createNativePushSender","subscribeNativePush","PO_WORKSPACE_SANDBOXES_CONTRACT","PO_SANDBOX_IDENTITY_CONTRACT","PO_PACKAGE_HEALTH_CONTRACT","PO_SELF_IMPROVE_CONTRACT","PO_REMOTE_ORIGIN_CONTRACT","identifyWorkspace","readWorkspaceMarker","resolveExtensionComposition","selectedServerProviderOverrides","resolveLayers","serveSessionApis","PO_SHARE_FILE_REMOTE_OFF_MESSAGE","SANDBOX_UNREACHABLE","launchSessionRequest","WORKFLOW_STEP_SESSION_PROVENANCE","sessionSelectionArgs","CONTAINER_WORKTREE_GONE","serveHeadlessServer","listSavedSessions","readSqliteTranscript","resolveWebTemplateDecision","reopenRecycledSessions","isCleanUserStop","stopSandboxProviders","SANDBOX_STOP_DEADLINE_MS","removeRecycleFile","keepTunnelIntent"],"sources":["../../../../src/builders/server/runtime.ts"],"sourcesContent":["import crypto from 'node:crypto';\nimport net from 'node:net';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { createSettingsApi } from '@agimon-ai/po-config';\nimport { globalPoConfigDirectory } from '@agimon-ai/po-config/config';\nimport { loadMajorModesConfig, resolveLayers } from '@agimon-ai/po-config/majorModes';\nimport { resolveProfile } from '@agimon-ai/po-config/profiles';\nimport { readPoBackgroundWorkService } from '@agimon-ai/po-core/backgroundWork';\nimport type { PoHeadlessRefreshAxis } from '@agimon-ai/po-core/headless';\nimport {\n createHeadlessHub,\n type HeadlessHub,\n type HeadlessHubOptions,\n type HeadlessHubSession,\n type HeadlessWorkspace,\n} from '@agimon-ai/po-core/headlessHub';\nimport { serveHeadlessServer } from '@agimon-ai/po-core/headlessServer';\nimport type { HeadlessSessionHost, HeadlessSessionHostOptions } from '@agimon-ai/po-core/headlessSessionHost';\nimport { createHeadlessSessionManager } from '@agimon-ai/po-core/headlessSessionManager';\nimport {\n PO_PACKAGE_HEALTH_CONTRACT,\n PO_SELF_IMPROVE_CONTRACT,\n type PoPackageFailureRecord,\n type PoSelfImproveReloadResult,\n} from '@agimon-ai/po-core/help';\nimport {\n createOpenSessionRegistry,\n createRequestReceipts,\n createWorkspaceRegistry,\n identifyWorkspace,\n listSavedSessionRecords,\n listSavedSessions,\n readSqliteTranscript,\n readWorkspaceMarker,\n writeWorkspaceMarker,\n} from '@agimon-ai/po-core/history';\nimport type { OpenSessionRecord, SavedSessionExecution, WorkspaceRecord } from '@agimon-ai/po-core/history';\nimport { WORKFLOW_STEP_SESSION_PROVENANCE } from '@agimon-ai/po-core/hubChannel';\nimport type {\n PoHubSessionApiRequest,\n PoHubSessionCreateRequest,\n PoHubSessionScope,\n} from '@agimon-ai/po-core/hubChannel';\nimport { loadMcpPlugins, mcpUiResource, type LoadedMcpPlugins } from '@agimon-ai/po-core/mcpFacet';\nimport { createModelGatewayContainer, type ModelGatewayContainer } from '@agimon-ai/po-core/modelGateway';\nimport { createNodePlatform } from '@agimon-ai/po-core/nodePlatform';\nimport { createPoNotificationEntryData, PO_NOTIFICATION_ENTRY_TYPE } from '@agimon-ai/po-core/notification';\nimport { createServerExecutionBudget, PO_SHARE_FILE_REMOTE_OFF_MESSAGE } from '@agimon-ai/po-core/packageApi';\nimport type { PoApiHandler, PoHostMediaArbitration, PoPeerAgentRegistry } from '@agimon-ai/po-core/packageApi';\nimport {\n serveSessionApis,\n type PackageApiServer,\n type PackageReconcileResult,\n} from '@agimon-ai/po-core/packageApiServer';\nimport { piAgentDirectory, poHomeDirectory } from '@agimon-ai/po-core/piSettings';\nimport {\n BACKGROUND_CONTEXT,\n getOrThrow,\n pathExists,\n nodeHost,\n readSessionFileDirectories,\n removeSessionFiles,\n} from '@agimon-ai/po-core/platform';\nimport { createRemoteRuntime, PO_REMOTE_ORIGIN_CONTRACT, type RemoteRuntime } from '@agimon-ai/po-core/remoteRuntime';\nimport type {\n HeadlessSessionCloseOptions,\n HeadlessSessionManager,\n} from '@agimon-ai/po-core/runtimeHeadlessSessionManager';\nimport { createHarnessTelemetry } from '@agimon-ai/po-core/runtimeLogSinkTelemetry';\nimport { PO_SANDBOX_IDENTITY_CONTRACT, type PoSandboxIdentity } from '@agimon-ai/po-core/sandboxIdentity';\nimport {\n loadServerPackages,\n selectedServerProviderOverrides,\n type LoadedServerPackages,\n} from '@agimon-ai/po-core/serverPlugin';\nimport { createServerTelemetry } from '@agimon-ai/po-core/serverTelemetry';\nimport { createWebCompositions, reapAbandonedPublications } from '@agimon-ai/po-core/webCompositions';\nimport { createWorkspaceSandboxRegistry, PO_WORKSPACE_SANDBOXES_CONTRACT } from '@agimon-ai/po-core/workspaceSandboxes';\nimport { readMinorModeCatalog } from '@agimon-ai/po-minor-mode';\nimport { createNativePushSender } from '@agimon-ai/po-notification';\n\nimport { HARNESS_STATE_KEYS, HARNESS_STATE_POINTER, updateHarnessState } from '../../composition/harnessState';\nimport { missingLayerPackageSpecifiers } from '../../composition/layerPackageInstaller';\nimport { resolveWorkspaceRoot } from '../../composition/repository';\nimport { globalWebPluginRoots, processIsAlive, readSyncPointer, syncPointerPath } from '../../composition/syncService';\nimport { poPackageRoot } from '../cli/entryResolution';\nimport { createLayerResolvers, resolveExtensionComposition, unsyncedSelectors } from '../cli/extensionAssembler';\nimport { buildHarnessContext } from '../cli/harnessContext';\nimport { createNodeIsolate } from '../isolate';\nimport {\n type GlobalNativeBuildRecord,\n mountNativePluginIds,\n NATIVE_APP_PLATFORMS,\n readGlobalNativeBuildRecord,\n readGlobalNativeBuildStatus,\n readNativeAppBuild,\n} from '../native';\nimport { createNodeNpm } from '../npm';\nimport {\n compositionPackageRoots,\n type GlobalWebBuildRecord,\n mountWebPluginSlots,\n newestGlobalWebBuildKey,\n readGlobalWebBuildRecord,\n readGlobalWebBuildStatus,\n unslottedWebPackages,\n} from '../web';\nimport { createBackgroundSync, createKeyedPickup, createSyncCheckpoints, syncedBuildKeys } from './backgroundSync';\nimport { createBundlerService } from './bundlerService';\nimport { createComputerUseBinding } from './computerUseBinding';\nimport { registerContainedSessionMethods } from './containedSessions';\nimport { createDefaultWorkspaceFolder } from './defaultWorkspace';\nimport { createHostModelGateway, type HostModelGateway } from './hostModelGateway';\nimport {\n createIdleRestart,\n holdsRestart,\n keepTunnelIntent,\n prepareSessionRestore,\n readRecycleState,\n removeRecycleFile,\n reopenRecycledSessions,\n RESTART_EXIT_CODE,\n takeTunnelIntent,\n testIdleRestartOverrides,\n writeRecycleFile,\n} from './idleRestart';\nimport { ensureGlobalLogSink } from './logSink';\nimport { readMcpAppBuild } from './mcpAppBuild';\nimport { loadNativePushCredentials, subscribeNativePush } from './nativePush';\nimport { monitorRuntimeResources } from './runtimeResources';\nimport { createSandboxRouter, SANDBOX_UNREACHABLE, type SandboxRouter } from './sandboxRouter';\nimport {\n CONTAINER_WORKTREE_GONE,\n createSandboxSessionHandoff,\n handoffProvider,\n type HandoffProvider,\n type SandboxSessionHandoff,\n} from './sandboxSessionHandoff';\nimport { publishHeadlessSelectionStatus } from './selectionStatus';\nimport {\n launchSessionRequest,\n type PinnedSelectionAxis,\n resolveSessionIdentity,\n sessionSelectionArgs,\n} from './sessionArguments';\nimport { isCleanUserStop, SANDBOX_STOP_DEADLINE_MS, stopSandboxProviders, withShutdownDeadline } from './shutdown';\nimport type { ServeOptions, ServerRuntimeEnvironment } from './types';\nimport { createWatcherService, outsideNodeModules, type WatchChangeSource } from './watcherService';\nimport { resolveWebTemplateDecision } from './webTemplateDecision';\nimport { checkoutWorkspaceId } from './workspaceCheckout';\n\n/** What asked every scope to recheck: a watched change, a watcher tick, a finished sync or an upm install. */\ntype ScopeCheckSource = WatchChangeSource | 'sync' | 'upm';\n/** The largest protocol message a contained server accepts from its host. */\nconst CONTAINED_MAX_PAYLOAD_BYTES = 8 * 1024 * 1024;\n/** The base path of po-config's settings API, the one API a sandboxed workspace still answers on the host. */\nconst SETTINGS_API = 'settings';\n/** Package failures Help reports at once; the oldest drop first. */\nconst PACKAGE_FAILURE_LIMIT = 64;\n\n/** Whether a listen address stays on this machine: `localhost`, `127.0.0.0/8`, or `::1`. */\nfunction isLoopbackHost(host: string): boolean {\n const address = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;\n if (address.toLowerCase() === 'localhost') return true;\n if (net.isIPv4(address)) return address.startsWith('127.');\n if (!net.isIPv6(address)) return false;\n const lower = address.toLowerCase();\n return (\n lower === '::1' || (lower.startsWith('::ffff:') && net.isIPv4(lower.slice(7)) && lower.slice(7).startsWith('127.'))\n );\n}\n\n/**\n * The installed payload a contained server imports in place, so it never writes package snapshots into a\n * read-only runtime. An installed Po sits at `<payload>/node_modules/@agimon-ai/po`; a source checkout is\n * its own package root.\n */\nfunction containedImmutableRoot(packageRoot: string): string {\n const scopeDirectory = path.dirname(packageRoot);\n return path.basename(path.dirname(scopeDirectory)) === 'node_modules'\n ? path.resolve(packageRoot, '../../..')\n : packageRoot;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** Whether the host itself serves the workspace: admitted here and not run by a sandbox. */\nfunction servedOnHost(workspace: HeadlessWorkspace): boolean {\n return workspace.available !== false && workspace.sandbox === undefined;\n}\n\n/** A workspace's live sandbox state, as the hub carries it. */\ntype SandboxStatusFields = Pick<HeadlessWorkspace, 'sandboxState' | 'sandboxReason'>;\n\n/** The hub's view of a workspace record: one mapping, so every registration carries its sandbox and its state. */\nfunction hubWorkspace(\n record: WorkspaceRecord,\n available: boolean,\n status: SandboxStatusFields = {},\n): HeadlessWorkspace {\n return {\n id: record.id,\n root: record.root,\n ...(record.name === undefined ? {} : { name: record.name }),\n ...(record.sandbox === undefined ? {} : { sandbox: record.sandbox }),\n ...(status.sandboxState === undefined ? {} : { sandboxState: status.sandboxState }),\n ...(status.sandboxReason === undefined ? {} : { sandboxReason: status.sandboxReason }),\n available,\n };\n}\n\nconst sameSandboxStatus = (left: SandboxStatusFields, right: SandboxStatusFields): boolean =>\n left.sandboxState === right.sandboxState && left.sandboxReason === right.sandboxReason;\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: rawNotice,\n resolveHarnessOptions,\n signal,\n onExtensionCheck,\n automation,\n } = runtime;\n // Only a contained server, reached through its sandbox's port forward, listens beyond loopback.\n if (options.host !== undefined && options.contained !== true && !isLoopbackHost(options.host))\n throw new Error(`--host ${options.host} is not a loopback address. Only a --contained server may listen on it.`);\n const sandboxIdentity: PoSandboxIdentity | undefined =\n options.contained === true\n ? Object.freeze({\n contained: true,\n ...(options.workspaceId === undefined ? {} : { workspaceId: options.workspaceId }),\n })\n : undefined;\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: rawNotice }).catch((error: unknown) =>\n rawNotice(`Global log sink unavailable: ${error instanceof Error ? error.message : String(error)}`),\n );\n // Telemetry's own warnings stay on the raw channel, so a failing sink cannot feed itself.\n const telemetry = createServerTelemetry({ cwd: baseCwd, env: baseEnvironment, warn: rawNotice });\n const notice = (message: string): void => {\n rawNotice(message);\n void telemetry\n .recordEvent('po_server.notice', { message })\n .catch((error: unknown) => rawNotice(`notice telemetry failed: ${String(error)}`));\n };\n const homeDirectory = baseEnvironment.HOME ?? os.homedir();\n const serverDirectory = path.join(piAgentDirectory(baseEnvironment), 'server');\n const temporaryDirectory = path.resolve(\n baseEnvironment.TMPDIR || baseEnvironment.TMP || baseEnvironment.TEMP || os.tmpdir(),\n );\n // One host platform for every composition root this server runs: hub, workspaces and sessions.\n const platform = {\n ...createNodePlatform({\n homeDirectory,\n temporaryDirectory,\n sessionsRoot: path.join(serverDirectory, 'sessions'),\n }),\n isolate: createNodeIsolate(),\n npm: createNodeNpm({\n poHome: poHomeDirectory(homeDirectory, baseEnvironment),\n homeDirectory,\n temporaryDirectory,\n environment: baseEnvironment,\n }),\n };\n /** Called on a watched change; assigned once every scope can be checked. */\n let pickUpChange = (_source: WatchChangeSource): void => undefined;\n const hostFiles = platform.env(baseCwd);\n const watcher = createWatcherService({\n onChange: (source) => pickUpChange(source),\n onNotice: notice,\n exists: async (directory) => {\n const info = await hostFiles.fileInfo(directory, BACKGROUND_CONTEXT);\n return info.ok && info.value.kind === 'directory';\n },\n });\n const isConfig = (file: string) => /\\.ya?ml$/u.test(file);\n // The Po home's documents layer under every root's own .po copy.\n watcher.add({ path: globalPoConfigDirectory(homeDirectory), include: isConfig });\n /** Compiles and loads packages once per content; every scope and session selects from it. */\n const bundler = createBundlerService({\n files: hostFiles,\n homeDirectory,\n environment: baseEnvironment,\n // Desktop owns this installed payload. Writing package snapshots into it breaks the app's signature.\n // A contained server runs from a read-only runtime and says so with its flag, not the environment.\n ...(sandboxIdentity !== undefined\n ? { immutableRoot: containedImmutableRoot(poPackageRoot()) }\n : baseEnvironment.PO_DISTRIBUTION === 'desktop' && baseEnvironment.PO_PACKAGE_ROOT\n ? { immutableRoot: path.resolve(baseEnvironment.PO_PACKAGE_ROOT, '../../..') }\n : {}),\n onNotice: notice,\n // What a root's compositions read: its .po documents and every repo-local package it selects.\n // Versioned and installed packages change only through sync or upm, which check every scope.\n onCompositions: (root, _compositions, packageRoots) => {\n watcher.add({ path: path.join(root, '.po'), include: isConfig });\n for (const packageRoot of packageRoots)\n if (!packageRoot.includes(`${path.sep}node_modules${path.sep}`))\n watcher.add({ path: packageRoot, recursive: true, include: outsideNodeModules });\n },\n });\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-v1') });\n const activeMedia = new Set<() => boolean>();\n const mediaArbitration: PoHostMediaArbitration = {\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: PoPeerAgentRegistry = {\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 // A contained server's workspace keeps its host id: its checkout root is recorded under that id before anything\n // admits it, so an exact root match names it and the container's session ids belong to the host's workspace.\n if (sandboxIdentity?.workspaceId !== undefined) {\n const containedRoot = await resolveWorkspaceRoot(baseCwd);\n for (const record of workspaces.list())\n if (record.root === containedRoot && record.id !== sandboxIdentity.workspaceId) workspaces.remove(record.id);\n if (!workspaces.list().some((record) => record.id === sandboxIdentity.workspaceId && record.root === containedRoot))\n workspaces.add({ id: sandboxIdentity.workspaceId, root: containedRoot });\n }\n // Bound on the global scope before it is served, so a root's global plugin can register a provider while\n // it loads. Closed once the global scope is up.\n const sandboxes = createWorkspaceSandboxRegistry();\n // Workspaces whose scope this process served. The hub cannot serve one twice, so a workspace that gets\n // a sandbox and is cleared again in the same run is marked available again instead of readmitted.\n const servedWorkspaces = new Set<string>();\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 onNotice: notice,\n });\n const recycled = await readRecycleState(serverDirectory);\n const restorePlan = prepareSessionRestore(recycled);\n const recoverySessionIds = new Set(restorePlan.sessionIds);\n // A crash or recycle record wins; otherwise a named tunnel kept open through the last normal stop.\n const keptTunnel = await takeTunnelIntent(serverDirectory);\n const tunnelToRestore = recycled?.tunnel ?? keptTunnel;\n let recoveryTunnel = tunnelToRestore;\n let persistRecovery = (): void => {};\n let cleanShutdown = false;\n let recoveryWork: Promise<unknown> = Promise.resolve();\n let recoveryWrites: Promise<void> = Promise.resolve();\n let recovering = false;\n const recordLiveSession = (\n created: Awaited<ReturnType<HeadlessHub['create']>>,\n repoRoot: string,\n groupingRoot: string,\n ): void => {\n if (created.workspaceId === undefined) throw new Error('The new session has no workspace.');\n const saved = openSessions.add({\n sessionId: created.id,\n workspaceId: created.workspaceId,\n cwd: created.cwd,\n repoRoot,\n groupingRoot,\n name: created.name,\n createdAt: created.createdAt,\n ...(created.parentSessionId === undefined ? {} : { parentSessionId: created.parentSessionId }),\n ...(created.sessionProvenance === undefined ? {} : { sessionProvenance: created.sessionProvenance }),\n ...(created.interaction === undefined ? {} : { interaction: created.interaction }),\n ...(created.groups === undefined || created.groups.length === 0 ? {} : { groups: [...created.groups] }),\n });\n if (saved === false) throw new Error('The new session could not be durably recorded.');\n recoverySessionIds.add(created.id);\n persistRecovery();\n };\n /** Named jobs running now, and every job that ran since the last sample, so a stall names what was busy. */\n const activeJobs = new Map<string, number>();\n const recentJobs = new Set<string>();\n const trackJob = async <T>(name: string, run: () => Promise<T>): Promise<T> => {\n activeJobs.set(name, (activeJobs.get(name) ?? 0) + 1);\n recentJobs.add(name);\n try {\n return await run();\n } finally {\n const left = (activeJobs.get(name) ?? 1) - 1;\n if (left === 0) activeJobs.delete(name);\n else activeJobs.set(name, left);\n }\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('po_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 // `none` means no named job ran: profile the host rather than reading scope checks.\n const jobs = [...recentJobs].join(':') || 'none';\n recentJobs.clear();\n for (const name of activeJobs.keys()) recentJobs.add(name);\n if (delay >= 100)\n void telemetry\n .recordEvent('po_server.event_loop_delay', { duration_ms: Math.round(delay), job_name: jobs })\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: LoadedServerPackages;\n mcpBundle: LoadedMcpPlugins;\n /** Loads the session's package set again from its own composition root and selection. */\n loadBundle: () => Promise<LoadedServerPackages>;\n };\n type SessionArtifacts = SessionSetup & { apis: PackageApiServer };\n /** The server's environment rooted at one configuration root, with no harness state of its own. */\n const rootEnvironment = (root: string): NodeJS.ProcessEnv => {\n const environment: NodeJS.ProcessEnv = { ...baseEnvironment, PO_ROOT: root };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete environment[key];\n return environment;\n };\n const pendingSessions = new Map<string, SessionSetup>();\n /** The last harness context built to report each repository's MCP projection, kept while it is current. */\n const repositoryContexts = new Map<string, { cleanup(): Promise<void> }>();\n const sessionArtifacts = new Map<string, SessionArtifacts>();\n /** Each host's session package root, where its session services (background work included) live. */\n const sessionServiceRoots = new WeakMap<HeadlessSessionHost, Parameters<HeadlessSessionHost['preparePackages']>[0]>();\n /** Assigned once packages can load: reloads one running session's own packages. */\n let reloadSessionPackages: ((sessionId: string) => Promise<PackageReconcileResult>) | undefined;\n /** Assigned with reloadSessionPackages: re-applies one session's selection axes from disk. */\n let refreshSessionSelection:\n | ((sessionId: string, axes: readonly PoHeadlessRefreshAxis[]) => Promise<void>)\n | undefined;\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 persistRecovery = () => {\n if (shuttingDown || signal.aborted) return;\n const ids = [...recoverySessionIds];\n const details = {\n kind: 'live' as const,\n crashRestores: restorePlan.crashRestores,\n ...(recoveryTunnel === undefined ? {} : { tunnel: recoveryTunnel }),\n };\n recoveryWrites = recoveryWrites\n .then(() => writeRecycleFile(serverDirectory, ids, details))\n .catch((error: unknown) => {\n notice(`Could not persist crash recovery: ${error instanceof Error ? error.message : String(error)}`);\n });\n };\n\n const removeSessionOutputs = async (sessionId: string): Promise<void> => {\n // A container session's files live in its container, which removes them, as do a host session's the host just\n // handed over.\n const handedTo = handoff?.handedOff(sessionId);\n if (router !== undefined && (router.owns(sessionId) || handedTo !== undefined)) {\n await router.removeSession(sessionId, handedTo);\n handoff?.forget(sessionId);\n openSessions.remove(sessionId);\n return;\n }\n const directories = await readSessionFileDirectories(platform.sessions, sessionId);\n await removeSessionFiles({\n platform,\n sessionId,\n environment: baseEnvironment,\n artifactDirectory: path.join(\n directories?.agentDirectory ?? piAgentDirectory(baseEnvironment, homeDirectory),\n 'po-artifacts',\n sessionId,\n ),\n ...(directories === undefined ? {} : { directories }),\n });\n // Leave the record available for a retry until both output roots have been removed.\n openSessions.remove(sessionId);\n };\n\n /** Routes the sessions of contained workspaces into their containers; host servers only. */\n let router: SandboxRouter | undefined;\n /** Hands sessions over between the host and a sandbox's Po home when a workspace switches; host servers only. */\n let handoff: SandboxSessionHandoff | undefined;\n /** The sandboxed workspace's provider, when it runs with a Po home on host disk that sessions can move into. */\n const handoffProviderOf = (workspaceId: string | undefined): HandoffProvider | undefined => {\n const sandbox = workspaces.list().find((workspace) => workspace.id === workspaceId)?.sandbox;\n return sandbox === undefined ? undefined : handoffProvider(sandboxes.get(sandbox));\n };\n /** The host's own part of a sandbox's state: a handover in progress, or a switch that failed. */\n const sandboxTransitions = new Map<string, SandboxStatusFields>();\n /** Set once the global scope has loaded, so a provider missing by then is missing for good. */\n let sandboxProvidersSettled = false;\n /**\n * A workspace's live sandbox state. A sandboxed one: the host's transition, else running while linked, else what\n * its provider reports. A local one: unavailable only when every provider that reports availability cannot run\n * sandboxes now, so the switch can say why it is off.\n */\n const sandboxStatus = (record: WorkspaceRecord): SandboxStatusFields => {\n if (record.sandbox === undefined) {\n const reports = sandboxes\n .list()\n .map((provider) => provider.availability?.())\n .filter((report) => report !== undefined);\n const blocked = reports.find((report) => !report.available);\n return blocked === undefined || blocked.available || reports.some((report) => report.available)\n ? {}\n : { sandboxState: 'unavailable', sandboxReason: blocked.reason };\n }\n // A switch that is starting the sandbox gives way to running, or to a failure its provider reports.\n const transition = sandboxTransitions.get(record.id);\n if (transition !== undefined && transition.sandboxState !== 'starting') return transition;\n if (router?.connected(record.id) === true) return { sandboxState: 'running' };\n const provider = sandboxes.get(record.sandbox);\n if (provider === undefined)\n return sandboxProvidersSettled\n ? { sandboxState: 'unavailable', sandboxReason: `The sandbox provider '${record.sandbox}' is not installed.` }\n : {};\n const availability = provider.availability?.();\n if (availability !== undefined && !availability.available)\n return { sandboxState: 'unavailable', sandboxReason: availability.reason };\n const status = provider.status?.(record.id);\n if (status?.state === 'failed') return { sandboxState: 'failed', sandboxReason: status.reason };\n // Running in the provider but not linked yet still counts as starting, as does a provider still checking.\n return (\n transition ??\n (status !== undefined || (provider.availability !== undefined && availability === undefined)\n ? { sandboxState: 'starting' }\n : {})\n );\n };\n const hubEntry = (record: WorkspaceRecord, available: boolean): HeadlessWorkspace =>\n hubWorkspace(record, available, sandboxStatus(record));\n /** Registers the workspace again when its availability or sandbox state changed, so clients see it live. */\n const refreshWorkspace = (workspaceId: string): void => {\n const record = workspaces.list().find((workspace) => workspace.id === workspaceId);\n const known = hub.workspaces().find((workspace) => workspace.id === workspaceId);\n // A record whose sandbox changed is registered by the switch itself.\n if (record === undefined || known === undefined || known.sandbox !== record.sandbox) return;\n const available =\n record.sandbox === undefined ? known.available !== false : router?.connected(workspaceId) === true;\n const entry = hubEntry(record, available);\n if (available === (known.available !== false) && sameSandboxStatus(entry, known)) return;\n hub.registerWorkspace(entry);\n };\n const refreshWorkspaces = (): void => {\n for (const workspace of hub.workspaces()) refreshWorkspace(workspace.id);\n };\n const stopSandboxWatches: (() => void)[] = [];\n /**\n * A host session of a workspace that is now sandboxed closed: it follows the workspace into the sandbox, and the\n * host scope, kept only for host sessions, unloads with the last of them.\n */\n const handOffClosedSession = async (sessionId: string, workspaceId: string, keepDormant: boolean): Promise<void> => {\n const provider = handoffProviderOf(workspaceId);\n if (provider === undefined || handoff === undefined) return;\n try {\n await handoff.sessionClosed(sessionId, workspaceId, keepDormant, provider);\n } catch (error) {\n notice(`Session ${sessionId} could not follow its workspace into the sandbox: ${errorMessage(error)}`);\n }\n const hostSessionsLeft = baseSessionManager\n .sessions()\n .some(\n (host) =>\n host.runtime.sessionId !== sessionId && hub.session(host.runtime.sessionId)?.workspaceId === workspaceId,\n );\n if (hostSessionsLeft || !servedWorkspaces.has(workspaceId)) return;\n servedWorkspaces.delete(workspaceId);\n await hub\n .unloadWorkspaceScope?.(workspaceId)\n .catch((error: unknown) => notice(`Workspace '${workspaceId}' scope did not unload: ${errorMessage(error)}`));\n };\n const closeManagedSession = async (sessionId: string, options?: HeadlessSessionCloseOptions): Promise<void> => {\n // A container session never had a host record or host outputs; at shutdown its mirror only lets go.\n if (router?.mirror(sessionId) !== undefined) {\n await router.closeSession(sessionId, { keepDormant: options?.keepDormant === true, disposeOnly: shuttingDown });\n return;\n }\n // The hub has already unregistered the session; its record still names the workspace.\n const closingWorkspaceId = openSessions.list().find((record) => record.sessionId === sessionId)?.workspaceId;\n // A released session keeps its record, which is what lists it as dormant.\n if (!shuttingDown) {\n recoverySessionIds.delete(sessionId);\n persistRecovery();\n if (options?.keepDormant !== true) openSessions.remove(sessionId);\n }\n const artifacts = sessionArtifacts.get(sessionId);\n sessionArtifacts.delete(sessionId);\n webCompositions?.remove({ scope: 'session', sessionId });\n webCompositions?.removeNative({ 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 packages 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 if (!shuttingDown && closingWorkspaceId !== undefined)\n await handOffClosedSession(sessionId, closingWorkspaceId, options?.keepDormant === true);\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) ?? router?.mirror(sessionId),\n sessions: () => [...baseSessionManager.sessions(), ...(router?.mirrors() ?? [])],\n closeSession: closeManagedSession,\n async close() {\n const ids = sessionManager.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: (scope: PoHubSessionScope, request: PoHubSessionApiRequest) => Promise<Response> = async () =>\n Response.json({ error: 'Session API unavailable.' }, { status: 404 });\n /** Assigned once the shared API context exists: the host-side APIs of a workspace whose scope it does not serve. */\n let unservedWorkspaceApi: NonNullable<HeadlessHubOptions['unservedWorkspaceApi']> = () => undefined;\n let openSession: (\n request: PoHubSessionCreateRequest,\n sessionId?: string,\n groupingWorkspaceId?: string,\n ) => Promise<PoHubSessionScope> = async () => {\n throw new Error('The cockpit session service is not ready.');\n };\n let admitWorkspace: (\n root: string,\n name?: string,\n ) => Promise<HeadlessWorkspace & { available: boolean }> = async () => {\n throw new Error('Workspace admission is not ready.');\n };\n let dormantSessions: () => readonly OpenSessionRecord[] = () => [];\n let reviveSession: (sessionId: string) => Promise<void> = async () => {\n throw new Error('Session revival is not ready.');\n };\n let remoteRuntime: RemoteRuntime | undefined;\n let stopNativePush: (() => void) | undefined;\n const computerUse = await createComputerUseBinding(process, {\n isDeviceAuthorized: (id) => remoteRuntime?.remote.isDeviceAuthorized(id) === true,\n stepUpRequired: () => remoteRuntime?.remote.stepUpRequired('computer-use.activate') === true,\n });\n /** Packages whose build failed since their scope's last commit, keyed like `bundler` scopes. */\n const failedPackages = new Map<string, Set<string>>();\n /** What Help's `help_status` reads: each package's latest failure per scope, oldest dropped first. */\n const packageFailures = new Map<string, PoPackageFailureRecord>();\n const recordPackageFailure = (record: Omit<PoPackageFailureRecord, 'at'>): void => {\n const id = `${record.scope}\\0${record.packageName}`;\n const reason = record.reason.slice(0, 512);\n const repeated = packageFailures.get(id)?.reason === reason;\n packageFailures.delete(id);\n packageFailures.set(id, { ...record, reason, at: new Date().toISOString() });\n for (const oldest of packageFailures.keys()) {\n if (packageFailures.size <= PACKAGE_FAILURE_LIMIT) break;\n packageFailures.delete(oldest);\n }\n if (!repeated) notifyPackageFailure(record);\n };\n /** Shows a failure once in each live top-level session of its scope, as a notification the hub sends to web and native. */\n const notifyPackageFailure = (record: Omit<PoPackageFailureRecord, 'at'>): void => {\n const data = createPoNotificationEntryData({\n title: 'Plugin failed',\n body: `${record.packageName} could not ${record.stage} (${record.reason})${record.previous === 'restored' ? '. Its previous build still runs.' : ''}`,\n level: 'error',\n });\n if (!data) return;\n for (const session of hub.snapshot()) {\n if (session.parentSessionId !== undefined || session.host.agentSession !== undefined) continue;\n if (record.scope !== 'global' && record.scope !== `workspace:${session.workspaceId}`) continue;\n void session.host.runtime\n .appendCustomEntry(PO_NOTIFICATION_ENTRY_TYPE, data)\n .catch((error: unknown) => notice(`Plugin failure notice for session ${session.id} failed: ${String(error)}`));\n }\n };\n /** Ends one install of a scope: returns the packages that failed to apply and clears the rest's record. */\n const takeFailedPackages = (\n key: string,\n packages: readonly { readonly declaration: { readonly packageName: string } }[],\n ): ReadonlySet<string> => {\n const failed = failedPackages.get(key) ?? new Set<string>();\n failedPackages.delete(key);\n for (const { declaration } of packages)\n if (!failed.has(declaration.packageName)) packageFailures.delete(`${key}\\0${declaration.packageName}`);\n return failed;\n };\n let hub!: HeadlessHub;\n /** Assigned once the global builds can be read; no session opens before then. */\n let publishSessionCompositions: NonNullable<HeadlessHubOptions['publishSessionCompositions']> = () => ({});\n hub = createHeadlessHub({\n manager: sessionManager,\n platform,\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 // The session mounts only its major mode's plugins, republished when the mode changes.\n publishSessionCompositions: (sessionId, root, majorMode) => publishSessionCompositions(sessionId, root, majorMode),\n admitWorkspace: async ({ root, name }) => {\n const byName = root === undefined || root.trim() === '';\n const admitted = await admitWorkspace(\n byName ? await createDefaultWorkspaceFolder(name ?? '', homeDirectory) : root,\n name,\n );\n // A channel admitting a folder by name gets a host workspace; a sandboxed one is not that.\n if (byName && admitted.sandbox !== undefined)\n throw new Error(\n `Workspace '${admitted.name ?? admitted.id}' runs in a sandbox and cannot be admitted by name.`,\n );\n return admitted;\n },\n dormantSessions: () => dormantSessions(),\n reviveSession: (sessionId) => reviveSession(sessionId),\n onWorkspaceRemoved: (workspaceId) => {\n workspaces.remove(workspaceId);\n bundler.forgetScope(`workspace:${workspaceId}`);\n webCompositions?.remove({ scope: 'workspace', workspaceId });\n webCompositions?.removeNative({ 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 ((await checkoutWorkspaceId(workspaces.list(), request.cwd)) !== placement.workspaceId)\n throw new Error('The session directory is outside this workspace.');\n return openSession(request, 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 onPackageFailed: (mount, failure) => {\n if (mount.scope === 'session') return;\n const key = mount.scope === 'global' ? 'global' : `workspace:${mount.workspaceId}`;\n failedPackages.set(key, (failedPackages.get(key) ?? new Set()).add(failure.packageName));\n recordPackageFailure({ scope: key, stage: 'apply', ...failure });\n },\n hubToken: () => attachToken,\n requestSessionApi: (scope, request) => requestSessionApi(scope, request),\n unservedWorkspaceApi: (workspaceId, basePath) => unservedWorkspaceApi(workspaceId, basePath),\n ...(computerUse === undefined ? {} : { computerUse }),\n });\n // A contained server holds no credentials: its sessions call models through the host's gateway.\n const modelGateway: ModelGatewayContainer | undefined =\n sandboxIdentity === undefined ? undefined : createModelGatewayContainer({ hub });\n /** Assigned once the global builds can be read: a mirror's compositions come from the global composition. */\n let publishMirrorCompositions: (\n sessionId: string,\n ) => Pick<HeadlessHubSession, 'webComposition' | 'nativeComposition'> = () => ({});\n let hostModels: Promise<HostModelGateway | undefined> | undefined;\n if (sandboxIdentity === undefined)\n router = createSandboxRouter({\n hub,\n sandboxes,\n workspaces: () => workspaces.list(),\n announceWorkspace: (workspaceId) => refreshWorkspace(workspaceId),\n sessionCompositions: (sessionId) => publishMirrorCompositions(sessionId),\n forgetCompositions: (sessionId) => {\n webCompositions?.remove({ scope: 'session', sessionId });\n webCompositions?.removeNative({ scope: 'session', sessionId });\n },\n // The host's own models and credentials, created once the first container needs them.\n modelGateway: () =>\n (hostModels ??= createHostModelGateway(piAgentDirectory(baseEnvironment, homeDirectory), homeDirectory).catch(\n (error: unknown) => {\n notice(\n `The host models for sandboxes could not load: ${error instanceof Error ? error.message : String(error)}`,\n );\n hostModels = undefined;\n return undefined;\n },\n )),\n // Host sessions closed while the link was down, and leftovers of an interrupted switch, follow on each link.\n onLinked: (workspaceId) => {\n // A start, or a failure reported earlier, is over once the sandbox answers.\n const transition = sandboxTransitions.get(workspaceId)?.sandboxState;\n if (transition === 'starting' || transition === 'failed') sandboxTransitions.delete(workspaceId);\n refreshWorkspace(workspaceId);\n const provider = handoffProviderOf(workspaceId);\n const workspace = workspaces.list().find((entry) => entry.id === workspaceId);\n if (provider === undefined || workspace === undefined || handoff === undefined) return;\n void handoff\n .retry(workspace, provider)\n .catch((error: unknown) =>\n notice(`Workspace '${workspaceId}' handover retry failed: ${errorMessage(error)}`),\n );\n },\n onNotice: notice,\n });\n if (router !== undefined) {\n const linkedRouter = router;\n handoff = createSandboxSessionHandoff({\n host: { poHome: poHomeDirectory(homeDirectory, baseEnvironment), agentDir: path.dirname(serverDirectory) },\n openSessions,\n savedSessionIds: async (workspace) =>\n (\n await listSavedSessionRecords(\n platform.sessions,\n workspace.root,\n new Set(hub.snapshot().map((active) => active.id)),\n workspace.id,\n )\n ).map((saved) => saved.summary.id),\n // A session the hub let go of still runs until its host has closed.\n isLive: (sessionId) => hub.session(sessionId) !== undefined || baseSessionManager.get(sessionId) !== undefined,\n adopt: (workspaceId, record) => linkedRouter.adoptSession(workspaceId, record),\n onNotice: notice,\n });\n }\n /** Started by the idle restart once the server is serving; until then a restart waits. */\n let requestRestart: (() => void) | undefined;\n const idleRestart = createIdleRestart({\n ...testIdleRestartOverrides(baseEnvironment),\n busy: async () => {\n // A container session's turn is not visible here, and a host restart drops its mirror: count it as busy.\n if (recovering || (router?.mirrors().length ?? 0) > 0) return true;\n const hosts = sessionManager.sessions();\n // Running runners (open terminals) and subagents block like a turn: a restart kills them.\n const working = hosts.some((host) => {\n const root = sessionServiceRoots.get(host);\n const service = root === undefined ? undefined : readPoBackgroundWorkService(root);\n return service !== undefined && holdsRestart(service.snapshot());\n });\n if (working) return true;\n const states = await Promise.all(hosts.map((host) => host.runtime.readState()));\n return states.some((state) => state.isStreaming || state.isCompacting);\n },\n restart: () => requestRestart?.(),\n onError: (error) => notice(`Idle restart check failed: ${error instanceof Error ? error.message : String(error)}`),\n });\n // Any hub event may be the end of a turn, so it re-arms a pending restart's debounce.\n const stopIdleRestartPoke = hub.onEvent(() => idleRestart.poke());\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 const groups = event.session.groups ?? [];\n const sameGroups =\n groups.length === (record?.groups ?? []).length &&\n groups.every((group, index) => record?.groups?.[index] === group);\n if (record === undefined || (record.name === event.session.name && sameGroups)) return;\n openSessions.add({ ...record, name: event.session.name, groups });\n });\n let harnessContext: Awaited<ReturnType<typeof buildHarnessContext>> | undefined;\n let launchWorkspaceId: string | undefined;\n let cockpit: Awaited<ReturnType<typeof serveHeadlessServer>> | undefined;\n let attachToken: string | undefined;\n let webCompositions: ReturnType<typeof createWebCompositions> | undefined;\n const stopResourceMonitor = monitorRuntimeResources({\n record: (attributes) => telemetry.recordEvent('po_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 superseded_module_count: idleRestart.supersededCount(),\n idle_restart_pending_age_ms: idleRestart.pendingAgeMs(),\n };\n },\n warn: notice,\n });\n\n try {\n await telemetry.runInSpan('po_server.startup', {}, async () => {\n const token = getOrThrow(await hostFiles.readTextFile(options.tokenFile, BACKGROUND_CONTEXT)).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 = globalPoConfigDirectory(homeDirectory);\n const publicationDirectory = path.join(globalRoot, 'server');\n await reapAbandonedPublications(platform.env(baseCwd), publicationDirectory, processIsAlive).catch(\n (error: unknown) =>\n notice(`Abandoned publication cleanup failed: ${error instanceof Error ? error.message : String(error)}`),\n );\n webCompositions = createWebCompositions(publicationDirectory, notice, {\n pid: nodeHost.processId(),\n startedAt: Date.now(),\n });\n /** Assigned once every scope can be checked; a sync that exits sooner is picked up then. */\n let pickUpSync: (source?: ScopeCheckSource) => Promise<void> = async () => undefined;\n // Sync is the only producer of artifacts; this server starts it in the background and\n // reads what it prepared. PO_AUTO_SYNC=0 turns that off.\n const backgroundSync = createBackgroundSync({\n files: hostFiles,\n environment: baseEnvironment,\n onNotice: notice,\n onExit: () => pickUpSync(),\n // The host serves a contained workspace's web and native UI, so its sync builds only packages.\n ...(sandboxIdentity === undefined ? {} : { skipArtifactBuilds: true }),\n });\n const syncCheckpoints = createSyncCheckpoints({\n globalRoot,\n homeDirectory,\n environment: baseEnvironment,\n background: backgroundSync,\n onNotice: notice,\n });\n // A manual `po sync` moves the pointer without this server's background sync exiting, and\n // names each app bundle it exported from a source checkout in `app-<platform>.json`.\n watcher.add({\n path: path.dirname(syncPointerPath(globalRoot)),\n include: (file) => file === path.basename(syncPointerPath(globalRoot)) || /^app-[a-z]+\\.json$/u.test(file),\n });\n /** What the root opened without: packages that do not resolve yet and web plugins with no slot. */\n const unsyncedOf = async (root: string): Promise<{ selectors: string[]; webPackages: string[] }> => {\n try {\n const compositions = bundler.compositions(root);\n const webPackages =\n webBuild === undefined\n ? []\n : await unslottedWebPackages(webBuild, await compositionPackageRoots(compositions, hostFiles), hostFiles);\n return { selectors: unsyncedSelectors(compositions), webPackages };\n } catch (error) {\n notice(`'${root}' sync state could not be read: ${error instanceof Error ? error.message : String(error)}`);\n return { selectors: [], webPackages: [] };\n }\n };\n const workspaceLabel = (root: string, name?: string) => `Workspace '${name ?? path.basename(root)}'`;\n /** A checkpoint: request a background sync when the root changed since the last one, and warn. */\n const syncCheckpoint = async (root: string, label: string, request = true) => {\n const { selectors, webPackages } = await unsyncedOf(root);\n // A selected package that gained a web plugin leaves the selection unchanged, so the stale\n // check misses it; ask once per pointer state for the build that gives it a slot.\n if (request && webPackages.length > 0)\n await syncCheckpoints.requestMissing(\n `web-slot:${root}:${webPackages.join(',')}`,\n `${label} has web plugins without a slot: ${webPackages.join(', ')}`,\n );\n return syncCheckpoints.check({ root, label, unsynced: [...new Set([...selectors, ...webPackages])] }, request);\n };\n let webBuild: GlobalWebBuildRecord | undefined;\n /**\n * Publishes one mount out of the current global build, naming only the plugin slots its root\n * resolves. A session mount passes its major mode, so it names only that mode's slots.\n */\n const publishWebMount = (\n mount: ScopeMount | { scope: 'session'; sessionId: string },\n root: string,\n majorMode?: string,\n ) =>\n webBuild === undefined\n ? undefined\n : webCompositions?.publish(\n mount,\n webBuild,\n hub.channelTypes(),\n mountWebPluginSlots(webBuild, bundler.packageRoots(root, majorMode)),\n );\n let nativeBuild: GlobalNativeBuildRecord | undefined;\n /** Publishes one mount's native composition out of the current global native build. */\n const publishNativeMount = (\n mount: ScopeMount | { scope: 'session'; sessionId: string },\n root: string,\n majorMode?: string,\n ) =>\n nativeBuild === undefined\n ? undefined\n : webCompositions?.publishNative(\n mount,\n nativeBuild,\n hub.channelTypes(),\n mountNativePluginIds(nativeBuild, bundler.packageRoots(root, majorMode)),\n );\n /**\n * Republishes a global or workspace mount and reports whether its web or native composition\n * changed, so clients are told to swap only after a publish that succeeded and differs.\n */\n const publishSharedMount = (mount: ScopeMount, root: string): boolean => {\n const current = () => JSON.stringify([webCompositions?.get(mount), webCompositions?.getNative(mount)]);\n const before = current();\n publishNativeMount(mount, root);\n publishWebMount(mount, root);\n return current() !== before;\n };\n publishSessionCompositions = (sessionId, root, majorMode) => ({\n webComposition: publishWebMount({ scope: 'session', sessionId }, root, majorMode),\n nativeComposition: publishNativeMount({ scope: 'session', sessionId }, root, majorMode),\n });\n // A container session's checkout is never read on the host, so its plugins come from the global composition.\n publishMirrorCompositions = (sessionId) => ({\n webComposition: publishWebMount({ scope: 'session', sessionId }, globalRoot),\n nativeComposition: publishNativeMount({ scope: 'session', sessionId }, globalRoot),\n });\n const pickUpWebBuild = createKeyedPickup(\n (key) => readGlobalWebBuildRecord(globalRoot, key, hostFiles),\n (build, key) => {\n notice(`Publishing global web build ${key}.`);\n webBuild = build;\n webCompositions?.publishShell(build);\n hub.bumpRevision?.('global:web-bundle');\n },\n );\n const pickUpNativeBuild = createKeyedPickup(\n (key) => readGlobalNativeBuildRecord(globalRoot, key, hostFiles),\n (build, key) => {\n notice(`Publishing global native build ${key}.`);\n nativeBuild = build;\n },\n );\n /** The keys these roots derive the way sync does, each only when its build exists. */\n const ownBuildKeys = async (): Promise<{ webKey?: string; nativeKey?: string }> => {\n const pluginRoots = await globalWebPluginRoots(globalRoot, homeDirectory, baseEnvironment, notice);\n const web = await readGlobalWebBuildStatus({\n poHome: globalRoot,\n pluginRoots,\n environment: baseEnvironment,\n files: hostFiles,\n });\n const native = await readGlobalNativeBuildStatus({ poHome: globalRoot, pluginRoots, files: hostFiles });\n return {\n ...(web.status === 'current' ? { webKey: web.key } : {}),\n ...(native.status === 'current' ? { nativeKey: native.key } : {}),\n };\n };\n const currentBuildKeys = async () => {\n const pointer = await readSyncPointer(globalRoot);\n return syncedBuildKeys({\n pointer,\n ownsPointer: await syncCheckpoints.ownsPointer(pointer),\n published: { web: webBuild !== undefined, native: nativeBuild !== undefined },\n ownKeys: ownBuildKeys,\n newestWebKey: () => newestGlobalWebBuildKey(globalRoot, hostFiles),\n });\n };\n /**\n * Read-only: picks up the global web and native builds sync's pointer names, publishing\n * the shell only when a key changed, then republishes every shared mount. Never builds;\n * a missing build leaves the previous one serving. Clients pick a new composition up at\n * their next refreshWebPluginCompositions.\n */\n const refreshWebBuild = async (): Promise<void> => {\n const keys = await currentBuildKeys();\n if ((await pickUpNativeBuild(keys.nativeKey)) === 'missing')\n notice(`The global native build ${String(keys.nativeKey)} is missing; run po sync.`);\n if ((await pickUpWebBuild(keys.webKey)) === 'missing')\n notice(`The global web build ${String(keys.webKey)} is missing; run po sync.`);\n const mounts = hub\n .workspaces()\n .filter(servedOnHost)\n .map((workspace) => ({\n root: workspace.root,\n mount: { scope: 'workspace', workspaceId: workspace.id } as const,\n }));\n await Promise.all([globalRoot, ...mounts.map(({ root }) => root)].map((root) => bundler.packageEntries(root)));\n const changed = [{ root: globalRoot, mount: { scope: 'global' } as const }, ...mounts]\n .filter(({ root, mount }) => publishSharedMount(mount, root))\n .map(({ mount }) => mount);\n hub.touchCompositions?.(changed);\n for (const platform of NATIVE_APP_PLATFORMS) {\n const app = await readNativeAppBuild(globalRoot, platform, hostFiles);\n if (app !== undefined) webCompositions?.publishApp(platform, app);\n }\n };\n const loadComposition = async (\n root: string,\n scope: 'global' | 'workspace' | 'session',\n selection?: { root: string; majorMode: string; activeLayers: string[] },\n /** The `bundler` scope key a load failure is recorded under; sessions record none. */\n healthKey?: string,\n ) => {\n const selected = selection ?? bundler.defaultSelection(root);\n return telemetry.runInSpan('po_server.composition_load', { scope }, async () =>\n loadServerPackages(scope, {\n entries: await bundler.packageEntries(root),\n majorMode: selected.majorMode,\n activeLayers: selected.activeLayers,\n retainCandidates: scope === 'session',\n onNotice: notice,\n ...(healthKey === undefined\n ? {}\n : {\n onPackageFailed: (packageName: string, reason: string) =>\n recordPackageFailure({ scope: healthKey, packageName, stage: 'load', reason }),\n }),\n poisoned: bundler.poisoned,\n importer: bundler.importer,\n }),\n );\n };\n type ScopeMount = { scope: 'global' } | { scope: 'workspace'; workspaceId: string };\n const scopeKey = (mount: ScopeMount) => (mount.scope === 'global' ? 'global' : `workspace:${mount.workspaceId}`);\n const scopeChecks = new Map<string, Promise<unknown>>();\n /** Each package of a scope (`global`, `workspace:<id>`, `session:<id>`) whose current build failed. */\n const scopeFailures = (key: string) =>\n [...packageFailures.values()]\n .filter((record) => record.scope === key)\n .map(({ packageName, reason }) => ({ packageName, reason }));\n /**\n * The reload check for one served global or workspace scope: recompute its package URLs\n * and, only when they changed, load the new set and install it. Unchanged URLs come from\n * the module cache and the scope skips them, so only changed packages import and restart;\n * a package no longer selected stays installed. A scope this server has not served yet is\n * left to its admission. Checks of one scope run one at a time; a changed package whose\n * new build fails to apply gets its previous build back and is not committed, so the next\n * check applies it again. An import failure poisons its URL instead and waits for a rebuild,\n * which gets a new URL. Runs on a watched change, a finished sync and an upm change, never\n * on the session path.\n *\n * An `explicit` check (Help's reload) runs even when nothing looks changed, retries poisoned\n * imports, disposes installed packages the scope no longer declares, and rejects on failure.\n */\n const checkScope = (\n root: string,\n mount: ScopeMount,\n explicit = false,\n ): Promise<PoSelfImproveReloadResult | undefined> => {\n const key = scopeKey(mount);\n const run = (scopeChecks.get(key) ?? Promise.resolve()).then(async () => {\n // A sync that finished since the last check may name new builds without touching packages.\n try {\n await refreshWebBuild();\n } catch (error) {\n notice(`Web build check failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (explicit) {\n bundler.invalidate();\n bundler.poisoned.clear();\n }\n const change = await bundler.diffScope(key, root, mount.scope);\n if (\n change.first ||\n (!explicit && change.changed.length === 0 && change.reselected.length === 0 && change.removed.length === 0)\n )\n return undefined;\n const bundle = await loadComposition(root, mount.scope, undefined, key);\n failedPackages.delete(key);\n let installed = await hub.installPackages(mount, bundle.packages);\n const declared = new Set(\n bundle.entries.filter((entry) => entry.scopes.includes(mount.scope)).map((entry) => entry.packageName),\n );\n const removed = explicit ? installed.filter((name) => !declared.has(name)) : [];\n if (removed.length > 0) installed = await hub.uninstallPackages(mount, removed);\n const failed = takeFailedPackages(key, bundle.packages);\n bundler.commitScope(key, root, mount.scope, bundle.entries, failed);\n idleRestart.supersede(change.superseded);\n if (publishSharedMount(mount, root)) hub.touchCompositions?.([mount]);\n // A web plugin the build has no slot for yet mounts when the requested sync finishes.\n if (explicit)\n await syncCheckpoint(\n root,\n mount.scope === 'global'\n ? 'The global scope'\n : workspaceLabel(root, hub.workspaces().find(({ id }) => id === mount.workspaceId)?.name),\n );\n notice(\n `Reloaded ${mount.scope === 'global' ? 'global' : `workspace '${mount.workspaceId}'`} packages (${String(change.changed.length)} changed, ${String(change.removed.length)} no longer selected${removed.length === 0 ? '' : `, ${String(removed.length)} removed`}${failed.size === 0 ? '' : `, ${String(failed.size)} failed and retry at the next check`}).`,\n );\n return { installed, removed, failed: scopeFailures(key) };\n });\n const settled = run.catch((error: unknown) => {\n notice(\n `Extension check of ${key} failed and retries at the next check: ${error instanceof Error ? error.message : String(error)}`,\n );\n return undefined;\n });\n scopeChecks.set(key, settled);\n void settled.then(() => {\n if (scopeChecks.get(key) === settled) scopeChecks.delete(key);\n });\n return explicit ? run : settled;\n };\n const loadSessionMcp = async (\n root: string,\n selection: { majorMode: string; activeLayers: readonly string[] },\n ): Promise<LoadedMcpPlugins> => {\n return telemetry.runInSpan('po_server.mcp_bundle_load', {}, async () => {\n const { candidates, entries } = await bundler.mcpEntries(root);\n let app: Awaited<ReturnType<typeof readMcpAppBuild>>;\n try {\n app = await readMcpAppBuild({ poHome: globalRoot, candidates, files: hostFiles });\n } catch (error) {\n notice(`The MCP app build could not be read: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (app !== undefined && app.build === undefined) {\n notice(`MCP app build ${app.key} is not synced yet; this session runs without MCP widgets.`);\n await syncCheckpoints.requestMissing(`mcp-app:${app.key}`, 'the MCP app build is missing');\n }\n const built = app?.build;\n return loadMcpPlugins({\n entries,\n ...(built === undefined ? {} : { uiResource: mcpUiResource(built.html, built.sha256) }),\n majorMode: selection.majorMode,\n activeLayers: selection.activeLayers,\n retainCandidates: true,\n onNotice: notice,\n poisoned: bundler.poisoned,\n importer: bundler.importer,\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 // Listed for settings, sandboxed ones too, so a switched-on workspace can be switched off again. Host packages\n // still never resolve a sandboxed checkout to run anything in it (`resolveRepository` below).\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) =>\n hub.workspaces().find((workspace) => workspace.id === id && workspace.sandbox === undefined)?.root,\n // Read per call: the listener starts after the global scope is served.\n serverOrigin: () => {\n if (cockpit === undefined) throw new Error('The headless server is not listening yet.');\n return cockpit.url;\n },\n /**\n * Package readiness and the MCP projection, resolved live from the repository. The\n * context stays until the next read replaces it: the projection names its staged files.\n */\n readRepositorySync: async (id: string) => {\n const workspace = hub.workspaces().find((candidate) => candidate.id === id);\n if (workspace?.sandbox !== undefined)\n throw new Error('A sandboxed workspace is prepared inside its sandbox, not on the host.');\n const root = workspace?.root;\n if (!root) return undefined;\n const environment = rootEnvironment(root);\n const config = loadMajorModesConfig(root, homeDirectory, environment);\n const missing = missingLayerPackageSpecifiers(\n config,\n Object.keys(config.layers),\n createLayerResolvers(root, environment),\n );\n const context = await buildHarnessContext(\n await resolveHarnessOptions({ args: ['--cwd', root], cwd: root, environment }),\n );\n const previous = repositoryContexts.get(root);\n repositoryContexts.set(root, context);\n await previous?.cleanup().catch((error: unknown) => notice(String(error)));\n const status = await syncCheckpoint(\n root,\n workspaceLabel(root, hub.workspaces().find((workspace) => workspace.id === id)?.name),\n false,\n );\n return {\n fresh: missing.length === 0 && status.reasons.length === 0,\n reasons: [\n ...missing.map((specifier) => `configured package is not installed: ${specifier}`),\n ...status.reasons,\n ],\n syncing: status.syncing,\n mcpProjection: context.resources.mcpProjection,\n };\n },\n onNotice: notice,\n ...(computerUse?.permissions === undefined\n ? {}\n : {\n desktopPermissions: {\n authorize: (headers: Headers, change: boolean) =>\n computerUse.authorizePermissions?.(headers, change) === true,\n request: (permission?: string) => computerUse.permissions!(permission),\n },\n }),\n };\n /**\n * A sandboxed workspace's settings, answered on the host while it serves no scope for it, so the person can\n * still see and change them and switch the sandbox off. Reading and writing its `.po` YAML is data only: the host\n * never loads its composition, runs git or executes anything from it. Closed once it runs on the host again.\n */\n const sandboxedSettings = new Map<string, { root: string; handler: PoApiHandler; release: () => void }>();\n const releaseSandboxedSettings = (workspaceId: string): void => {\n sandboxedSettings.get(workspaceId)?.release();\n sandboxedSettings.delete(workspaceId);\n };\n unservedWorkspaceApi = (workspaceId, basePath) => {\n const record = workspaces.list().find((workspace) => workspace.id === workspaceId);\n const held = sandboxedSettings.get(workspaceId);\n if (held !== undefined && (record?.sandbox === undefined || held.root !== record.root))\n releaseSandboxedSettings(workspaceId);\n if (basePath !== SETTINGS_API || record?.sandbox === undefined) return undefined;\n const current = sandboxedSettings.get(workspaceId);\n if (current !== undefined) return current.handler;\n const env = platform.env(record.root);\n const handler = createSettingsApi(env).start({\n ...sharedApiContext,\n scope: 'workspace',\n workspaceId,\n workspaceRoot: record.root,\n cwd: record.root,\n resolveRepository: () => undefined,\n });\n sandboxedSettings.set(workspaceId, {\n root: record.root,\n handler,\n release: () => {\n handler.close();\n void env.cleanup(BACKGROUND_CONTEXT).catch((error: unknown) => notice(String(error)));\n },\n });\n return handler;\n };\n stopSandboxWatches.push(() => {\n for (const workspaceId of sandboxedSettings.keys()) releaseSandboxedSettings(workspaceId);\n });\n const globalDirectoryExisted = await pathExists(hostFiles, globalRoot, BACKGROUND_CONTEXT);\n getOrThrow(await hostFiles.createDir(globalRoot, { recursive: true }, BACKGROUND_CONTEXT));\n if (!globalDirectoryExisted) await nodeHost.setMode(globalRoot, 0o700);\n const globalBundle = await loadComposition(globalRoot, 'global', undefined, 'global');\n // A contained server has no remote access or native push: its host owns both.\n if (sandboxIdentity === undefined) {\n remoteRuntime = createRemoteRuntime({\n homeDirectory,\n registrationToken: token,\n onStateChanged: () => hub.bumpRevision?.('global:remote'),\n onTunnelIntentChanged: (intent) => {\n recoveryTunnel = intent;\n persistRecovery();\n },\n onDeviceDropped: (id) => computerUse?.revokeDevice?.(id),\n reservedPorts: () => [options.webPort],\n bundleTrust: () => webCompositions?.shellTrust(),\n attestHost: (fields) => webCompositions?.attestHost(fields),\n onNotice: notice,\n telemetry,\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-po-token', attachToken);\n return fetch(\n new URL(`${from.pathname}${from.search}`, cockpit.url),\n new Request(request, { headers, redirect: 'manual' }),\n );\n },\n acceptProtocol: (pathname, link, deviceId) => {\n if (!cockpit) throw new Error('The headless protocol listener is not ready.');\n return cockpit.acceptProtocol(pathname, link, {\n 'x-po-api-caller-locality': 'remote',\n 'x-po-api-caller-device-id': deviceId,\n 'x-po-api-caller-step-up': 'not-required',\n });\n },\n });\n const pushCredentials = await loadNativePushCredentials(baseEnvironment, platform.env(baseCwd), notice);\n const pushSender = createNativePushSender({\n ...pushCredentials,\n diagnostic: ({ provider, outcome, status, reason }) =>\n notice(\n `Native push ${provider}: ${outcome}${status === undefined ? '' : ` ${status}`}${reason ? ` ${reason}` : ''}.`,\n ),\n });\n stopNativePush = subscribeNativePush(hub, remoteRuntime.remote, pushSender, notice);\n }\n try {\n // The hub resets its global scope when serving fails, so any retry must bind the registry again.\n const globalScope = await hub.sessionParentScope(undefined);\n // Only the long-lived hub that owns the Po home runs sandboxes: a one-shot automation run binds no registry,\n // so no provider starts a container lifecycle or a clean-stop hook that would stop shared containers.\n if (automation === undefined) await globalScope.bind(PO_WORKSPACE_SANDBOXES_CONTRACT, sandboxes);\n if (sandboxIdentity !== undefined) await globalScope.bind(PO_SANDBOX_IDENTITY_CONTRACT, sandboxIdentity);\n await globalScope.bind(PO_PACKAGE_HEALTH_CONTRACT, { failures: () => [...packageFailures.values()] });\n // Who may reload which scope is Help's call; this only reloads it.\n await globalScope.bind(PO_SELF_IMPROVE_CONTRACT, {\n reload: async ({ scope, sessionId }) => {\n if (scope === 'session') {\n if (reloadSessionPackages === undefined) throw new Error('Session reload is not ready yet.');\n const result = await reloadSessionPackages(sessionId);\n return {\n ...result,\n failed: result.failed.map(({ packageName, reason }) => ({ packageName, reason })),\n };\n }\n const workspaceId = hub.session(sessionId)?.workspaceId;\n const workspace =\n workspaceId === undefined ? undefined : hub.workspaces().find(({ id }) => id === workspaceId);\n if (scope === 'workspace' && (workspace === undefined || !servedOnHost(workspace)))\n throw new Error(`Session '${sessionId}' has no workspace served on this host.`);\n const result = await checkScope(\n scope === 'global' ? globalRoot : workspace!.root,\n scope === 'global' ? { scope: 'global' } : { scope: 'workspace', workspaceId: workspace!.id },\n true,\n );\n return result ?? { installed: [], removed: [], failed: [] };\n },\n refresh: async ({ sessionId, axes }) => {\n if (refreshSessionSelection === undefined) throw new Error('Session refresh is not ready yet.');\n await refreshSessionSelection(sessionId, axes);\n },\n });\n await globalScope.bind(PO_REMOTE_ORIGIN_CONTRACT, {\n current: () => remoteRuntime?.remote.publicOrigin(),\n revision: () => remoteRuntime?.remote.publicOriginRevision() ?? 0,\n });\n failedPackages.delete('global');\n await hub.serveScope(\n {\n ...sharedApiContext,\n scope: 'global',\n requestReceipts: requestReceipts.receipts,\n ...(sandboxIdentity === undefined\n ? { remoteControl: { fetch: (request: Request) => remoteRuntime!.fetchLocal(request) } }\n : {}),\n },\n globalBundle.packages,\n );\n } finally {\n sandboxes.close();\n sandboxProvidersSettled = true;\n }\n // Each provider's own changes (its engine check, a container starting or failing) reach clients live.\n for (const provider of sandboxes.list())\n if (provider.onStatusChange !== undefined) stopSandboxWatches.push(provider.onStatusChange(refreshWorkspaces));\n bundler.commitScope(\n 'global',\n globalRoot,\n 'global',\n globalBundle.entries,\n takeFailedPackages('global', globalBundle.packages),\n );\n await refreshWebBuild();\n await syncCheckpoint(globalRoot, 'The global scope');\n // Server start covers app launch and Po updates: sync exits at once when nothing changed.\n if (!backgroundSync.syncing) await backgroundSync.request('server start');\n const admissions = new Map<string, Promise<HeadlessWorkspace & { available: boolean }>>();\n // A member checkout is any checkout other than its workspace root, such as a worktree.\n const isMemberCheckout = async (from: string, workspace: { root: string }): Promise<boolean> =>\n (await resolveWorkspaceRoot(from)) !== workspace.root;\n admitWorkspace = async (from, requestedName) => {\n const directory = await hostFiles.fileInfo(from, BACKGROUND_CONTEXT);\n if (!directory.ok || directory.value.kind !== 'directory') throw new Error(`Folder not found: ${from}`);\n const checkoutRoot = await resolveWorkspaceRoot(from);\n // A sandboxed workspace is registered and nothing else: the host never reads or writes its marker (it lives\n // behind the repository's `.git` pointer, which the sandbox controls), loads its composition, or serves its\n // scope. It is available only while the host is linked to its sandbox, which then runs its sessions. An\n // exact root match is settled before the marker is read.\n const admitSandboxed = (sandboxed: WorkspaceRecord): HeadlessWorkspace & { available: boolean } => {\n const requested = requestedName?.trim() || undefined;\n const record =\n requested === undefined || requested === sandboxed.name ? sandboxed : { ...sandboxed, name: requested };\n // The stored sandbox survives: `add` keeps it when the incoming record omits the key.\n if (record !== sandboxed)\n workspaces.add({\n id: record.id,\n root: record.root,\n ...(record.name === undefined ? {} : { name: record.name }),\n });\n const available = router?.connected(record.id) === true;\n const entry = { ...hubEntry(record, available), available };\n const known = hub.workspaces().find((workspace) => workspace.id === record.id);\n if (\n known === undefined ||\n (known.available !== false) !== available ||\n known.name !== entry.name ||\n known.sandbox !== entry.sandbox ||\n !sameSandboxStatus(known, entry)\n ) {\n if (known === undefined) notice(`Workspace '${record.id}' runs in sandbox '${String(record.sandbox)}'.`);\n hub.registerWorkspace(entry);\n }\n return entry;\n };\n const sandboxedHere = workspaces\n .list()\n .find((workspace) => workspace.sandbox !== undefined && workspace.root === checkoutRoot);\n if (sandboxedHere !== undefined) return admitSandboxed(sandboxedHere);\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 if (record?.sandbox !== undefined) return admitSandboxed(record);\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 await syncCheckpoint(root, workspaceLabel(root, name));\n if (renamed) {\n workspaces.add({ id, root, ...named });\n hub.registerWorkspace(hubEntry({ id, root, ...named }, 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(hubEntry({ id, root, ...named }, false));\n const admission = (async () => {\n // Admission only reads what sync prepared; a package it has not prepared yet is left\n // out with a warning and a background sync, and mounts when that sync finishes.\n const bundle = await loadComposition(root, 'workspace', undefined, `workspace:${id}`);\n failedPackages.delete(`workspace:${id}`);\n await hub.serveScope(\n {\n ...sharedApiContext,\n scope: 'workspace',\n workspaceId: id,\n workspaceRoot: root,\n cwd: root,\n resolveRepository: (requestedId) => (requestedId === id ? root : undefined),\n },\n bundle.packages,\n );\n servedWorkspaces.add(id);\n bundler.commitScope(\n `workspace:${id}`,\n root,\n 'workspace',\n bundle.entries,\n takeFailedPackages(`workspace:${id}`, bundle.packages),\n );\n // A missing web build leaves the workspace usable; the next checkpoint picks one up.\n try {\n await refreshWebBuild();\n const mount: ScopeMount = { scope: 'workspace', workspaceId: id };\n if (publishSharedMount(mount, root)) hub.touchCompositions?.([mount]);\n } catch (error) {\n notice(\n `Workspace '${id}' web build check failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n await syncCheckpoint(root, workspaceLabel(root, name));\n // Serving the scope registered it without its sandbox state.\n refreshWorkspace(id);\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.cwd;\n const root = await resolveWorkspaceRoot(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(hubEntry(workspace, false));\n try {\n // A sandboxed workspace is never resolved here; admission registers it unavailable.\n const root = workspace.sandbox === undefined ? await resolveWorkspaceRoot(workspace.root) : 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: LoadedServerPackages,\n mcpBundle: LoadedMcpPlugins,\n identity: {\n sessionId: string;\n sessionName: string;\n parentSessionId?: string;\n sessionProvenance?: string;\n interaction?: PoHubSessionCreateRequest['interaction'];\n },\n workspace: { id: string; root: string },\n explicit: {\n pinned: readonly PinnedSelectionAxis[];\n minorModes?: readonly string[];\n allowedTools?: readonly string[];\n initialFastMode?: boolean;\n initialAgentLocked?: boolean;\n resume?: boolean;\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 // Composed from this session's own root, environment and selection, never from the\n // process, and without the bootstrap: no PO_COMPOSED, no composition claim.\n const sessionEnvironment = context.environment;\n // The prompt-cache namespace keys on this, so publish it before the host reads the state.\n updateHarnessState(\n {\n compositionFingerprint: resolveExtensionComposition({\n majorMode: policyOptions.majorMode,\n layers: [...context.selectedLayers],\n majorModesConfig: loadMajorModesConfig(\n policyOptions.configRoot ?? policyOptions.repoRoot,\n homeDirectory,\n sessionEnvironment,\n ),\n resolvers: createLayerResolvers(policyOptions.configRoot ?? policyOptions.repoRoot, sessionEnvironment),\n tolerateUnsynced: true,\n }).fingerprint,\n },\n sessionEnvironment,\n );\n return {\n cwd: policyOptions.cwd,\n repoRoot: policyOptions.repoRoot,\n platform,\n sessionId: identity.sessionId,\n workspaceId: workspace.id,\n groupingRoot: workspace.root,\n sessionName: identity.sessionName,\n ...(explicit.initialFastMode === undefined ? {} : { initialFastMode: explicit.initialFastMode }),\n ...(explicit.initialAgentLocked === undefined ? {} : { initialAgentLocked: explicit.initialAgentLocked }),\n ...(explicit.resume ? { resume: true } : {}),\n ...(identity.parentSessionId === undefined ? {} : { parentSessionId: identity.parentSessionId }),\n ...(identity.sessionProvenance === undefined ? {} : { sessionProvenance: identity.sessionProvenance }),\n ...(identity.interaction === undefined ? {} : { interaction: identity.interaction }),\n agentArgs: policyOptions.piArgs,\n environment: Object.freeze({ ...context.environment }),\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: async () => {\n const environment = { ...baseEnvironment };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete environment[key];\n const defaults = await 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.entries,\n providerOverrides: () => selectedServerProviderOverrides(bundle.packages, sessionEnvironment, notice),\n mcpPlugins: mcpBundle.plugins,\n ...(modelGateway === undefined\n ? {}\n : { modelDependencies: (hostOptions) => modelGateway.modelDependencies(hostOptions) }),\n resolveSelection: (requested) => {\n const config = loadMajorModesConfig(\n policyOptions.configRoot ?? policyOptions.repoRoot,\n policyOptions.homeDirectory,\n policyOptions.environment ?? baseEnvironment,\n );\n return {\n ...requested,\n activeLayers: resolveLayers(config, requested.majorMode),\n };\n },\n telemetry,\n onNotice: notice,\n };\n };\n\n mountSessionApis = async (sessionOptions, host) =>\n serveSessionApis({\n // Workspace and global contracts reach the session's packages as native services.\n parentScope: await hub.sessionParentScope(sessionOptions.workspaceId),\n sessionId: sessionOptions.sessionId,\n platform,\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 // Read per call: shares follow the remote runtime's current tunnel.\n shareFile: (filePath, label) =>\n remoteRuntime === undefined\n ? Promise.reject(new Error(PO_SHARE_FILE_REMOTE_OFF_MESSAGE))\n : remoteRuntime.fileShares.mint({\n sessionId: sessionOptions.sessionId,\n cwd: sessionOptions.cwd,\n path: filePath,\n label,\n }),\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) =>\n computerUse.authorizeSession?.(sessionOptions.sessionId, headers) === true ||\n computerUse.authorize?.(headers) === true,\n authorizeRecording: (headers: Headers) =>\n computerUse.authorizeRecording?.(sessionOptions.sessionId, headers) === true,\n authorizeActivation: (headers: Headers) => computerUse.authorizeActivation?.(headers) === true,\n claim: (headers?: Headers) => computerUse.claimSession?.(sessionOptions.sessionId, headers),\n fetchRecording: (artifactId: string, range: string) =>\n computerUse.readRecording?.(\n { sessionId: sessionOptions.sessionId, cwd: sessionOptions.cwd },\n artifactId,\n range,\n ) ?? Promise.resolve(Response.json({ error: 'Not found.' }, { status: 404 })),\n subscribe: (listener: () => void) =>\n computerUse.subscribe?.(listener, sessionOptions.sessionId) ?? (() => undefined),\n },\n }),\n hubToken: token,\n sessionService: hub.sessionService,\n mediaArbitration,\n executionBudget,\n editPresence: hub.editPresence,\n peerAgents,\n pluginRegistry: hub.pluginRegistry,\n apis: [],\n packages: pendingSessions.get(sessionOptions.sessionId)?.bundle.packages ?? [],\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 preparePackages: (root) => {\n sessionServiceRoots.set(host, root);\n host.preparePackages(root);\n },\n activatePackages: host.activatePackages,\n canDispatch: host.canDispatch,\n telemetry,\n onNotice: notice,\n });\n\n requestSessionApi = async (scope, request) => {\n // A container session's panels call the container's own HTTP API, with its token.\n if (router?.mirror(scope.sessionId) !== undefined) return router.requestSessionApi(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://po.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 // An unclean boot restores recorded identities, never an extra random launch session.\n if (!options.noSession && recycled === undefined) {\n const initialOptions = await resolveHarnessOptions({\n args: resolved.agentArgs,\n cwd: baseCwd,\n environment: baseEnvironment,\n });\n const initialWorkspace = await admitWorkspace(initialOptions.repoRoot);\n launchWorkspaceId = initialWorkspace.id;\n // A sandboxed folder's launch session runs in its sandbox; nothing below may run on the host.\n if (initialWorkspace.sandbox !== undefined) {\n if (router === undefined) throw new Error(SANDBOX_UNREACHABLE);\n // The model, thinking level and selection the launch arguments ask for go with it.\n await router.openSession(initialWorkspace.id, {\n cwd: baseCwd,\n name: resolved.identity.sessionName,\n signal,\n ...launchSessionRequest(resolved.agentArgs, initialOptions),\n });\n } else {\n harnessContext = await buildHarnessContext(\n await resolveHarnessOptions({ args: resolved.agentArgs, cwd: baseCwd, environment: baseEnvironment }),\n harnessTelemetry,\n );\n const activeHarnessContext = harnessContext;\n try {\n const loadBundle = () =>\n loadComposition(activeHarnessContext.options.repoRoot, 'session', {\n root: activeHarnessContext.options.repoRoot,\n majorMode: activeHarnessContext.options.majorMode,\n activeLayers: activeHarnessContext.selectedLayers,\n });\n const initialBundle = await loadBundle();\n const initialMcpBundle = await loadSessionMcp(harnessContext.options.repoRoot, {\n majorMode: harnessContext.options.majorMode,\n activeLayers: harnessContext.selectedLayers,\n });\n pendingSessions.set(resolved.identity.sessionId, {\n cleanup: () => activeHarnessContext.cleanup(),\n bundle: initialBundle,\n mcpBundle: initialMcpBundle,\n loadBundle,\n });\n const created = await hub.create(\n sessionHostOptions(harnessContext, initialBundle, initialMcpBundle, resolved.identity, initialWorkspace),\n );\n recordLiveSession(created, harnessContext.options.repoRoot, initialWorkspace.root);\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\n const reservedOpens = new Map<string, Promise<PoHubSessionScope>>();\n /**\n * The sandboxed workspace this session would join, decided before any host preparation. The\n * inherited workspace (placement or parent link) wins; otherwise the checkout's own root is\n * matched without reading its marker, and only then the marker names an owner.\n */\n const sandboxedWorkspaceOf = async (\n request: PoHubSessionCreateRequest,\n groupingWorkspaceId?: string,\n ): Promise<string | undefined> => {\n const records = workspaces.list();\n const inherited =\n groupingWorkspaceId ??\n (request.parentSessionId\n ? (hub.session(request.parentSessionId)?.workspaceId ??\n [...openSessions.list(), ...(router?.dormant() ?? [])].find(\n (record) => record.sessionId === request.parentSessionId,\n )?.workspaceId)\n : undefined);\n const owner = inherited ?? (await checkoutWorkspaceId(records, request.cwd));\n return records.find((record) => record.id === owner && record.sandbox !== undefined)?.id;\n };\n openSession = async (request, sessionId, groupingWorkspaceId) => {\n request.signal?.throwIfAborted();\n const parent =\n request.parentSessionId === undefined\n ? undefined\n : (hub.session(request.parentSessionId) ??\n [...openSessions.list(), ...(router?.dormant() ?? [])].find(\n (record) => record.sessionId === request.parentSessionId,\n ));\n // A child cannot elevate an unattended parent, including across the sandbox boundary.\n if (parent?.interaction === 'unattended') request = { ...request, interaction: 'unattended' };\n // A sandboxed workspace's sessions run in its sandbox: the host prepares nothing and records nothing.\n const sandboxed = await sandboxedWorkspaceOf(request, groupingWorkspaceId);\n if (sandboxed !== undefined) {\n if (router === undefined) throw new Error(SANDBOX_UNREACHABLE);\n return router.openSession(sandboxed, request, sessionId);\n }\n if (\n request.workflowContext !== undefined &&\n (request.reservationId !== undefined ||\n sessionId !== undefined ||\n request.parentSessionId !== request.workflowContext.run.ownerSessionId ||\n request.sessionProvenance !== WORKFLOW_STEP_SESSION_PROVENANCE)\n ) {\n throw new Error('Workflow context requires a new, unreserved step session owned by its workflow session.');\n }\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 interaction: request.interaction,\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 explicit = sessionSelectionArgs(request);\n const openStartedAt = Date.now();\n const start = (async (): Promise<PoHubSessionScope> => {\n // Snapshot only for creation. Explicit-ID resumes retain their own durable Fast state.\n const parent =\n request.parentSessionId !== undefined && (sessionId === undefined || request.reservationId !== undefined)\n ? sessionManager.get(request.parentSessionId)\n : undefined;\n let initialFastMode: boolean | undefined;\n if (parent !== undefined) {\n const state = await parent.runtime.readState();\n if (typeof state.fastMode !== 'boolean') throw new Error('Parent Fast mode must be a boolean.');\n initialFastMode = state.fastMode;\n }\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 if (workspace.sandbox !== undefined) throw new Error(SANDBOX_UNREACHABLE);\n // Shared scopes reload on watched changes, never here. The session's own packages, MCP\n // plugins and Pi factories load below from the current URLs; running sessions keep\n // the set they were created with until restarted.\n await syncCheckpoint(globalRoot, 'The global scope');\n if (inheritedWorkspaceId !== undefined)\n // Without an inherited workspace, admitWorkspace above already ran this checkpoint.\n await syncCheckpoint(workspace.root, workspaceLabel(workspace.root, workspace.name));\n // A member checkout composes from its workspace's configuration.\n const member = await isMemberCheckout(request.cwd, workspace);\n const childContext = await buildHarnessContext(\n await 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 // A member checkout (a worktree) has no node_modules or builds of its own, so its\n // packages, local ones included, load from the workspace checkout that sync prepared.\n const compositionRoot = childContext.options.configRoot ?? childContext.options.repoRoot;\n const loadBundle = () =>\n loadComposition(compositionRoot, 'session', {\n root: compositionRoot,\n majorMode: childContext.options.majorMode,\n activeLayers: childContext.selectedLayers,\n });\n const bundle = await loadBundle();\n const mcpBundle = await loadSessionMcp(compositionRoot, {\n majorMode: childContext.options.majorMode,\n activeLayers: childContext.selectedLayers,\n });\n request.signal?.throwIfAborted();\n pendingSessions.set(identity.sessionId, {\n cleanup: () => childContext.cleanup(),\n bundle,\n mcpBundle,\n loadBundle,\n });\n const created = await hub.create({\n ...sessionHostOptions(childContext, bundle, mcpBundle, identity, workspace, {\n pinned: explicit.pinned,\n ...(initialFastMode === undefined ? {} : { initialFastMode }),\n ...(request.reservationId === undefined ? {} : { initialAgentLocked: true }),\n ...(sessionId !== undefined && request.reservationId === undefined ? { resume: true } : {}),\n ...(request.selection?.minorModes === undefined ? {} : { minorModes: request.selection.minorModes }),\n ...(request.tools === undefined ? {} : { allowedTools: request.tools }),\n }),\n ...(request.workflowContext === undefined ? {} : { workflowContext: request.workflowContext }),\n });\n request.signal?.throwIfAborted();\n recordLiveSession(created, childContext.options.repoRoot, workspace.root);\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 void start\n .then(\n () => 'success',\n () => 'failure',\n )\n .then((outcome) =>\n telemetry.recordEvent('po_server.session_open', { duration_ms: Date.now() - openStartedAt, outcome }),\n )\n .catch((error: unknown) => rawNotice(`session open telemetry failed: ${String(error)}`));\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 // A contained server's host creates and closes its sessions over the protocol socket.\n if (sandboxIdentity !== undefined)\n registerContainedSessionMethods(hub.pluginRegistry, {\n open: (request, sessionId) => openSession(request, sessionId),\n close: (sessionId, keepDormant) =>\n hub.closeSession(sessionId, keepDormant ? { keepDormant: true } : undefined),\n // A host session the host moved in here after closing it: listed dormant, like one closed here.\n adopt: async (record) => {\n if (record.workspaceId !== sandboxIdentity.workspaceId)\n throw new Error('The adopted session belongs to another workspace.');\n if (hub.session(record.sessionId) !== undefined) return;\n if (!openSessions.add(record)) throw new Error('The adopted session could not be durably recorded.');\n hub.notifyDormantChanged(record.sessionId);\n },\n });\n // The checkpoint for package installs and removals (upm add/remove), finished syncs and\n // watched changes: every root recomputes, and each scope re-imports only moved URLs.\n const checkAllScopes = (source: ScopeCheckSource = 'upm'): Promise<void> =>\n trackJob('scope_check', async () => {\n const started = performance.now();\n let roots = 1;\n bundler.invalidate();\n syncCheckpoints.invalidate();\n await checkScope(globalRoot, { scope: 'global' });\n for (const workspace of hub.workspaces())\n if (servedOnHost(workspace)) {\n roots += 1;\n await checkScope(workspace.root, { scope: 'workspace', workspaceId: workspace.id });\n }\n void telemetry\n .recordEvent('po_server.scope_check', {\n source,\n roots,\n duration_ms: Math.round(performance.now() - started),\n })\n .catch((error: unknown) => notice(`scope check telemetry failed: ${String(error)}`));\n });\n onExtensionCheck?.(() => checkAllScopes('upm'));\n /**\n * Reloads one session's own packages between tool rounds: changed and added packages install\n * with per-package rollback, removed ones are disposed, then the selection gates on the new set.\n * ponytail: provider overrides and MCP plugins keep the set the session opened with; reopen the\n * session to change those.\n */\n reloadSessionPackages = async (sessionId: string) => {\n const artifacts = sessionArtifacts.get(sessionId);\n const host = baseSessionManager.get(sessionId);\n const reconcile = artifacts?.apis.reconcile;\n if (artifacts === undefined || host?.reloadPackages === undefined || reconcile === undefined)\n throw new Error(`Session '${sessionId}' cannot reload its packages here.`);\n return host.runtime.runAtToolBoundary(async () => {\n bundler.invalidate();\n bundler.poisoned.clear();\n const bundle = await artifacts.loadBundle();\n const declared = bundle.entries\n .filter((entry) => entry.scopes.includes('session'))\n .map((entry) => entry.packageName);\n const result = await reconcile(bundle.packages, declared);\n artifacts.bundle = bundle;\n await host.reloadPackages?.(bundle.entries, result.installed);\n return result;\n });\n };\n refreshSessionSelection = async (sessionId, axes) => {\n const host = baseSessionManager.get(sessionId);\n if (host?.refreshSelection === undefined)\n throw new Error(`Session '${sessionId}' cannot refresh its selection here.`);\n await host.runtime.runAtToolBoundary(() => host.refreshSelection!(axes));\n };\n /**\n * A finished background sync goes through the same live reload: the read-only refresh\n * republishes a changed build, and each scope re-imports only packages whose URLs moved.\n * Session packages and the MCP app switch at the next session. The warnings are re-read\n * without requesting another sync, so a sync that could not fix a root never loops.\n */\n pickUpSync = async (source: ScopeCheckSource = 'sync') => {\n await checkAllScopes(source);\n await syncCheckpoint(globalRoot, 'The global scope', false);\n for (const workspace of hub.workspaces())\n if (servedOnHost(workspace))\n await syncCheckpoint(workspace.root, workspaceLabel(workspace.root, workspace.name), false);\n };\n pickUpChange = (source) => {\n void pickUpSync(source).catch((error: unknown) => notice(`Extension reload failed: ${String(error)}`));\n };\n });\n\n const workspaceResumes = new Map<string, Promise<string>>();\n // History is listed on every page view, so each unreadable file is reported once per server.\n const reportedUnreadable = new Set<string>();\n const unreadableHistory = (sessionId: string, error: unknown): void => {\n if (reportedUnreadable.has(sessionId)) return;\n reportedUnreadable.add(sessionId);\n notice(\n `Saved session ${sessionId} is hidden from History: ${error instanceof Error ? error.message : String(error)}`,\n );\n };\n const savedHistory = async (workspaceId: string) => {\n const root = hub.workspaces().find((workspace) => workspace.id === workspaceId && servedOnHost(workspace))?.root;\n if (!root) throw new Error('Workspace not found.');\n return listSavedSessionRecords(\n platform.sessions,\n root,\n new Set(hub.snapshot().map((active) => active.id)),\n workspaceId,\n unreadableHistory,\n );\n };\n const validateExecution = async (target: SavedSessionExecution, workspaceId: string): Promise<void> => {\n const root = hub.workspaces().find((workspace) => workspace.id === workspaceId && servedOnHost(workspace))?.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 ((await resolveWorkspaceRoot(target.cwd)) !== target.repoRoot)\n throw new Error('Saved session checkout is unavailable.');\n };\n const reviving = new Map<string, Promise<void>>();\n const reviveRecord = (record: OpenSessionRecord): Promise<void> => {\n // A container session wakes in its container; its mirror appears once it runs.\n if (router?.owns(record.sessionId) === true) return router.revive(record.sessionId);\n const pending = reviving.get(record.sessionId);\n if (pending) return pending;\n if (sessionManager.get(record.sessionId)) return Promise.resolve();\n // A record taken back from a sandbox whose folder was a container worktree.\n const opening = (async () => {\n if (!(await pathExists(hostFiles, record.cwd, BACKGROUND_CONTEXT))) throw new Error(CONTAINER_WORKTREE_GONE);\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 && (await resolveWorkspaceRoot(record.cwd)) !== record.repoRoot)\n throw new Error('The session checkout has changed.');\n await openSession(\n {\n cwd: record.cwd,\n signal,\n name: record.name,\n ...(record.parentSessionId === undefined ? {} : { parentSessionId: record.parentSessionId }),\n ...(record.sessionProvenance === undefined ? {} : { sessionProvenance: record.sessionProvenance }),\n ...(record.interaction === undefined ? {} : { interaction: record.interaction }),\n },\n record.sessionId,\n record.workspaceId,\n );\n // Groups edited while dormant live only on the record; the journal adopts them now.\n const groups = record.groups ?? [];\n const opened = hub.session(record.sessionId)?.groups ?? [];\n if (groups.length !== opened.length || groups.some((group, index) => opened[index] !== group))\n await hub.runtime(record.sessionId)?.setGroups(groups);\n })();\n reviving.set(record.sessionId, opening);\n void opening.finally(() => reviving.delete(record.sessionId)).catch(() => undefined);\n return opening;\n };\n /** Host records, then the dormant sessions each linked container lists. */\n const allDormant = (): readonly OpenSessionRecord[] => [...openSessions.list(), ...(router?.dormant() ?? [])];\n dormantSessions = allDormant;\n reviveSession = (sessionId) => {\n const record = allDormant().find((item) => item.sessionId === sessionId);\n return record ? reviveRecord(record) : Promise.reject(new Error('The session has no saved record.'));\n };\n cockpit = await serveHeadlessServer({\n port: options.webPort,\n ...(options.host === undefined ? {} : { host: options.host }),\n // A contained server answers only its host, which holds the token.\n ...(sandboxIdentity === undefined\n ? {}\n : { publicRoutes: false, webSocketMaxPayload: CONTAINED_MAX_PAYLOAD_BYTES }),\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 setWorkspaceSandbox: async (workspaceId, sandbox) => {\n const record = workspaces.list().find((workspace) => workspace.id === workspaceId);\n if (record === undefined) return { error: 'Workspace not found.' };\n if (sandbox !== null && sandboxes.get(sandbox) === undefined)\n return { error: `Sandbox provider '${sandbox}' is not registered.` };\n // Refuse before any session moves: a sandbox that cannot start would strand them until it comes back.\n const blocked =\n sandbox === null || sandbox === record.sandbox ? undefined : sandboxes.get(sandbox)?.availability?.();\n if (blocked !== undefined && !blocked.available) return { error: blocked.reason };\n const previous = record.sandbox;\n const switchingOff = previous !== undefined && previous !== (sandbox ?? undefined);\n const switchingOn = sandbox !== null && sandbox !== previous;\n const offProvider = switchingOff ? handoffProvider(sandboxes.get(previous)) : undefined;\n const onProvider = switchingOn ? handoffProvider(sandboxes.get(sandbox)) : undefined;\n const failed = (error: unknown): void => {\n sandboxTransitions.set(workspaceId, { sandboxState: 'failed', sandboxReason: errorMessage(error) });\n refreshWorkspace(workspaceId);\n };\n // Sessions follow the workspace out: the host lets go of its mirrors, the sandbox stops, and only then do its\n // sessions move back to the host.\n if (offProvider !== undefined && handoff !== undefined) {\n sandboxTransitions.set(workspaceId, { sandboxState: 'stopping' });\n refreshWorkspace(workspaceId);\n try {\n await router?.release(workspaceId);\n for (const sessionId of await handoff.switchOff(record, offProvider)) hub.notifyDormantChanged(sessionId);\n } catch (error) {\n failed(error);\n // Linked again if its sandbox still runs.\n router?.start();\n return { error: `The workspace's sessions could not leave its sandbox: ${errorMessage(error)}` };\n }\n }\n sandboxTransitions.delete(workspaceId);\n // Recorded before the handover, so no new session of the workspace starts on the host meanwhile.\n workspaces.setSandbox(workspaceId, sandbox ?? undefined);\n const updated = workspaces.list().find((workspace) => workspace.id === workspaceId) ?? record;\n // A sandboxed workspace is unavailable on the host until its sandbox links. A cleared one is admitted again\n // as a local workspace.\n if (updated.sandbox !== undefined) {\n if (onProvider !== undefined && handoff !== undefined)\n sandboxTransitions.set(workspaceId, { sandboxState: 'starting' });\n const entry = hubEntry(updated, router?.connected(workspaceId) === true);\n hub.registerWorkspace(entry);\n if (onProvider !== undefined && handoff !== undefined) {\n // Saved host sessions and their records move into the sandbox, then it starts. Live host sessions follow\n // as they close; the host scope stays for them, without reloads.\n try {\n for (const sessionId of await handoff.switchOn(updated, onProvider)) hub.notifySessionRemoved(sessionId);\n } catch (error) {\n failed(error);\n return { error: `The workspace's sandbox did not start: ${errorMessage(error)}` };\n }\n // Starting until the host links to it, then running.\n router?.start();\n }\n return { workspace: hub.workspaces().find((workspace) => workspace.id === workspaceId) ?? entry };\n }\n if (servedWorkspaces.has(workspaceId)) {\n const entry = hubEntry(updated, true);\n hub.registerWorkspace(entry);\n return { workspace: entry };\n }\n // Registered unavailable first, so admission serves the scope instead of answering the sandboxed entry.\n hub.registerWorkspace(hubEntry(updated, false));\n const admitted = await admitWorkspace(updated.root);\n return { workspace: hub.workspaces().find((workspace) => workspace.id === workspaceId) ?? admitted };\n },\n workspaceHistory: async (workspaceId) =>\n router?.contains(workspaceId) === true\n ? ((await router.history(workspaceId)) as Awaited<ReturnType<typeof savedHistory>>[number]['summary'][])\n : (await savedHistory(workspaceId)).map((record) => record.summary),\n resumeWorkspaceSession: async (workspaceId, targetSessionId) => {\n if (router?.contains(workspaceId) === true) return router.resumeWorkspace(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)\n throw new Error('Saved Pi 1.0 session not found in this workspace. Earlier sessions cannot be resumed.');\n if (!(await pathExists(hostFiles, target.execution.cwd, BACKGROUND_CONTEXT)))\n throw new Error(CONTAINER_WORKTREE_GONE);\n await validateExecution(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 ...(target.execution.interaction === undefined ? {} : { interaction: target.execution.interaction }),\n },\n target.summary.id,\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 // A container session's history lives in its container.\n if (router?.mirror(session.id) !== undefined)\n return router.sessionHistory(session.id) as ReturnType<typeof listSavedSessions>;\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 platform.sessions,\n workspaceRoot,\n new Set(hub.snapshot().map((active) => active.id)),\n session.workspaceId,\n unreadableHistory,\n );\n },\n readDormantTranscript: async (record, request, context) => {\n // A dormant container session's transcript is read in its container.\n if (router?.owns(record.sessionId) === true) return router.readTranscript(record.sessionId, request);\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 = await resolveWorkspaceRoot(record.cwd);\n if (record.repoRoot !== undefined && record.repoRoot !== owner)\n throw new Error('Saved transcript checkout has changed.');\n return readSqliteTranscript(platform.sessions, record.sessionId, request, context, {\n sessionId: record.sessionId,\n workspaceRoot: owner,\n workspaceId: record.workspaceId,\n groupingRoot: workspaceRoot,\n });\n },\n restartSession: async (session) => {\n if (router?.mirror(session.id) !== undefined) {\n await router.restart(session.id);\n return;\n }\n const record = openSessions.list().find((entry) => entry.sessionId === session.id);\n const workspaceRoot = hub\n .workspaces()\n .find((workspace) => workspace.id === session.workspaceId && workspace.available !== false)?.root;\n if (!workspaceRoot) throw new Error('Session workspace not found.');\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 ...(session.interaction === undefined ? {} : { interaction: session.interaction }),\n },\n session.id,\n 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 if (router?.mirror(session.id) !== undefined) return router.resume(session.id, 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)\n throw new Error('Saved Pi 1.0 session not found in this workspace. Earlier sessions cannot be resumed.');\n await validateExecution(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 ...(target.execution.interaction === undefined ? {} : { interaction: target.execution.interaction }),\n },\n target.summary.id,\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: allDormant,\n removeDormantSession: (record: OpenSessionRecord) => removeSessionOutputs(record.sessionId),\n removeSessionFiles: removeSessionOutputs,\n setDormantGroups: async (record: OpenSessionRecord, groups: readonly string[]) => {\n if (router?.owns(record.sessionId) === true) return router.setDormantGroups(record.sessionId, groups);\n if (!openSessions.add({ ...record, groups: [...groups] }))\n throw new Error('The session groups could not be durably recorded.');\n },\n reviveSession: reviveRecord,\n requestAsset: (request) => webCompositions?.request(request) ?? Promise.resolve(undefined),\n compositions: () => {\n // A sandboxed workspace has no host composition, and its folder is never read here.\n const workspaces = hub.workspaces().filter((workspace) => workspace.sandbox === undefined);\n const decision = {\n cwd: baseCwd,\n launchWorkspaceId,\n workspaces,\n homeDirectory,\n environment: baseEnvironment,\n notice,\n };\n return {\n global: webCompositions?.get({ scope: 'global' }),\n nativeGlobal: webCompositions?.getNative({ scope: 'global' }),\n nativeApp: webCompositions?.apps(),\n publicKey: webCompositions?.publicKey(),\n shell: webCompositions?.shellTrust(),\n template: resolveWebTemplateDecision(decision),\n nativeTemplate: resolveWebTemplateDecision({ ...decision, host: 'native' }),\n workspaces: hub.workspaces().map((workspace) =>\n workspace.sandbox === undefined\n ? {\n ...workspace,\n webComposition: webCompositions?.get({ scope: 'workspace', workspaceId: workspace.id }),\n nativeComposition: webCompositions?.getNative({ scope: 'workspace', workspaceId: workspace.id }),\n }\n : // Listed with no host plugins, so its sessions (mirrors with global compositions) still mount.\n { ...workspace, webComposition: null, nativeComposition: null },\n ),\n };\n },\n telemetry,\n onNotice: notice,\n });\n notice(`protocol on ${cockpit.url}/api/ws`);\n // Containers that run or were taken back show their sessions, live and dormant, through mirrors.\n router?.start();\n let resolveShutdown!: (exitCode: number) => void;\n const shutdown = new Promise<number>((resolve) => {\n resolveShutdown = resolve;\n });\n requestRestart = () => {\n // Only sessions live right now reopen; dormant ones stay dormant.\n const ids = openSessions\n .list()\n .map((record) => record.sessionId)\n .filter((id) => sessionManager.get(id) !== undefined);\n persistRecovery = () => {};\n const details = {\n crashRestores: restorePlan.crashRestores,\n ...(recoveryTunnel === undefined ? {} : { tunnel: recoveryTunnel }),\n };\n recoveryWrites = recoveryWrites.then(async () => {\n try {\n await writeRecycleFile(serverDirectory, ids, details);\n } catch (error) {\n notice(`Could not write the recycle file: ${error instanceof Error ? error.message : String(error)}`);\n }\n notice(`Restarting at idle to release superseded extension versions (${String(ids.length)} sessions reopen).`);\n resolveShutdown(RESTART_EXIT_CODE);\n });\n };\n persistRecovery();\n if (restorePlan.blocked)\n notice(\n 'Automatic crash restore paused after two attempts in 15 minutes. Sessions remain dormant; use Wake to retry.',\n );\n const stop = (): void => {\n cleanShutdown = signal.reason !== 'crash';\n resolveShutdown(0);\n };\n signal.addEventListener('abort', stop, { once: true });\n if (signal.aborted) stop();\n // Serial recovery starts only after listen. Wake joins the same per-session promise.\n recovering = true;\n const restoredSessions = reopenRecycledSessions(\n serverDirectory,\n async (sessionId) => {\n if (signal.aborted || shuttingDown) return;\n const record = openSessions.list().find((entry) => entry.sessionId === sessionId);\n try {\n if (record === undefined) throw new Error('its record is gone.');\n await reviveRecord(record);\n } catch (error) {\n recoverySessionIds.delete(sessionId);\n throw error;\n } finally {\n persistRecovery();\n }\n },\n (sessionId, error) =>\n notice(\n `Session '${sessionId}' did not reopen after the restart: ${error instanceof Error ? error.message : String(error)}`,\n ),\n { sessionIds: restorePlan.sessionIds, removeAfter: false },\n ).catch((error: unknown) => notice(`Crash restore failed: ${String(error)}`));\n let restoredTunnel: Promise<unknown> | undefined;\n if (tunnelToRestore !== undefined && !signal.aborted) {\n restoredTunnel = remoteRuntime\n ?.restoreTunnel(tunnelToRestore)\n .then((result) => {\n if (!result.ok) notice(`Remote access did not restore: ${result.error}`);\n })\n .catch((error: unknown) => notice(`Remote access did not restore: ${String(error)}`))\n .finally(() => {\n recoveryTunnel = remoteRuntime?.tunnelIntent();\n persistRecovery();\n });\n }\n recoveryWork = Promise.allSettled([restoredSessions, restoredTunnel]).then(() => {\n recovering = false;\n idleRestart.poke();\n });\n if (automation !== undefined && !signal.aborted) {\n void automation({\n hub,\n sessionHost: (sessionId) => sessionManager.get(sessionId),\n openSession: (request) => openSession(request),\n closeSession: (sessionId) => closeManagedSession(sessionId),\n signal,\n })\n .then((exitCode) => resolveShutdown(exitCode))\n .catch((error: unknown) => {\n notice(`Native automation failed: ${error instanceof Error ? error.message : String(error)}`);\n resolveShutdown(1);\n });\n }\n try {\n const exitCode = await shutdown;\n if (exitCode === 0 && signal.reason !== 'crash') cleanShutdown = true;\n return exitCode;\n } finally {\n signal.removeEventListener('abort', stop);\n }\n } finally {\n shuttingDown = true;\n persistRecovery = () => {};\n await recoveryWrites;\n const cleanUserStop = isCleanUserStop(cleanShutdown, signal);\n // Started first so container stops overlap the rest of shutdown, and awaited before the global scope unloads.\n const sandboxesStopped =\n cleanUserStop && automation === undefined\n ? withShutdownDeadline(\n () => stopSandboxProviders(sandboxes.list(), notice),\n 'sandbox stop',\n SANDBOX_STOP_DEADLINE_MS,\n ).catch((error: unknown) =>\n notice(`sandbox stop failed: ${error instanceof Error ? error.message : String(error)}`),\n )\n : Promise.resolve();\n if (cleanUserStop) {\n try {\n await recoveryWrites;\n await removeRecycleFile(serverDirectory);\n // Stopping the server is not switching remote access off: a named tunnel comes back next start.\n await keepTunnelIntent(serverDirectory, recoveryTunnel);\n } catch (error) {\n notice(`Could not remove crash recovery state: ${String(error)}`);\n }\n }\n idleRestart.dispose();\n stopIdleRestartPoke();\n stopResourceMonitor();\n executionBudget.close();\n watcher.close();\n stopPersistSessionNames();\n stopNativePush?.();\n for (const stop of stopSandboxWatches.splice(0)) stop();\n modelGateway?.dispose();\n clearInterval(eventLoopMonitor);\n await bounded(telemetry.recordEvent('po_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 await bounded(\n withShutdownDeadline(() => recoveryWork, 'crash recovery shutdown'),\n 'crash recovery shutdown',\n notice,\n );\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(router?.dispose() ?? Promise.resolve(), 'sandbox router shutdown', notice);\n await sandboxesStopped;\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 Promise.allSettled(\n [...repositoryContexts.values()].map((context) =>\n bounded(context.cleanup(), 'repository context cleanup', notice),\n ),\n );\n repositoryContexts.clear();\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4JA,MAAM,8BAA8B;;AAEpC,MAAM,eAAe;;AAErB,MAAM,wBAAwB;;AAG9B,SAAS,eAAe,MAAuB;CAC7C,MAAM,UAAU,KAAK,WAAW,GAAG,KAAK,KAAK,SAAS,GAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;CACjF,IAAI,QAAQ,YAAY,MAAM,aAAa,OAAO;CAClD,IAAIA,SAAAA,QAAI,OAAO,OAAO,GAAG,OAAO,QAAQ,WAAW,MAAM;CACzD,IAAI,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GAAG,8BAA8B,MAAM,CACjE,CACF;EACA,mBAAmB,MAAM;EACzB,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.cjs","names":["net","path","withShutdownDeadline","createServerExecutionBudget","ensureGlobalLogSink","createServerTelemetry","os","piAgentDirectory","createNodePlatform","createNodeIsolate","createNodeNpm","poHomeDirectory","createWatcherService","BACKGROUND_CONTEXT","globalPoConfigDirectory","createBundlerService","poPackageRoot","outsideNodeModules","createRequestReceipts","createWorkspaceRegistry","resolveWorkspaceRoot","createWorkspaceSandboxRegistry","createOpenSessionRegistry","readRecycleState","prepareSessionRestore","takeTunnelIntent","createHarnessTelemetry","createHeadlessSessionManager","publishHeadlessSelectionStatus","readMinorModeCatalog","HARNESS_STATE_POINTER","HARNESS_STATE_KEYS","writeRecycleFile","readSessionFileDirectories","removeSessionFiles","handoffProvider","createComputerUseBinding","createPoNotificationEntryData","PO_NOTIFICATION_ENTRY_TYPE","createHeadlessHub","resolveProfile","createDefaultWorkspaceFolder","checkoutWorkspaceId","createModelGatewayContainer","createSandboxRouter","createHostModelGateway","createSandboxSessionHandoff","listSavedSessionRecords","createIdleRestart","testIdleRestartOverrides","readPoBackgroundWorkService","holdsRestart","monitorRuntimeResources","getOrThrow","resolveSessionIdentity","crypto","reapAbandonedPublications","processIsAlive","createWebCompositions","nodeHost","createBackgroundSync","createSyncCheckpoints","syncPointerPath","unslottedWebPackages","compositionPackageRoots","unsyncedSelectors","mountWebPluginSlots","mountNativePluginIds","createKeyedPickup","readGlobalWebBuildRecord","readGlobalNativeBuildRecord","globalWebPluginRoots","readGlobalWebBuildStatus","readGlobalNativeBuildStatus","readSyncPointer","syncedBuildKeys","newestGlobalWebBuildKey","NATIVE_APP_PLATFORMS","readNativeAppBuild","loadServerPackages","readMcpAppBuild","loadMcpPlugins","mcpUiResource","loadMajorModesConfig","missingLayerPackageSpecifiers","createLayerResolvers","buildHarnessContext","createSettingsApi","pathExists","createRemoteRuntime","loadNativePushCredentials","createNativePushSender","subscribeNativePush","PO_WORKSPACE_SANDBOXES_CONTRACT","PO_SANDBOX_IDENTITY_CONTRACT","PO_PACKAGE_HEALTH_CONTRACT","PO_SELF_IMPROVE_CONTRACT","PO_REMOTE_ORIGIN_CONTRACT","identifyWorkspace","readWorkspaceMarker","resolveExtensionComposition","selectedServerProviderOverrides","resolveLayers","serveSessionApis","PO_SHARE_FILE_REMOTE_OFF_MESSAGE","SANDBOX_UNREACHABLE","launchSessionRequest","WORKFLOW_STEP_SESSION_PROVENANCE","sessionSelectionArgs","CONTAINER_WORKTREE_GONE","serveHeadlessServer","listSavedSessions","readSqliteTranscript","resolveWebTemplateDecision","reopenRecycledSessions","isCleanUserStop","stopSandboxProviders","SANDBOX_STOP_DEADLINE_MS","removeRecycleFile","keepTunnelIntent"],"sources":["../../../../src/builders/server/runtime.ts"],"sourcesContent":["import crypto from 'node:crypto';\nimport net from 'node:net';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { createSettingsApi } from '@agimon-ai/po-config';\nimport { globalPoConfigDirectory } from '@agimon-ai/po-config/config';\nimport { loadMajorModesConfig, resolveLayers } from '@agimon-ai/po-config/majorModes';\nimport { resolveProfile } from '@agimon-ai/po-config/profiles';\nimport { readPoBackgroundWorkService } from '@agimon-ai/po-core/backgroundWork';\nimport type { PoHeadlessRefreshAxis } from '@agimon-ai/po-core/headless';\nimport {\n createHeadlessHub,\n type HeadlessHub,\n type HeadlessHubOptions,\n type HeadlessHubSession,\n type HeadlessWorkspace,\n} from '@agimon-ai/po-core/headlessHub';\nimport { serveHeadlessServer } from '@agimon-ai/po-core/headlessServer';\nimport type { HeadlessSessionHost, HeadlessSessionHostOptions } from '@agimon-ai/po-core/headlessSessionHost';\nimport { createHeadlessSessionManager } from '@agimon-ai/po-core/headlessSessionManager';\nimport {\n PO_PACKAGE_HEALTH_CONTRACT,\n PO_SELF_IMPROVE_CONTRACT,\n type PoPackageFailureRecord,\n type PoSelfImproveReloadResult,\n} from '@agimon-ai/po-core/help';\nimport {\n createOpenSessionRegistry,\n createRequestReceipts,\n createWorkspaceRegistry,\n identifyWorkspace,\n listSavedSessionRecords,\n listSavedSessions,\n readSqliteTranscript,\n readWorkspaceMarker,\n writeWorkspaceMarker,\n} from '@agimon-ai/po-core/history';\nimport type { OpenSessionRecord, SavedSessionExecution, WorkspaceRecord } from '@agimon-ai/po-core/history';\nimport { WORKFLOW_STEP_SESSION_PROVENANCE } from '@agimon-ai/po-core/hubChannel';\nimport type {\n PoHubSessionApiRequest,\n PoHubSessionCreateRequest,\n PoHubSessionScope,\n} from '@agimon-ai/po-core/hubChannel';\nimport { loadMcpPlugins, mcpUiResource, type LoadedMcpPlugins } from '@agimon-ai/po-core/mcpFacet';\nimport { createModelGatewayContainer, type ModelGatewayContainer } from '@agimon-ai/po-core/modelGateway';\nimport { createNodePlatform } from '@agimon-ai/po-core/nodePlatform';\nimport { createPoNotificationEntryData, PO_NOTIFICATION_ENTRY_TYPE } from '@agimon-ai/po-core/notification';\nimport { createServerExecutionBudget, PO_SHARE_FILE_REMOTE_OFF_MESSAGE } from '@agimon-ai/po-core/packageApi';\nimport type { PoApiHandler, PoHostMediaArbitration, PoPeerAgentRegistry } from '@agimon-ai/po-core/packageApi';\nimport {\n serveSessionApis,\n type PackageApiServer,\n type PackageReconcileResult,\n} from '@agimon-ai/po-core/packageApiServer';\nimport { piAgentDirectory, poHomeDirectory } from '@agimon-ai/po-core/piSettings';\nimport {\n BACKGROUND_CONTEXT,\n getOrThrow,\n pathExists,\n nodeHost,\n readSessionFileDirectories,\n removeSessionFiles,\n} from '@agimon-ai/po-core/platform';\nimport { createRemoteRuntime, PO_REMOTE_ORIGIN_CONTRACT, type RemoteRuntime } from '@agimon-ai/po-core/remoteRuntime';\nimport type {\n HeadlessSessionCloseOptions,\n HeadlessSessionManager,\n} from '@agimon-ai/po-core/runtimeHeadlessSessionManager';\nimport { createHarnessTelemetry } from '@agimon-ai/po-core/runtimeLogSinkTelemetry';\nimport { PO_SANDBOX_IDENTITY_CONTRACT, type PoSandboxIdentity } from '@agimon-ai/po-core/sandboxIdentity';\nimport {\n loadServerPackages,\n selectedServerProviderOverrides,\n type LoadedServerPackages,\n} from '@agimon-ai/po-core/serverPlugin';\nimport { createServerTelemetry } from '@agimon-ai/po-core/serverTelemetry';\nimport { createWebCompositions, reapAbandonedPublications } from '@agimon-ai/po-core/webCompositions';\nimport { createWorkspaceSandboxRegistry, PO_WORKSPACE_SANDBOXES_CONTRACT } from '@agimon-ai/po-core/workspaceSandboxes';\nimport { readMinorModeCatalog } from '@agimon-ai/po-minor-mode';\nimport { createNativePushSender } from '@agimon-ai/po-notification';\n\nimport { HARNESS_STATE_KEYS, HARNESS_STATE_POINTER, updateHarnessState } from '../../composition/harnessState';\nimport { missingLayerPackageSpecifiers } from '../../composition/layerPackageInstaller';\nimport { resolveWorkspaceRoot } from '../../composition/repository';\nimport { globalWebPluginRoots, processIsAlive, readSyncPointer, syncPointerPath } from '../../composition/syncService';\nimport { poPackageRoot } from '../cli/entryResolution';\nimport { createLayerResolvers, resolveExtensionComposition, unsyncedSelectors } from '../cli/extensionAssembler';\nimport { buildHarnessContext } from '../cli/harnessContext';\nimport { createNodeIsolate } from '../isolate';\nimport {\n type GlobalNativeBuildRecord,\n mountNativePluginIds,\n NATIVE_APP_PLATFORMS,\n readGlobalNativeBuildRecord,\n readGlobalNativeBuildStatus,\n readNativeAppBuild,\n} from '../native';\nimport { createNodeNpm } from '../npm';\nimport {\n compositionPackageRoots,\n type GlobalWebBuildRecord,\n mountWebPluginSlots,\n newestGlobalWebBuildKey,\n readGlobalWebBuildRecord,\n readGlobalWebBuildStatus,\n unslottedWebPackages,\n} from '../web';\nimport { createBackgroundSync, createKeyedPickup, createSyncCheckpoints, syncedBuildKeys } from './backgroundSync';\nimport { createBundlerService } from './bundlerService';\nimport { createComputerUseBinding } from './computerUseBinding';\nimport { registerContainedSessionMethods } from './containedSessions';\nimport { createDefaultWorkspaceFolder } from './defaultWorkspace';\nimport { createHostModelGateway, type HostModelGateway } from './hostModelGateway';\nimport {\n createIdleRestart,\n holdsRestart,\n keepTunnelIntent,\n prepareSessionRestore,\n readRecycleState,\n removeRecycleFile,\n reopenRecycledSessions,\n RESTART_EXIT_CODE,\n takeTunnelIntent,\n testIdleRestartOverrides,\n writeRecycleFile,\n} from './idleRestart';\nimport { ensureGlobalLogSink } from './logSink';\nimport { readMcpAppBuild } from './mcpAppBuild';\nimport { loadNativePushCredentials, subscribeNativePush } from './nativePush';\nimport { monitorRuntimeResources } from './runtimeResources';\nimport { createSandboxRouter, SANDBOX_UNREACHABLE, type SandboxRouter } from './sandboxRouter';\nimport {\n CONTAINER_WORKTREE_GONE,\n createSandboxSessionHandoff,\n handoffProvider,\n type HandoffProvider,\n type SandboxSessionHandoff,\n} from './sandboxSessionHandoff';\nimport { publishHeadlessSelectionStatus } from './selectionStatus';\nimport {\n launchSessionRequest,\n type PinnedSelectionAxis,\n resolveSessionIdentity,\n sessionSelectionArgs,\n} from './sessionArguments';\nimport { isCleanUserStop, SANDBOX_STOP_DEADLINE_MS, stopSandboxProviders, withShutdownDeadline } from './shutdown';\nimport type { ServeOptions, ServerRuntimeEnvironment } from './types';\nimport { createWatcherService, outsideNodeModules, type WatchChangeSource } from './watcherService';\nimport { resolveWebTemplateDecision } from './webTemplateDecision';\nimport { checkoutWorkspaceId } from './workspaceCheckout';\n\n/** What asked every scope to recheck: a watched change, a watcher tick, a finished sync or an upm install. */\ntype ScopeCheckSource = WatchChangeSource | 'sync' | 'upm';\n/** The largest protocol message a contained server accepts from its host. */\nconst CONTAINED_MAX_PAYLOAD_BYTES = 8 * 1024 * 1024;\n/** The base path of po-config's settings API, the one API a sandboxed workspace still answers on the host. */\nconst SETTINGS_API = 'settings';\n/** Package failures Help reports at once; the oldest drop first. */\nconst PACKAGE_FAILURE_LIMIT = 64;\n\n/** Whether a listen address stays on this machine: `localhost`, `127.0.0.0/8`, or `::1`. */\nfunction isLoopbackHost(host: string): boolean {\n const address = host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;\n if (address.toLowerCase() === 'localhost') return true;\n if (net.isIPv4(address)) return address.startsWith('127.');\n if (!net.isIPv6(address)) return false;\n const lower = address.toLowerCase();\n return (\n lower === '::1' || (lower.startsWith('::ffff:') && net.isIPv4(lower.slice(7)) && lower.slice(7).startsWith('127.'))\n );\n}\n\n/**\n * The installed payload a contained server imports in place, so it never writes package snapshots into a\n * read-only runtime. An installed Po sits at `<payload>/node_modules/@agimon-ai/po`; a source checkout is\n * its own package root.\n */\nfunction containedImmutableRoot(packageRoot: string): string {\n const scopeDirectory = path.dirname(packageRoot);\n return path.basename(path.dirname(scopeDirectory)) === 'node_modules'\n ? path.resolve(packageRoot, '../../..')\n : packageRoot;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** Whether the host itself serves the workspace: admitted here and not run by a sandbox. */\nfunction servedOnHost(workspace: HeadlessWorkspace): boolean {\n return workspace.available !== false && workspace.sandbox === undefined;\n}\n\n/** A workspace's live sandbox state, as the hub carries it. */\ntype SandboxStatusFields = Pick<HeadlessWorkspace, 'sandboxState' | 'sandboxReason'>;\n\n/** The hub's view of a workspace record: one mapping, so every registration carries its sandbox and its state. */\nfunction hubWorkspace(\n record: WorkspaceRecord,\n available: boolean,\n status: SandboxStatusFields = {},\n): HeadlessWorkspace {\n return {\n id: record.id,\n root: record.root,\n ...(record.name === undefined ? {} : { name: record.name }),\n ...(record.sandbox === undefined ? {} : { sandbox: record.sandbox }),\n ...(status.sandboxState === undefined ? {} : { sandboxState: status.sandboxState }),\n ...(status.sandboxReason === undefined ? {} : { sandboxReason: status.sandboxReason }),\n available,\n };\n}\n\nconst sameSandboxStatus = (left: SandboxStatusFields, right: SandboxStatusFields): boolean =>\n left.sandboxState === right.sandboxState && left.sandboxReason === right.sandboxReason;\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: rawNotice,\n resolveHarnessOptions,\n signal,\n onExtensionCheck,\n automation,\n } = runtime;\n // Only a contained server, reached through its sandbox's port forward, listens beyond loopback.\n if (options.host !== undefined && options.contained !== true && !isLoopbackHost(options.host))\n throw new Error(`--host ${options.host} is not a loopback address. Only a --contained server may listen on it.`);\n const sandboxIdentity: PoSandboxIdentity | undefined =\n options.contained === true\n ? Object.freeze({\n contained: true,\n ...(options.workspaceId === undefined ? {} : { workspaceId: options.workspaceId }),\n })\n : undefined;\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: rawNotice }).catch((error: unknown) =>\n rawNotice(`Global log sink unavailable: ${error instanceof Error ? error.message : String(error)}`),\n );\n // Telemetry's own warnings stay on the raw channel, so a failing sink cannot feed itself.\n const telemetry = createServerTelemetry({ cwd: baseCwd, env: baseEnvironment, warn: rawNotice });\n const notice = (message: string): void => {\n rawNotice(message);\n void telemetry\n .recordEvent('po_server.notice', { message })\n .catch((error: unknown) => rawNotice(`notice telemetry failed: ${String(error)}`));\n };\n const homeDirectory = baseEnvironment.HOME ?? os.homedir();\n const serverDirectory = path.join(piAgentDirectory(baseEnvironment), 'server');\n const temporaryDirectory = path.resolve(\n baseEnvironment.TMPDIR || baseEnvironment.TMP || baseEnvironment.TEMP || os.tmpdir(),\n );\n // One host platform for every composition root this server runs: hub, workspaces and sessions.\n const platform = {\n ...createNodePlatform({\n homeDirectory,\n temporaryDirectory,\n sessionsRoot: path.join(serverDirectory, 'sessions'),\n }),\n isolate: createNodeIsolate(),\n npm: createNodeNpm({\n poHome: poHomeDirectory(homeDirectory, baseEnvironment),\n homeDirectory,\n temporaryDirectory,\n environment: baseEnvironment,\n }),\n };\n /** Called on a watched change; assigned once every scope can be checked. */\n let pickUpChange = (_source: WatchChangeSource): void => undefined;\n const hostFiles = platform.env(baseCwd);\n const watcher = createWatcherService({\n onChange: (source) => pickUpChange(source),\n onNotice: notice,\n exists: async (directory) => {\n const info = await hostFiles.fileInfo(directory, BACKGROUND_CONTEXT);\n return info.ok && info.value.kind === 'directory';\n },\n });\n const isConfig = (file: string) => /\\.ya?ml$/u.test(file);\n // The Po home's documents layer under every root's own .po copy.\n watcher.add({ path: globalPoConfigDirectory(homeDirectory), include: isConfig });\n /** Compiles and loads packages once per content; every scope and session selects from it. */\n const bundler = createBundlerService({\n files: hostFiles,\n homeDirectory,\n environment: baseEnvironment,\n // Desktop owns this installed payload. Writing package snapshots into it breaks the app's signature.\n // A contained server runs from a read-only runtime and says so with its flag, not the environment.\n ...(sandboxIdentity !== undefined\n ? { immutableRoot: containedImmutableRoot(poPackageRoot()) }\n : baseEnvironment.PO_DISTRIBUTION === 'desktop' && baseEnvironment.PO_PACKAGE_ROOT\n ? { immutableRoot: path.resolve(baseEnvironment.PO_PACKAGE_ROOT, '../../..') }\n : {}),\n onNotice: notice,\n // What a root's compositions read: its .po documents and every repo-local package it selects.\n // Versioned and installed packages change only through sync or upm, which check every scope.\n onCompositions: (root, _compositions, packageRoots) => {\n watcher.add({ path: path.join(root, '.po'), include: isConfig });\n for (const packageRoot of packageRoots)\n if (!packageRoot.includes(`${path.sep}node_modules${path.sep}`))\n watcher.add({ path: packageRoot, recursive: true, include: outsideNodeModules });\n },\n });\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-v1') });\n const activeMedia = new Set<() => boolean>();\n const mediaArbitration: PoHostMediaArbitration = {\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: PoPeerAgentRegistry = {\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 // A contained server's workspace keeps its host id: its checkout root is recorded under that id before anything\n // admits it, so an exact root match names it and the container's session ids belong to the host's workspace.\n if (sandboxIdentity?.workspaceId !== undefined) {\n const containedRoot = await resolveWorkspaceRoot(baseCwd);\n for (const record of workspaces.list())\n if (record.root === containedRoot && record.id !== sandboxIdentity.workspaceId) workspaces.remove(record.id);\n if (!workspaces.list().some((record) => record.id === sandboxIdentity.workspaceId && record.root === containedRoot))\n workspaces.add({ id: sandboxIdentity.workspaceId, root: containedRoot });\n }\n // Bound on the global scope before it is served, so a root's global plugin can register a provider while\n // it loads. Closed once the global scope is up.\n const sandboxes = createWorkspaceSandboxRegistry();\n // Workspaces whose scope this process served. The hub cannot serve one twice, so a workspace that gets\n // a sandbox and is cleared again in the same run is marked available again instead of readmitted.\n const servedWorkspaces = new Set<string>();\n // Remembered workspaces (id to root) whose admission failed, such as a package import that ran while a build\n // rewrote it. The scope checks skip workspaces that are not served, so they retry these instead.\n const failedAdmissions = new Map<string, string>();\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 onNotice: notice,\n });\n const recycled = await readRecycleState(serverDirectory);\n const restorePlan = prepareSessionRestore(recycled);\n const recoverySessionIds = new Set(restorePlan.sessionIds);\n // A crash or recycle record wins; otherwise a named tunnel kept open through the last normal stop.\n const keptTunnel = await takeTunnelIntent(serverDirectory);\n const tunnelToRestore = recycled?.tunnel ?? keptTunnel;\n let recoveryTunnel = tunnelToRestore;\n let persistRecovery = (): void => {};\n let cleanShutdown = false;\n let recoveryWork: Promise<unknown> = Promise.resolve();\n let recoveryWrites: Promise<void> = Promise.resolve();\n let recovering = false;\n const recordLiveSession = (\n created: Awaited<ReturnType<HeadlessHub['create']>>,\n repoRoot: string,\n groupingRoot: string,\n ): void => {\n if (created.workspaceId === undefined) throw new Error('The new session has no workspace.');\n const saved = openSessions.add({\n sessionId: created.id,\n workspaceId: created.workspaceId,\n cwd: created.cwd,\n repoRoot,\n groupingRoot,\n name: created.name,\n createdAt: created.createdAt,\n ...(created.parentSessionId === undefined ? {} : { parentSessionId: created.parentSessionId }),\n ...(created.sessionProvenance === undefined ? {} : { sessionProvenance: created.sessionProvenance }),\n ...(created.interaction === undefined ? {} : { interaction: created.interaction }),\n ...(created.groups === undefined || created.groups.length === 0 ? {} : { groups: [...created.groups] }),\n });\n if (saved === false) throw new Error('The new session could not be durably recorded.');\n recoverySessionIds.add(created.id);\n persistRecovery();\n };\n /** Named jobs running now, and every job that ran since the last sample, so a stall names what was busy. */\n const activeJobs = new Map<string, number>();\n const recentJobs = new Set<string>();\n const trackJob = async <T>(name: string, run: () => Promise<T>): Promise<T> => {\n activeJobs.set(name, (activeJobs.get(name) ?? 0) + 1);\n recentJobs.add(name);\n try {\n return await run();\n } finally {\n const left = (activeJobs.get(name) ?? 1) - 1;\n if (left === 0) activeJobs.delete(name);\n else activeJobs.set(name, left);\n }\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('po_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 // `none` means no named job ran: profile the host rather than reading scope checks.\n const jobs = [...recentJobs].join(':') || 'none';\n recentJobs.clear();\n for (const name of activeJobs.keys()) recentJobs.add(name);\n if (delay >= 100)\n void telemetry\n .recordEvent('po_server.event_loop_delay', { duration_ms: Math.round(delay), job_name: jobs })\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: LoadedServerPackages;\n mcpBundle: LoadedMcpPlugins;\n /** Loads the session's package set again from its own composition root and selection. */\n loadBundle: () => Promise<LoadedServerPackages>;\n };\n type SessionArtifacts = SessionSetup & { apis: PackageApiServer };\n /** The server's environment rooted at one configuration root, with no harness state of its own. */\n const rootEnvironment = (root: string): NodeJS.ProcessEnv => {\n const environment: NodeJS.ProcessEnv = { ...baseEnvironment, PO_ROOT: root };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete environment[key];\n return environment;\n };\n const pendingSessions = new Map<string, SessionSetup>();\n /** The last harness context built to report each repository's MCP projection, kept while it is current. */\n const repositoryContexts = new Map<string, { cleanup(): Promise<void> }>();\n const sessionArtifacts = new Map<string, SessionArtifacts>();\n /** Each host's session package root, where its session services (background work included) live. */\n const sessionServiceRoots = new WeakMap<HeadlessSessionHost, Parameters<HeadlessSessionHost['preparePackages']>[0]>();\n /** Assigned once packages can load: reloads one running session's own packages. */\n let reloadSessionPackages: ((sessionId: string) => Promise<PackageReconcileResult>) | undefined;\n /** Assigned with reloadSessionPackages: re-applies one session's selection axes from disk. */\n let refreshSessionSelection:\n | ((sessionId: string, axes: readonly PoHeadlessRefreshAxis[]) => Promise<void>)\n | undefined;\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 persistRecovery = () => {\n if (shuttingDown || signal.aborted) return;\n const ids = [...recoverySessionIds];\n const details = {\n kind: 'live' as const,\n crashRestores: restorePlan.crashRestores,\n ...(recoveryTunnel === undefined ? {} : { tunnel: recoveryTunnel }),\n };\n recoveryWrites = recoveryWrites\n .then(() => writeRecycleFile(serverDirectory, ids, details))\n .catch((error: unknown) => {\n notice(`Could not persist crash recovery: ${error instanceof Error ? error.message : String(error)}`);\n });\n };\n\n const removeSessionOutputs = async (sessionId: string): Promise<void> => {\n // A container session's files live in its container, which removes them, as do a host session's the host just\n // handed over.\n const handedTo = handoff?.handedOff(sessionId);\n if (router !== undefined && (router.owns(sessionId) || handedTo !== undefined)) {\n await router.removeSession(sessionId, handedTo);\n handoff?.forget(sessionId);\n openSessions.remove(sessionId);\n return;\n }\n const directories = await readSessionFileDirectories(platform.sessions, sessionId);\n await removeSessionFiles({\n platform,\n sessionId,\n environment: baseEnvironment,\n artifactDirectory: path.join(\n directories?.agentDirectory ?? piAgentDirectory(baseEnvironment, homeDirectory),\n 'po-artifacts',\n sessionId,\n ),\n ...(directories === undefined ? {} : { directories }),\n });\n // Leave the record available for a retry until both output roots have been removed.\n openSessions.remove(sessionId);\n };\n\n /** Routes the sessions of contained workspaces into their containers; host servers only. */\n let router: SandboxRouter | undefined;\n /** Hands sessions over between the host and a sandbox's Po home when a workspace switches; host servers only. */\n let handoff: SandboxSessionHandoff | undefined;\n /** The sandboxed workspace's provider, when it runs with a Po home on host disk that sessions can move into. */\n const handoffProviderOf = (workspaceId: string | undefined): HandoffProvider | undefined => {\n const sandbox = workspaces.list().find((workspace) => workspace.id === workspaceId)?.sandbox;\n return sandbox === undefined ? undefined : handoffProvider(sandboxes.get(sandbox));\n };\n /** The host's own part of a sandbox's state: a handover in progress, or a switch that failed. */\n const sandboxTransitions = new Map<string, SandboxStatusFields>();\n /** Set once the global scope has loaded, so a provider missing by then is missing for good. */\n let sandboxProvidersSettled = false;\n /**\n * A workspace's live sandbox state. A sandboxed one: the host's transition, else running while linked, else what\n * its provider reports. A local one: unavailable only when every provider that reports availability cannot run\n * sandboxes now, so the switch can say why it is off.\n */\n const sandboxStatus = (record: WorkspaceRecord): SandboxStatusFields => {\n if (record.sandbox === undefined) {\n const reports = sandboxes\n .list()\n .map((provider) => provider.availability?.())\n .filter((report) => report !== undefined);\n const blocked = reports.find((report) => !report.available);\n return blocked === undefined || blocked.available || reports.some((report) => report.available)\n ? {}\n : { sandboxState: 'unavailable', sandboxReason: blocked.reason };\n }\n // A switch that is starting the sandbox gives way to running, or to a failure its provider reports.\n const transition = sandboxTransitions.get(record.id);\n if (transition !== undefined && transition.sandboxState !== 'starting') return transition;\n if (router?.connected(record.id) === true) return { sandboxState: 'running' };\n const provider = sandboxes.get(record.sandbox);\n if (provider === undefined)\n return sandboxProvidersSettled\n ? { sandboxState: 'unavailable', sandboxReason: `The sandbox provider '${record.sandbox}' is not installed.` }\n : {};\n const availability = provider.availability?.();\n if (availability !== undefined && !availability.available)\n return { sandboxState: 'unavailable', sandboxReason: availability.reason };\n const status = provider.status?.(record.id);\n if (status?.state === 'failed') return { sandboxState: 'failed', sandboxReason: status.reason };\n // Running in the provider but not linked yet still counts as starting, as does a provider still checking.\n return (\n transition ??\n (status !== undefined || (provider.availability !== undefined && availability === undefined)\n ? { sandboxState: 'starting' }\n : {})\n );\n };\n const hubEntry = (record: WorkspaceRecord, available: boolean): HeadlessWorkspace =>\n hubWorkspace(record, available, sandboxStatus(record));\n /** Registers the workspace again when its availability or sandbox state changed, so clients see it live. */\n const refreshWorkspace = (workspaceId: string): void => {\n const record = workspaces.list().find((workspace) => workspace.id === workspaceId);\n const known = hub.workspaces().find((workspace) => workspace.id === workspaceId);\n // A record whose sandbox changed is registered by the switch itself.\n if (record === undefined || known === undefined || known.sandbox !== record.sandbox) return;\n const available =\n record.sandbox === undefined ? known.available !== false : router?.connected(workspaceId) === true;\n const entry = hubEntry(record, available);\n if (available === (known.available !== false) && sameSandboxStatus(entry, known)) return;\n hub.registerWorkspace(entry);\n };\n const refreshWorkspaces = (): void => {\n for (const workspace of hub.workspaces()) refreshWorkspace(workspace.id);\n };\n const stopSandboxWatches: (() => void)[] = [];\n /**\n * A host session of a workspace that is now sandboxed closed: it follows the workspace into the sandbox, and the\n * host scope, kept only for host sessions, unloads with the last of them.\n */\n const handOffClosedSession = async (sessionId: string, workspaceId: string, keepDormant: boolean): Promise<void> => {\n const provider = handoffProviderOf(workspaceId);\n if (provider === undefined || handoff === undefined) return;\n try {\n await handoff.sessionClosed(sessionId, workspaceId, keepDormant, provider);\n } catch (error) {\n notice(`Session ${sessionId} could not follow its workspace into the sandbox: ${errorMessage(error)}`);\n }\n const hostSessionsLeft = baseSessionManager\n .sessions()\n .some(\n (host) =>\n host.runtime.sessionId !== sessionId && hub.session(host.runtime.sessionId)?.workspaceId === workspaceId,\n );\n if (hostSessionsLeft || !servedWorkspaces.has(workspaceId)) return;\n servedWorkspaces.delete(workspaceId);\n await hub\n .unloadWorkspaceScope?.(workspaceId)\n .catch((error: unknown) => notice(`Workspace '${workspaceId}' scope did not unload: ${errorMessage(error)}`));\n };\n const closeManagedSession = async (sessionId: string, options?: HeadlessSessionCloseOptions): Promise<void> => {\n // A container session never had a host record or host outputs; at shutdown its mirror only lets go.\n if (router?.mirror(sessionId) !== undefined) {\n await router.closeSession(sessionId, { keepDormant: options?.keepDormant === true, disposeOnly: shuttingDown });\n return;\n }\n // The hub has already unregistered the session; its record still names the workspace.\n const closingWorkspaceId = openSessions.list().find((record) => record.sessionId === sessionId)?.workspaceId;\n // A released session keeps its record, which is what lists it as dormant.\n if (!shuttingDown) {\n recoverySessionIds.delete(sessionId);\n persistRecovery();\n if (options?.keepDormant !== true) openSessions.remove(sessionId);\n }\n const artifacts = sessionArtifacts.get(sessionId);\n sessionArtifacts.delete(sessionId);\n webCompositions?.remove({ scope: 'session', sessionId });\n webCompositions?.removeNative({ 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 packages 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 if (!shuttingDown && closingWorkspaceId !== undefined)\n await handOffClosedSession(sessionId, closingWorkspaceId, options?.keepDormant === true);\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) ?? router?.mirror(sessionId),\n sessions: () => [...baseSessionManager.sessions(), ...(router?.mirrors() ?? [])],\n closeSession: closeManagedSession,\n async close() {\n const ids = sessionManager.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: (scope: PoHubSessionScope, request: PoHubSessionApiRequest) => Promise<Response> = async () =>\n Response.json({ error: 'Session API unavailable.' }, { status: 404 });\n /** Assigned once the shared API context exists: the host-side APIs of a workspace whose scope it does not serve. */\n let unservedWorkspaceApi: NonNullable<HeadlessHubOptions['unservedWorkspaceApi']> = () => undefined;\n let openSession: (\n request: PoHubSessionCreateRequest,\n sessionId?: string,\n groupingWorkspaceId?: string,\n ) => Promise<PoHubSessionScope> = async () => {\n throw new Error('The cockpit session service is not ready.');\n };\n let admitWorkspace: (\n root: string,\n name?: string,\n ) => Promise<HeadlessWorkspace & { available: boolean }> = async () => {\n throw new Error('Workspace admission is not ready.');\n };\n let dormantSessions: () => readonly OpenSessionRecord[] = () => [];\n let reviveSession: (sessionId: string) => Promise<void> = async () => {\n throw new Error('Session revival is not ready.');\n };\n let remoteRuntime: RemoteRuntime | undefined;\n let stopNativePush: (() => void) | undefined;\n const computerUse = await createComputerUseBinding(process, {\n isDeviceAuthorized: (id) => remoteRuntime?.remote.isDeviceAuthorized(id) === true,\n stepUpRequired: () => remoteRuntime?.remote.stepUpRequired('computer-use.activate') === true,\n });\n /** Packages whose build failed since their scope's last commit, keyed like `bundler` scopes. */\n const failedPackages = new Map<string, Set<string>>();\n /** What Help's `help_status` reads: each package's latest failure per scope, oldest dropped first. */\n const packageFailures = new Map<string, PoPackageFailureRecord>();\n const recordPackageFailure = (record: Omit<PoPackageFailureRecord, 'at'>): void => {\n const id = `${record.scope}\\0${record.packageName}`;\n const reason = record.reason.slice(0, 512);\n const repeated = packageFailures.get(id)?.reason === reason;\n packageFailures.delete(id);\n packageFailures.set(id, { ...record, reason, at: new Date().toISOString() });\n for (const oldest of packageFailures.keys()) {\n if (packageFailures.size <= PACKAGE_FAILURE_LIMIT) break;\n packageFailures.delete(oldest);\n }\n if (!repeated) notifyPackageFailure(record);\n };\n /** Shows a failure once in each live top-level session of its scope, as a notification the hub sends to web and native. */\n const notifyPackageFailure = (record: Omit<PoPackageFailureRecord, 'at'>): void => {\n const data = createPoNotificationEntryData({\n title: 'Plugin failed',\n body: `${record.packageName} could not ${record.stage} (${record.reason})${record.previous === 'restored' ? '. Its previous build still runs.' : ''}`,\n level: 'error',\n });\n if (!data) return;\n for (const session of hub.snapshot()) {\n if (session.parentSessionId !== undefined || session.host.agentSession !== undefined) continue;\n if (record.scope !== 'global' && record.scope !== `workspace:${session.workspaceId}`) continue;\n void session.host.runtime\n .appendCustomEntry(PO_NOTIFICATION_ENTRY_TYPE, data)\n .catch((error: unknown) => notice(`Plugin failure notice for session ${session.id} failed: ${String(error)}`));\n }\n };\n /** Ends one install of a scope: returns the packages that failed to apply and clears the rest's record. */\n const takeFailedPackages = (\n key: string,\n packages: readonly { readonly declaration: { readonly packageName: string } }[],\n ): ReadonlySet<string> => {\n const failed = failedPackages.get(key) ?? new Set<string>();\n failedPackages.delete(key);\n for (const { declaration } of packages)\n if (!failed.has(declaration.packageName)) packageFailures.delete(`${key}\\0${declaration.packageName}`);\n return failed;\n };\n let hub!: HeadlessHub;\n /** Assigned once the global builds can be read; no session opens before then. */\n let publishSessionCompositions: NonNullable<HeadlessHubOptions['publishSessionCompositions']> = () => ({});\n hub = createHeadlessHub({\n manager: sessionManager,\n platform,\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 // The session mounts only its major mode's plugins, republished when the mode changes.\n publishSessionCompositions: (sessionId, root, majorMode) => publishSessionCompositions(sessionId, root, majorMode),\n admitWorkspace: async ({ root, name }) => {\n const byName = root === undefined || root.trim() === '';\n const admitted = await admitWorkspace(\n byName ? await createDefaultWorkspaceFolder(name ?? '', homeDirectory) : root,\n name,\n );\n // A channel admitting a folder by name gets a host workspace; a sandboxed one is not that.\n if (byName && admitted.sandbox !== undefined)\n throw new Error(\n `Workspace '${admitted.name ?? admitted.id}' runs in a sandbox and cannot be admitted by name.`,\n );\n return admitted;\n },\n dormantSessions: () => dormantSessions(),\n reviveSession: (sessionId) => reviveSession(sessionId),\n onWorkspaceRemoved: (workspaceId) => {\n workspaces.remove(workspaceId);\n bundler.forgetScope(`workspace:${workspaceId}`);\n webCompositions?.remove({ scope: 'workspace', workspaceId });\n webCompositions?.removeNative({ 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 ((await checkoutWorkspaceId(workspaces.list(), request.cwd)) !== placement.workspaceId)\n throw new Error('The session directory is outside this workspace.');\n return openSession(request, 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 onPackageFailed: (mount, failure) => {\n if (mount.scope === 'session') return;\n const key = mount.scope === 'global' ? 'global' : `workspace:${mount.workspaceId}`;\n failedPackages.set(key, (failedPackages.get(key) ?? new Set()).add(failure.packageName));\n recordPackageFailure({ scope: key, stage: 'apply', ...failure });\n },\n hubToken: () => attachToken,\n requestSessionApi: (scope, request) => requestSessionApi(scope, request),\n unservedWorkspaceApi: (workspaceId, basePath) => unservedWorkspaceApi(workspaceId, basePath),\n ...(computerUse === undefined ? {} : { computerUse }),\n });\n // A contained server holds no credentials: its sessions call models through the host's gateway.\n const modelGateway: ModelGatewayContainer | undefined =\n sandboxIdentity === undefined ? undefined : createModelGatewayContainer({ hub });\n /** Assigned once the global builds can be read: a mirror's compositions come from the global composition. */\n let publishMirrorCompositions: (\n sessionId: string,\n ) => Pick<HeadlessHubSession, 'webComposition' | 'nativeComposition'> = () => ({});\n let hostModels: Promise<HostModelGateway | undefined> | undefined;\n if (sandboxIdentity === undefined)\n router = createSandboxRouter({\n hub,\n sandboxes,\n workspaces: () => workspaces.list(),\n announceWorkspace: (workspaceId) => refreshWorkspace(workspaceId),\n sessionCompositions: (sessionId) => publishMirrorCompositions(sessionId),\n forgetCompositions: (sessionId) => {\n webCompositions?.remove({ scope: 'session', sessionId });\n webCompositions?.removeNative({ scope: 'session', sessionId });\n },\n // The host's own models and credentials, created once the first container needs them.\n modelGateway: () =>\n (hostModels ??= createHostModelGateway(piAgentDirectory(baseEnvironment, homeDirectory), homeDirectory).catch(\n (error: unknown) => {\n notice(\n `The host models for sandboxes could not load: ${error instanceof Error ? error.message : String(error)}`,\n );\n hostModels = undefined;\n return undefined;\n },\n )),\n // Host sessions closed while the link was down, and leftovers of an interrupted switch, follow on each link.\n onLinked: (workspaceId) => {\n // A start, or a failure reported earlier, is over once the sandbox answers.\n const transition = sandboxTransitions.get(workspaceId)?.sandboxState;\n if (transition === 'starting' || transition === 'failed') sandboxTransitions.delete(workspaceId);\n refreshWorkspace(workspaceId);\n const provider = handoffProviderOf(workspaceId);\n const workspace = workspaces.list().find((entry) => entry.id === workspaceId);\n if (provider === undefined || workspace === undefined || handoff === undefined) return;\n void handoff\n .retry(workspace, provider)\n .catch((error: unknown) =>\n notice(`Workspace '${workspaceId}' handover retry failed: ${errorMessage(error)}`),\n );\n },\n onNotice: notice,\n });\n if (router !== undefined) {\n const linkedRouter = router;\n handoff = createSandboxSessionHandoff({\n host: { poHome: poHomeDirectory(homeDirectory, baseEnvironment), agentDir: path.dirname(serverDirectory) },\n openSessions,\n savedSessionIds: async (workspace) =>\n (\n await listSavedSessionRecords(\n platform.sessions,\n workspace.root,\n new Set(hub.snapshot().map((active) => active.id)),\n workspace.id,\n )\n ).map((saved) => saved.summary.id),\n // A session the hub let go of still runs until its host has closed.\n isLive: (sessionId) => hub.session(sessionId) !== undefined || baseSessionManager.get(sessionId) !== undefined,\n adopt: (workspaceId, record) => linkedRouter.adoptSession(workspaceId, record),\n onNotice: notice,\n });\n }\n /** Started by the idle restart once the server is serving; until then a restart waits. */\n let requestRestart: (() => void) | undefined;\n const idleRestart = createIdleRestart({\n ...testIdleRestartOverrides(baseEnvironment),\n busy: async () => {\n // A container session's turn is not visible here, and a host restart drops its mirror: count it as busy.\n if (recovering || (router?.mirrors().length ?? 0) > 0) return true;\n const hosts = sessionManager.sessions();\n // Running runners (open terminals) and subagents block like a turn: a restart kills them.\n const working = hosts.some((host) => {\n const root = sessionServiceRoots.get(host);\n const service = root === undefined ? undefined : readPoBackgroundWorkService(root);\n return service !== undefined && holdsRestart(service.snapshot());\n });\n if (working) return true;\n const states = await Promise.all(hosts.map((host) => host.runtime.readState()));\n return states.some((state) => state.isStreaming || state.isCompacting);\n },\n restart: () => requestRestart?.(),\n onError: (error) => notice(`Idle restart check failed: ${error instanceof Error ? error.message : String(error)}`),\n });\n // Any hub event may be the end of a turn, so it re-arms a pending restart's debounce.\n const stopIdleRestartPoke = hub.onEvent(() => idleRestart.poke());\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 const groups = event.session.groups ?? [];\n const sameGroups =\n groups.length === (record?.groups ?? []).length &&\n groups.every((group, index) => record?.groups?.[index] === group);\n if (record === undefined || (record.name === event.session.name && sameGroups)) return;\n openSessions.add({ ...record, name: event.session.name, groups });\n });\n let harnessContext: Awaited<ReturnType<typeof buildHarnessContext>> | undefined;\n let launchWorkspaceId: string | undefined;\n let cockpit: Awaited<ReturnType<typeof serveHeadlessServer>> | undefined;\n let attachToken: string | undefined;\n let webCompositions: ReturnType<typeof createWebCompositions> | undefined;\n const stopResourceMonitor = monitorRuntimeResources({\n record: (attributes) => telemetry.recordEvent('po_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 superseded_module_count: idleRestart.supersededCount(),\n idle_restart_pending_age_ms: idleRestart.pendingAgeMs(),\n };\n },\n warn: notice,\n });\n\n try {\n await telemetry.runInSpan('po_server.startup', {}, async () => {\n const token = getOrThrow(await hostFiles.readTextFile(options.tokenFile, BACKGROUND_CONTEXT)).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 = globalPoConfigDirectory(homeDirectory);\n const publicationDirectory = path.join(globalRoot, 'server');\n await reapAbandonedPublications(platform.env(baseCwd), publicationDirectory, processIsAlive).catch(\n (error: unknown) =>\n notice(`Abandoned publication cleanup failed: ${error instanceof Error ? error.message : String(error)}`),\n );\n webCompositions = createWebCompositions(publicationDirectory, notice, {\n pid: nodeHost.processId(),\n startedAt: Date.now(),\n });\n /** Assigned once every scope can be checked; a sync that exits sooner is picked up then. */\n let pickUpSync: (source?: ScopeCheckSource) => Promise<void> = async () => undefined;\n // Sync is the only producer of artifacts; this server starts it in the background and\n // reads what it prepared. PO_AUTO_SYNC=0 turns that off.\n const backgroundSync = createBackgroundSync({\n files: hostFiles,\n environment: baseEnvironment,\n onNotice: notice,\n onExit: () => pickUpSync(),\n // The host serves a contained workspace's web and native UI, so its sync builds only packages.\n ...(sandboxIdentity === undefined ? {} : { skipArtifactBuilds: true }),\n });\n const syncCheckpoints = createSyncCheckpoints({\n globalRoot,\n homeDirectory,\n environment: baseEnvironment,\n background: backgroundSync,\n onNotice: notice,\n });\n // A manual `po sync` moves the pointer without this server's background sync exiting, and\n // names each app bundle it exported from a source checkout in `app-<platform>.json`.\n watcher.add({\n path: path.dirname(syncPointerPath(globalRoot)),\n include: (file) => file === path.basename(syncPointerPath(globalRoot)) || /^app-[a-z]+\\.json$/u.test(file),\n });\n /** What the root opened without: packages that do not resolve yet and web plugins with no slot. */\n const unsyncedOf = async (root: string): Promise<{ selectors: string[]; webPackages: string[] }> => {\n try {\n const compositions = bundler.compositions(root);\n const webPackages =\n webBuild === undefined\n ? []\n : await unslottedWebPackages(webBuild, await compositionPackageRoots(compositions, hostFiles), hostFiles);\n return { selectors: unsyncedSelectors(compositions), webPackages };\n } catch (error) {\n notice(`'${root}' sync state could not be read: ${error instanceof Error ? error.message : String(error)}`);\n return { selectors: [], webPackages: [] };\n }\n };\n const workspaceLabel = (root: string, name?: string) => `Workspace '${name ?? path.basename(root)}'`;\n /** A checkpoint: request a background sync when the root changed since the last one, and warn. */\n const syncCheckpoint = async (root: string, label: string, request = true) => {\n const { selectors, webPackages } = await unsyncedOf(root);\n // A selected package that gained a web plugin leaves the selection unchanged, so the stale\n // check misses it; ask once per pointer state for the build that gives it a slot.\n if (request && webPackages.length > 0)\n await syncCheckpoints.requestMissing(\n `web-slot:${root}:${webPackages.join(',')}`,\n `${label} has web plugins without a slot: ${webPackages.join(', ')}`,\n );\n return syncCheckpoints.check({ root, label, unsynced: [...new Set([...selectors, ...webPackages])] }, request);\n };\n let webBuild: GlobalWebBuildRecord | undefined;\n /**\n * Publishes one mount out of the current global build, naming only the plugin slots its root\n * resolves. A session mount passes its major mode, so it names only that mode's slots.\n */\n const publishWebMount = (\n mount: ScopeMount | { scope: 'session'; sessionId: string },\n root: string,\n majorMode?: string,\n ) =>\n webBuild === undefined\n ? undefined\n : webCompositions?.publish(\n mount,\n webBuild,\n hub.channelTypes(),\n mountWebPluginSlots(webBuild, bundler.packageRoots(root, majorMode)),\n );\n let nativeBuild: GlobalNativeBuildRecord | undefined;\n /** Publishes one mount's native composition out of the current global native build. */\n const publishNativeMount = (\n mount: ScopeMount | { scope: 'session'; sessionId: string },\n root: string,\n majorMode?: string,\n ) =>\n nativeBuild === undefined\n ? undefined\n : webCompositions?.publishNative(\n mount,\n nativeBuild,\n hub.channelTypes(),\n mountNativePluginIds(nativeBuild, bundler.packageRoots(root, majorMode)),\n );\n /**\n * Republishes a global or workspace mount and reports whether its web or native composition\n * changed, so clients are told to swap only after a publish that succeeded and differs.\n */\n const publishSharedMount = (mount: ScopeMount, root: string): boolean => {\n const current = () => JSON.stringify([webCompositions?.get(mount), webCompositions?.getNative(mount)]);\n const before = current();\n publishNativeMount(mount, root);\n publishWebMount(mount, root);\n return current() !== before;\n };\n publishSessionCompositions = (sessionId, root, majorMode) => ({\n webComposition: publishWebMount({ scope: 'session', sessionId }, root, majorMode),\n nativeComposition: publishNativeMount({ scope: 'session', sessionId }, root, majorMode),\n });\n // A container session's checkout is never read on the host, so its plugins come from the global composition.\n publishMirrorCompositions = (sessionId) => ({\n webComposition: publishWebMount({ scope: 'session', sessionId }, globalRoot),\n nativeComposition: publishNativeMount({ scope: 'session', sessionId }, globalRoot),\n });\n const pickUpWebBuild = createKeyedPickup(\n (key) => readGlobalWebBuildRecord(globalRoot, key, hostFiles),\n (build, key) => {\n notice(`Publishing global web build ${key}.`);\n webBuild = build;\n webCompositions?.publishShell(build);\n hub.bumpRevision?.('global:web-bundle');\n },\n );\n const pickUpNativeBuild = createKeyedPickup(\n (key) => readGlobalNativeBuildRecord(globalRoot, key, hostFiles),\n (build, key) => {\n notice(`Publishing global native build ${key}.`);\n nativeBuild = build;\n },\n );\n /** The keys these roots derive the way sync does, each only when its build exists. */\n const ownBuildKeys = async (): Promise<{ webKey?: string; nativeKey?: string }> => {\n const pluginRoots = await globalWebPluginRoots(globalRoot, homeDirectory, baseEnvironment, notice);\n const web = await readGlobalWebBuildStatus({\n poHome: globalRoot,\n pluginRoots,\n environment: baseEnvironment,\n files: hostFiles,\n });\n const native = await readGlobalNativeBuildStatus({ poHome: globalRoot, pluginRoots, files: hostFiles });\n return {\n ...(web.status === 'current' ? { webKey: web.key } : {}),\n ...(native.status === 'current' ? { nativeKey: native.key } : {}),\n };\n };\n const currentBuildKeys = async () => {\n const pointer = await readSyncPointer(globalRoot);\n return syncedBuildKeys({\n pointer,\n ownsPointer: await syncCheckpoints.ownsPointer(pointer),\n published: { web: webBuild !== undefined, native: nativeBuild !== undefined },\n ownKeys: ownBuildKeys,\n newestWebKey: () => newestGlobalWebBuildKey(globalRoot, hostFiles),\n });\n };\n /**\n * Read-only: picks up the global web and native builds sync's pointer names, publishing\n * the shell only when a key changed, then republishes every shared mount. Never builds;\n * a missing build leaves the previous one serving. Clients pick a new composition up at\n * their next refreshWebPluginCompositions.\n */\n const refreshWebBuild = async (): Promise<void> => {\n const keys = await currentBuildKeys();\n if ((await pickUpNativeBuild(keys.nativeKey)) === 'missing')\n notice(`The global native build ${String(keys.nativeKey)} is missing; run po sync.`);\n if ((await pickUpWebBuild(keys.webKey)) === 'missing')\n notice(`The global web build ${String(keys.webKey)} is missing; run po sync.`);\n const mounts = hub\n .workspaces()\n .filter(servedOnHost)\n .map((workspace) => ({\n root: workspace.root,\n mount: { scope: 'workspace', workspaceId: workspace.id } as const,\n }));\n await Promise.all([globalRoot, ...mounts.map(({ root }) => root)].map((root) => bundler.packageEntries(root)));\n const changed = [{ root: globalRoot, mount: { scope: 'global' } as const }, ...mounts]\n .filter(({ root, mount }) => publishSharedMount(mount, root))\n .map(({ mount }) => mount);\n hub.touchCompositions?.(changed);\n for (const platform of NATIVE_APP_PLATFORMS) {\n const app = await readNativeAppBuild(globalRoot, platform, hostFiles);\n if (app !== undefined) webCompositions?.publishApp(platform, app);\n }\n };\n const loadComposition = async (\n root: string,\n scope: 'global' | 'workspace' | 'session',\n selection?: { root: string; majorMode: string; activeLayers: string[] },\n /** The `bundler` scope key a load failure is recorded under; sessions record none. */\n healthKey?: string,\n ) => {\n const selected = selection ?? bundler.defaultSelection(root);\n return telemetry.runInSpan('po_server.composition_load', { scope }, async () =>\n loadServerPackages(scope, {\n entries: await bundler.packageEntries(root),\n majorMode: selected.majorMode,\n activeLayers: selected.activeLayers,\n retainCandidates: scope === 'session',\n onNotice: notice,\n ...(healthKey === undefined\n ? {}\n : {\n onPackageFailed: (packageName: string, reason: string) =>\n recordPackageFailure({ scope: healthKey, packageName, stage: 'load', reason }),\n }),\n poisoned: bundler.poisoned,\n importer: bundler.importer,\n }),\n );\n };\n type ScopeMount = { scope: 'global' } | { scope: 'workspace'; workspaceId: string };\n const scopeKey = (mount: ScopeMount) => (mount.scope === 'global' ? 'global' : `workspace:${mount.workspaceId}`);\n const scopeChecks = new Map<string, Promise<unknown>>();\n /** Each package of a scope (`global`, `workspace:<id>`, `session:<id>`) whose current build failed. */\n const scopeFailures = (key: string) =>\n [...packageFailures.values()]\n .filter((record) => record.scope === key)\n .map(({ packageName, reason }) => ({ packageName, reason }));\n /**\n * The reload check for one served global or workspace scope: recompute its package URLs\n * and, only when they changed, load the new set and install it. Unchanged URLs come from\n * the module cache and the scope skips them, so only changed packages import and restart;\n * a package no longer selected stays installed. A scope this server has not served yet is\n * left to its admission. Checks of one scope run one at a time; a changed package whose\n * new build fails to apply gets its previous build back and is not committed, so the next\n * check applies it again. An import failure poisons its URL instead and waits for a rebuild,\n * which gets a new URL. Runs on a watched change, a finished sync and an upm change, never\n * on the session path.\n *\n * An `explicit` check (Help's reload) runs even when nothing looks changed, retries poisoned\n * imports, disposes installed packages the scope no longer declares, and rejects on failure.\n */\n const checkScope = (\n root: string,\n mount: ScopeMount,\n explicit = false,\n ): Promise<PoSelfImproveReloadResult | undefined> => {\n const key = scopeKey(mount);\n const run = (scopeChecks.get(key) ?? Promise.resolve()).then(async () => {\n // A sync that finished since the last check may name new builds without touching packages.\n try {\n await refreshWebBuild();\n } catch (error) {\n notice(`Web build check failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (explicit) {\n bundler.invalidate();\n bundler.poisoned.clear();\n }\n const change = await bundler.diffScope(key, root, mount.scope);\n if (\n change.first ||\n (!explicit && change.changed.length === 0 && change.reselected.length === 0 && change.removed.length === 0)\n )\n return undefined;\n const bundle = await loadComposition(root, mount.scope, undefined, key);\n failedPackages.delete(key);\n let installed = await hub.installPackages(mount, bundle.packages);\n const declared = new Set(\n bundle.entries.filter((entry) => entry.scopes.includes(mount.scope)).map((entry) => entry.packageName),\n );\n const removed = explicit ? installed.filter((name) => !declared.has(name)) : [];\n if (removed.length > 0) installed = await hub.uninstallPackages(mount, removed);\n const failed = takeFailedPackages(key, bundle.packages);\n bundler.commitScope(key, root, mount.scope, bundle.entries, failed);\n idleRestart.supersede(change.superseded);\n if (publishSharedMount(mount, root)) hub.touchCompositions?.([mount]);\n // A web plugin the build has no slot for yet mounts when the requested sync finishes.\n if (explicit)\n await syncCheckpoint(\n root,\n mount.scope === 'global'\n ? 'The global scope'\n : workspaceLabel(root, hub.workspaces().find(({ id }) => id === mount.workspaceId)?.name),\n );\n notice(\n `Reloaded ${mount.scope === 'global' ? 'global' : `workspace '${mount.workspaceId}'`} packages (${String(change.changed.length)} changed, ${String(change.removed.length)} no longer selected${removed.length === 0 ? '' : `, ${String(removed.length)} removed`}${failed.size === 0 ? '' : `, ${String(failed.size)} failed and retry at the next check`}).`,\n );\n return { installed, removed, failed: scopeFailures(key) };\n });\n const settled = run.catch((error: unknown) => {\n notice(\n `Extension check of ${key} failed and retries at the next check: ${error instanceof Error ? error.message : String(error)}`,\n );\n return undefined;\n });\n scopeChecks.set(key, settled);\n void settled.then(() => {\n if (scopeChecks.get(key) === settled) scopeChecks.delete(key);\n });\n return explicit ? run : settled;\n };\n const loadSessionMcp = async (\n root: string,\n selection: { majorMode: string; activeLayers: readonly string[] },\n ): Promise<LoadedMcpPlugins> => {\n return telemetry.runInSpan('po_server.mcp_bundle_load', {}, async () => {\n const { candidates, entries } = await bundler.mcpEntries(root);\n let app: Awaited<ReturnType<typeof readMcpAppBuild>>;\n try {\n app = await readMcpAppBuild({ poHome: globalRoot, candidates, files: hostFiles });\n } catch (error) {\n notice(`The MCP app build could not be read: ${error instanceof Error ? error.message : String(error)}`);\n }\n if (app !== undefined && app.build === undefined) {\n notice(`MCP app build ${app.key} is not synced yet; this session runs without MCP widgets.`);\n await syncCheckpoints.requestMissing(`mcp-app:${app.key}`, 'the MCP app build is missing');\n }\n const built = app?.build;\n return loadMcpPlugins({\n entries,\n ...(built === undefined ? {} : { uiResource: mcpUiResource(built.html, built.sha256) }),\n majorMode: selection.majorMode,\n activeLayers: selection.activeLayers,\n retainCandidates: true,\n onNotice: notice,\n poisoned: bundler.poisoned,\n importer: bundler.importer,\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 // Listed for settings, sandboxed ones too, so a switched-on workspace can be switched off again. Host packages\n // still never resolve a sandboxed checkout to run anything in it (`resolveRepository` below).\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) =>\n hub.workspaces().find((workspace) => workspace.id === id && workspace.sandbox === undefined)?.root,\n // Read per call: the listener starts after the global scope is served.\n serverOrigin: () => {\n if (cockpit === undefined) throw new Error('The headless server is not listening yet.');\n return cockpit.url;\n },\n /**\n * Package readiness and the MCP projection, resolved live from the repository. The\n * context stays until the next read replaces it: the projection names its staged files.\n */\n readRepositorySync: async (id: string) => {\n const workspace = hub.workspaces().find((candidate) => candidate.id === id);\n if (workspace?.sandbox !== undefined)\n throw new Error('A sandboxed workspace is prepared inside its sandbox, not on the host.');\n const root = workspace?.root;\n if (!root) return undefined;\n const environment = rootEnvironment(root);\n const config = loadMajorModesConfig(root, homeDirectory, environment);\n const missing = missingLayerPackageSpecifiers(\n config,\n Object.keys(config.layers),\n createLayerResolvers(root, environment),\n );\n const context = await buildHarnessContext(\n await resolveHarnessOptions({ args: ['--cwd', root], cwd: root, environment }),\n );\n const previous = repositoryContexts.get(root);\n repositoryContexts.set(root, context);\n await previous?.cleanup().catch((error: unknown) => notice(String(error)));\n const status = await syncCheckpoint(\n root,\n workspaceLabel(root, hub.workspaces().find((workspace) => workspace.id === id)?.name),\n false,\n );\n return {\n fresh: missing.length === 0 && status.reasons.length === 0,\n reasons: [\n ...missing.map((specifier) => `configured package is not installed: ${specifier}`),\n ...status.reasons,\n ],\n syncing: status.syncing,\n mcpProjection: context.resources.mcpProjection,\n };\n },\n onNotice: notice,\n ...(computerUse?.permissions === undefined\n ? {}\n : {\n desktopPermissions: {\n authorize: (headers: Headers, change: boolean) =>\n computerUse.authorizePermissions?.(headers, change) === true,\n request: (permission?: string) => computerUse.permissions!(permission),\n },\n }),\n };\n /**\n * A sandboxed workspace's settings, answered on the host while it serves no scope for it, so the person can\n * still see and change them and switch the sandbox off. Reading and writing its `.po` YAML is data only: the host\n * never loads its composition, runs git or executes anything from it. Closed once it runs on the host again.\n */\n const sandboxedSettings = new Map<string, { root: string; handler: PoApiHandler; release: () => void }>();\n const releaseSandboxedSettings = (workspaceId: string): void => {\n sandboxedSettings.get(workspaceId)?.release();\n sandboxedSettings.delete(workspaceId);\n };\n unservedWorkspaceApi = (workspaceId, basePath) => {\n const record = workspaces.list().find((workspace) => workspace.id === workspaceId);\n const held = sandboxedSettings.get(workspaceId);\n if (held !== undefined && (record?.sandbox === undefined || held.root !== record.root))\n releaseSandboxedSettings(workspaceId);\n if (basePath !== SETTINGS_API || record?.sandbox === undefined) return undefined;\n const current = sandboxedSettings.get(workspaceId);\n if (current !== undefined) return current.handler;\n const env = platform.env(record.root);\n const handler = createSettingsApi(env).start({\n ...sharedApiContext,\n scope: 'workspace',\n workspaceId,\n workspaceRoot: record.root,\n cwd: record.root,\n resolveRepository: () => undefined,\n });\n sandboxedSettings.set(workspaceId, {\n root: record.root,\n handler,\n release: () => {\n handler.close();\n void env.cleanup(BACKGROUND_CONTEXT).catch((error: unknown) => notice(String(error)));\n },\n });\n return handler;\n };\n stopSandboxWatches.push(() => {\n for (const workspaceId of sandboxedSettings.keys()) releaseSandboxedSettings(workspaceId);\n });\n const globalDirectoryExisted = await pathExists(hostFiles, globalRoot, BACKGROUND_CONTEXT);\n getOrThrow(await hostFiles.createDir(globalRoot, { recursive: true }, BACKGROUND_CONTEXT));\n if (!globalDirectoryExisted) await nodeHost.setMode(globalRoot, 0o700);\n const globalBundle = await loadComposition(globalRoot, 'global', undefined, 'global');\n // A contained server has no remote access or native push: its host owns both.\n if (sandboxIdentity === undefined) {\n remoteRuntime = createRemoteRuntime({\n homeDirectory,\n registrationToken: token,\n onStateChanged: () => hub.bumpRevision?.('global:remote'),\n onTunnelIntentChanged: (intent) => {\n recoveryTunnel = intent;\n persistRecovery();\n },\n onDeviceDropped: (id) => computerUse?.revokeDevice?.(id),\n reservedPorts: () => [options.webPort],\n bundleTrust: () => webCompositions?.shellTrust(),\n attestHost: (fields) => webCompositions?.attestHost(fields),\n onNotice: notice,\n telemetry,\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-po-token', attachToken);\n return fetch(\n new URL(`${from.pathname}${from.search}`, cockpit.url),\n new Request(request, { headers, redirect: 'manual' }),\n );\n },\n acceptProtocol: (pathname, link, deviceId) => {\n if (!cockpit) throw new Error('The headless protocol listener is not ready.');\n return cockpit.acceptProtocol(pathname, link, {\n 'x-po-api-caller-locality': 'remote',\n 'x-po-api-caller-device-id': deviceId,\n 'x-po-api-caller-step-up': 'not-required',\n });\n },\n });\n const pushCredentials = await loadNativePushCredentials(baseEnvironment, platform.env(baseCwd), notice);\n const pushSender = createNativePushSender({\n ...pushCredentials,\n diagnostic: ({ provider, outcome, status, reason }) =>\n notice(\n `Native push ${provider}: ${outcome}${status === undefined ? '' : ` ${status}`}${reason ? ` ${reason}` : ''}.`,\n ),\n });\n stopNativePush = subscribeNativePush(hub, remoteRuntime.remote, pushSender, notice);\n }\n try {\n // The hub resets its global scope when serving fails, so any retry must bind the registry again.\n const globalScope = await hub.sessionParentScope(undefined);\n // Only the long-lived hub that owns the Po home runs sandboxes: a one-shot automation run binds no registry,\n // so no provider starts a container lifecycle or a clean-stop hook that would stop shared containers.\n if (automation === undefined) await globalScope.bind(PO_WORKSPACE_SANDBOXES_CONTRACT, sandboxes);\n if (sandboxIdentity !== undefined) await globalScope.bind(PO_SANDBOX_IDENTITY_CONTRACT, sandboxIdentity);\n await globalScope.bind(PO_PACKAGE_HEALTH_CONTRACT, { failures: () => [...packageFailures.values()] });\n // Who may reload which scope is Help's call; this only reloads it.\n await globalScope.bind(PO_SELF_IMPROVE_CONTRACT, {\n reload: async ({ scope, sessionId }) => {\n if (scope === 'session') {\n if (reloadSessionPackages === undefined) throw new Error('Session reload is not ready yet.');\n const result = await reloadSessionPackages(sessionId);\n return {\n ...result,\n failed: result.failed.map(({ packageName, reason }) => ({ packageName, reason })),\n };\n }\n const workspaceId = hub.session(sessionId)?.workspaceId;\n const workspace =\n workspaceId === undefined ? undefined : hub.workspaces().find(({ id }) => id === workspaceId);\n if (scope === 'workspace' && (workspace === undefined || !servedOnHost(workspace)))\n throw new Error(`Session '${sessionId}' has no workspace served on this host.`);\n const result = await checkScope(\n scope === 'global' ? globalRoot : workspace!.root,\n scope === 'global' ? { scope: 'global' } : { scope: 'workspace', workspaceId: workspace!.id },\n true,\n );\n return result ?? { installed: [], removed: [], failed: [] };\n },\n refresh: async ({ sessionId, axes }) => {\n if (refreshSessionSelection === undefined) throw new Error('Session refresh is not ready yet.');\n await refreshSessionSelection(sessionId, axes);\n },\n });\n await globalScope.bind(PO_REMOTE_ORIGIN_CONTRACT, {\n current: () => remoteRuntime?.remote.publicOrigin(),\n revision: () => remoteRuntime?.remote.publicOriginRevision() ?? 0,\n });\n failedPackages.delete('global');\n await hub.serveScope(\n {\n ...sharedApiContext,\n scope: 'global',\n requestReceipts: requestReceipts.receipts,\n ...(sandboxIdentity === undefined\n ? { remoteControl: { fetch: (request: Request) => remoteRuntime!.fetchLocal(request) } }\n : {}),\n },\n globalBundle.packages,\n );\n } finally {\n sandboxes.close();\n sandboxProvidersSettled = true;\n }\n // Each provider's own changes (its engine check, a container starting or failing) reach clients live.\n for (const provider of sandboxes.list())\n if (provider.onStatusChange !== undefined) stopSandboxWatches.push(provider.onStatusChange(refreshWorkspaces));\n bundler.commitScope(\n 'global',\n globalRoot,\n 'global',\n globalBundle.entries,\n takeFailedPackages('global', globalBundle.packages),\n );\n await refreshWebBuild();\n await syncCheckpoint(globalRoot, 'The global scope');\n // Server start covers app launch and Po updates: sync exits at once when nothing changed.\n if (!backgroundSync.syncing) await backgroundSync.request('server start');\n const admissions = new Map<string, Promise<HeadlessWorkspace & { available: boolean }>>();\n // A member checkout is any checkout other than its workspace root, such as a worktree.\n const isMemberCheckout = async (from: string, workspace: { root: string }): Promise<boolean> =>\n (await resolveWorkspaceRoot(from)) !== workspace.root;\n admitWorkspace = async (from, requestedName) => {\n const directory = await hostFiles.fileInfo(from, BACKGROUND_CONTEXT);\n if (!directory.ok || directory.value.kind !== 'directory') throw new Error(`Folder not found: ${from}`);\n const checkoutRoot = await resolveWorkspaceRoot(from);\n // A sandboxed workspace is registered and nothing else: the host never reads or writes its marker (it lives\n // behind the repository's `.git` pointer, which the sandbox controls), loads its composition, or serves its\n // scope. It is available only while the host is linked to its sandbox, which then runs its sessions. An\n // exact root match is settled before the marker is read.\n const admitSandboxed = (sandboxed: WorkspaceRecord): HeadlessWorkspace & { available: boolean } => {\n const requested = requestedName?.trim() || undefined;\n const record =\n requested === undefined || requested === sandboxed.name ? sandboxed : { ...sandboxed, name: requested };\n // The stored sandbox survives: `add` keeps it when the incoming record omits the key.\n if (record !== sandboxed)\n workspaces.add({\n id: record.id,\n root: record.root,\n ...(record.name === undefined ? {} : { name: record.name }),\n });\n const available = router?.connected(record.id) === true;\n const entry = { ...hubEntry(record, available), available };\n const known = hub.workspaces().find((workspace) => workspace.id === record.id);\n if (\n known === undefined ||\n (known.available !== false) !== available ||\n known.name !== entry.name ||\n known.sandbox !== entry.sandbox ||\n !sameSandboxStatus(known, entry)\n ) {\n if (known === undefined) notice(`Workspace '${record.id}' runs in sandbox '${String(record.sandbox)}'.`);\n hub.registerWorkspace(entry);\n }\n return entry;\n };\n const sandboxedHere = workspaces\n .list()\n .find((workspace) => workspace.sandbox !== undefined && workspace.root === checkoutRoot);\n if (sandboxedHere !== undefined) return admitSandboxed(sandboxedHere);\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 if (record?.sandbox !== undefined) return admitSandboxed(record);\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 await syncCheckpoint(root, workspaceLabel(root, name));\n if (renamed) {\n workspaces.add({ id, root, ...named });\n hub.registerWorkspace(hubEntry({ id, root, ...named }, 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(hubEntry({ id, root, ...named }, false));\n const admission = (async () => {\n // Admission only reads what sync prepared; a package it has not prepared yet is left\n // out with a warning and a background sync, and mounts when that sync finishes.\n const bundle = await loadComposition(root, 'workspace', undefined, `workspace:${id}`);\n failedPackages.delete(`workspace:${id}`);\n await hub.serveScope(\n {\n ...sharedApiContext,\n scope: 'workspace',\n workspaceId: id,\n workspaceRoot: root,\n cwd: root,\n resolveRepository: (requestedId) => (requestedId === id ? root : undefined),\n },\n bundle.packages,\n );\n servedWorkspaces.add(id);\n failedAdmissions.delete(id);\n bundler.commitScope(\n `workspace:${id}`,\n root,\n 'workspace',\n bundle.entries,\n takeFailedPackages(`workspace:${id}`, bundle.packages),\n );\n // A missing web build leaves the workspace usable; the next checkpoint picks one up.\n try {\n await refreshWebBuild();\n const mount: ScopeMount = { scope: 'workspace', workspaceId: id };\n if (publishSharedMount(mount, root)) hub.touchCompositions?.([mount]);\n } catch (error) {\n notice(\n `Workspace '${id}' web build check failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n await syncCheckpoint(root, workspaceLabel(root, name));\n // Serving the scope registered it without its sandbox state.\n refreshWorkspace(id);\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 } else if (!servedWorkspaces.has(id)) failedAdmissions.set(id, root);\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.cwd;\n const root = await resolveWorkspaceRoot(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(hubEntry(workspace, false));\n try {\n // A sandboxed workspace is never resolved here; admission registers it unavailable.\n const root = workspace.sandbox === undefined ? await resolveWorkspaceRoot(workspace.root) : 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: LoadedServerPackages,\n mcpBundle: LoadedMcpPlugins,\n identity: {\n sessionId: string;\n sessionName: string;\n parentSessionId?: string;\n sessionProvenance?: string;\n interaction?: PoHubSessionCreateRequest['interaction'];\n },\n workspace: { id: string; root: string },\n explicit: {\n pinned: readonly PinnedSelectionAxis[];\n minorModes?: readonly string[];\n allowedTools?: readonly string[];\n initialFastMode?: boolean;\n initialAgentLocked?: boolean;\n resume?: boolean;\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 // Composed from this session's own root, environment and selection, never from the\n // process, and without the bootstrap: no PO_COMPOSED, no composition claim.\n const sessionEnvironment = context.environment;\n // The prompt-cache namespace keys on this, so publish it before the host reads the state.\n updateHarnessState(\n {\n compositionFingerprint: resolveExtensionComposition({\n majorMode: policyOptions.majorMode,\n layers: [...context.selectedLayers],\n majorModesConfig: loadMajorModesConfig(\n policyOptions.configRoot ?? policyOptions.repoRoot,\n homeDirectory,\n sessionEnvironment,\n ),\n resolvers: createLayerResolvers(policyOptions.configRoot ?? policyOptions.repoRoot, sessionEnvironment),\n tolerateUnsynced: true,\n }).fingerprint,\n },\n sessionEnvironment,\n );\n return {\n cwd: policyOptions.cwd,\n repoRoot: policyOptions.repoRoot,\n platform,\n sessionId: identity.sessionId,\n workspaceId: workspace.id,\n groupingRoot: workspace.root,\n sessionName: identity.sessionName,\n ...(explicit.initialFastMode === undefined ? {} : { initialFastMode: explicit.initialFastMode }),\n ...(explicit.initialAgentLocked === undefined ? {} : { initialAgentLocked: explicit.initialAgentLocked }),\n ...(explicit.resume ? { resume: true } : {}),\n ...(identity.parentSessionId === undefined ? {} : { parentSessionId: identity.parentSessionId }),\n ...(identity.sessionProvenance === undefined ? {} : { sessionProvenance: identity.sessionProvenance }),\n ...(identity.interaction === undefined ? {} : { interaction: identity.interaction }),\n agentArgs: policyOptions.piArgs,\n environment: Object.freeze({ ...context.environment }),\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: async () => {\n const environment = { ...baseEnvironment };\n for (const key of [HARNESS_STATE_POINTER, ...Object.values(HARNESS_STATE_KEYS)]) delete environment[key];\n const defaults = await 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.entries,\n providerOverrides: () => selectedServerProviderOverrides(bundle.packages, sessionEnvironment, notice),\n mcpPlugins: mcpBundle.plugins,\n ...(modelGateway === undefined\n ? {}\n : { modelDependencies: (hostOptions) => modelGateway.modelDependencies(hostOptions) }),\n resolveSelection: (requested) => {\n const config = loadMajorModesConfig(\n policyOptions.configRoot ?? policyOptions.repoRoot,\n policyOptions.homeDirectory,\n policyOptions.environment ?? baseEnvironment,\n );\n return {\n ...requested,\n activeLayers: resolveLayers(config, requested.majorMode),\n };\n },\n telemetry,\n onNotice: notice,\n };\n };\n\n mountSessionApis = async (sessionOptions, host) =>\n serveSessionApis({\n // Workspace and global contracts reach the session's packages as native services.\n parentScope: await hub.sessionParentScope(sessionOptions.workspaceId),\n sessionId: sessionOptions.sessionId,\n platform,\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 // Read per call: shares follow the remote runtime's current tunnel.\n shareFile: (filePath, label) =>\n remoteRuntime === undefined\n ? Promise.reject(new Error(PO_SHARE_FILE_REMOTE_OFF_MESSAGE))\n : remoteRuntime.fileShares.mint({\n sessionId: sessionOptions.sessionId,\n cwd: sessionOptions.cwd,\n path: filePath,\n label,\n }),\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) =>\n computerUse.authorizeSession?.(sessionOptions.sessionId, headers) === true ||\n computerUse.authorize?.(headers) === true,\n authorizeRecording: (headers: Headers) =>\n computerUse.authorizeRecording?.(sessionOptions.sessionId, headers) === true,\n authorizeActivation: (headers: Headers) => computerUse.authorizeActivation?.(headers) === true,\n claim: (headers?: Headers) => computerUse.claimSession?.(sessionOptions.sessionId, headers),\n fetchRecording: (artifactId: string, range: string) =>\n computerUse.readRecording?.(\n { sessionId: sessionOptions.sessionId, cwd: sessionOptions.cwd },\n artifactId,\n range,\n ) ?? Promise.resolve(Response.json({ error: 'Not found.' }, { status: 404 })),\n subscribe: (listener: () => void) =>\n computerUse.subscribe?.(listener, sessionOptions.sessionId) ?? (() => undefined),\n },\n }),\n hubToken: token,\n sessionService: hub.sessionService,\n mediaArbitration,\n executionBudget,\n editPresence: hub.editPresence,\n peerAgents,\n pluginRegistry: hub.pluginRegistry,\n apis: [],\n packages: pendingSessions.get(sessionOptions.sessionId)?.bundle.packages ?? [],\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 preparePackages: (root) => {\n sessionServiceRoots.set(host, root);\n host.preparePackages(root);\n },\n activatePackages: host.activatePackages,\n canDispatch: host.canDispatch,\n telemetry,\n onNotice: notice,\n });\n\n requestSessionApi = async (scope, request) => {\n // A container session's panels call the container's own HTTP API, with its token.\n if (router?.mirror(scope.sessionId) !== undefined) return router.requestSessionApi(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://po.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 // An unclean boot restores recorded identities, never an extra random launch session.\n if (!options.noSession && recycled === undefined) {\n const initialOptions = await resolveHarnessOptions({\n args: resolved.agentArgs,\n cwd: baseCwd,\n environment: baseEnvironment,\n });\n const initialWorkspace = await admitWorkspace(initialOptions.repoRoot);\n launchWorkspaceId = initialWorkspace.id;\n // A sandboxed folder's launch session runs in its sandbox; nothing below may run on the host.\n if (initialWorkspace.sandbox !== undefined) {\n if (router === undefined) throw new Error(SANDBOX_UNREACHABLE);\n // The model, thinking level and selection the launch arguments ask for go with it.\n await router.openSession(initialWorkspace.id, {\n cwd: baseCwd,\n name: resolved.identity.sessionName,\n signal,\n ...launchSessionRequest(resolved.agentArgs, initialOptions),\n });\n } else {\n harnessContext = await buildHarnessContext(\n await resolveHarnessOptions({ args: resolved.agentArgs, cwd: baseCwd, environment: baseEnvironment }),\n harnessTelemetry,\n );\n const activeHarnessContext = harnessContext;\n try {\n const loadBundle = () =>\n loadComposition(activeHarnessContext.options.repoRoot, 'session', {\n root: activeHarnessContext.options.repoRoot,\n majorMode: activeHarnessContext.options.majorMode,\n activeLayers: activeHarnessContext.selectedLayers,\n });\n const initialBundle = await loadBundle();\n const initialMcpBundle = await loadSessionMcp(harnessContext.options.repoRoot, {\n majorMode: harnessContext.options.majorMode,\n activeLayers: harnessContext.selectedLayers,\n });\n pendingSessions.set(resolved.identity.sessionId, {\n cleanup: () => activeHarnessContext.cleanup(),\n bundle: initialBundle,\n mcpBundle: initialMcpBundle,\n loadBundle,\n });\n const created = await hub.create(\n sessionHostOptions(harnessContext, initialBundle, initialMcpBundle, resolved.identity, initialWorkspace),\n );\n recordLiveSession(created, harnessContext.options.repoRoot, initialWorkspace.root);\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\n const reservedOpens = new Map<string, Promise<PoHubSessionScope>>();\n /**\n * The sandboxed workspace this session would join, decided before any host preparation. The\n * inherited workspace (placement or parent link) wins; otherwise the checkout's own root is\n * matched without reading its marker, and only then the marker names an owner.\n */\n const sandboxedWorkspaceOf = async (\n request: PoHubSessionCreateRequest,\n groupingWorkspaceId?: string,\n ): Promise<string | undefined> => {\n const records = workspaces.list();\n const inherited =\n groupingWorkspaceId ??\n (request.parentSessionId\n ? (hub.session(request.parentSessionId)?.workspaceId ??\n [...openSessions.list(), ...(router?.dormant() ?? [])].find(\n (record) => record.sessionId === request.parentSessionId,\n )?.workspaceId)\n : undefined);\n const owner = inherited ?? (await checkoutWorkspaceId(records, request.cwd));\n return records.find((record) => record.id === owner && record.sandbox !== undefined)?.id;\n };\n openSession = async (request, sessionId, groupingWorkspaceId) => {\n request.signal?.throwIfAborted();\n const parent =\n request.parentSessionId === undefined\n ? undefined\n : (hub.session(request.parentSessionId) ??\n [...openSessions.list(), ...(router?.dormant() ?? [])].find(\n (record) => record.sessionId === request.parentSessionId,\n ));\n // A child cannot elevate an unattended parent, including across the sandbox boundary.\n if (parent?.interaction === 'unattended') request = { ...request, interaction: 'unattended' };\n // A sandboxed workspace's sessions run in its sandbox: the host prepares nothing and records nothing.\n const sandboxed = await sandboxedWorkspaceOf(request, groupingWorkspaceId);\n if (sandboxed !== undefined) {\n if (router === undefined) throw new Error(SANDBOX_UNREACHABLE);\n return router.openSession(sandboxed, request, sessionId);\n }\n if (\n request.workflowContext !== undefined &&\n (request.reservationId !== undefined ||\n sessionId !== undefined ||\n request.parentSessionId !== request.workflowContext.run.ownerSessionId ||\n request.sessionProvenance !== WORKFLOW_STEP_SESSION_PROVENANCE)\n ) {\n throw new Error('Workflow context requires a new, unreserved step session owned by its workflow session.');\n }\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 interaction: request.interaction,\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 explicit = sessionSelectionArgs(request);\n const openStartedAt = Date.now();\n const start = (async (): Promise<PoHubSessionScope> => {\n // Snapshot only for creation. Explicit-ID resumes retain their own durable Fast state.\n const parent =\n request.parentSessionId !== undefined && (sessionId === undefined || request.reservationId !== undefined)\n ? sessionManager.get(request.parentSessionId)\n : undefined;\n let initialFastMode: boolean | undefined;\n if (parent !== undefined) {\n const state = await parent.runtime.readState();\n if (typeof state.fastMode !== 'boolean') throw new Error('Parent Fast mode must be a boolean.');\n initialFastMode = state.fastMode;\n }\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 if (workspace.sandbox !== undefined) throw new Error(SANDBOX_UNREACHABLE);\n // Shared scopes reload on watched changes, never here. The session's own packages, MCP\n // plugins and Pi factories load below from the current URLs; running sessions keep\n // the set they were created with until restarted.\n await syncCheckpoint(globalRoot, 'The global scope');\n if (inheritedWorkspaceId !== undefined)\n // Without an inherited workspace, admitWorkspace above already ran this checkpoint.\n await syncCheckpoint(workspace.root, workspaceLabel(workspace.root, workspace.name));\n // A member checkout composes from its workspace's configuration.\n const member = await isMemberCheckout(request.cwd, workspace);\n const childContext = await buildHarnessContext(\n await 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 // A member checkout (a worktree) has no node_modules or builds of its own, so its\n // packages, local ones included, load from the workspace checkout that sync prepared.\n const compositionRoot = childContext.options.configRoot ?? childContext.options.repoRoot;\n const loadBundle = () =>\n loadComposition(compositionRoot, 'session', {\n root: compositionRoot,\n majorMode: childContext.options.majorMode,\n activeLayers: childContext.selectedLayers,\n });\n const bundle = await loadBundle();\n const mcpBundle = await loadSessionMcp(compositionRoot, {\n majorMode: childContext.options.majorMode,\n activeLayers: childContext.selectedLayers,\n });\n request.signal?.throwIfAborted();\n pendingSessions.set(identity.sessionId, {\n cleanup: () => childContext.cleanup(),\n bundle,\n mcpBundle,\n loadBundle,\n });\n const created = await hub.create({\n ...sessionHostOptions(childContext, bundle, mcpBundle, identity, workspace, {\n pinned: explicit.pinned,\n ...(initialFastMode === undefined ? {} : { initialFastMode }),\n ...(request.reservationId === undefined ? {} : { initialAgentLocked: true }),\n ...(sessionId !== undefined && request.reservationId === undefined ? { resume: true } : {}),\n ...(request.selection?.minorModes === undefined ? {} : { minorModes: request.selection.minorModes }),\n ...(request.tools === undefined ? {} : { allowedTools: request.tools }),\n }),\n ...(request.workflowContext === undefined ? {} : { workflowContext: request.workflowContext }),\n });\n request.signal?.throwIfAborted();\n recordLiveSession(created, childContext.options.repoRoot, workspace.root);\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 void start\n .then(\n () => 'success',\n () => 'failure',\n )\n .then((outcome) =>\n telemetry.recordEvent('po_server.session_open', { duration_ms: Date.now() - openStartedAt, outcome }),\n )\n .catch((error: unknown) => rawNotice(`session open telemetry failed: ${String(error)}`));\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 // A contained server's host creates and closes its sessions over the protocol socket.\n if (sandboxIdentity !== undefined)\n registerContainedSessionMethods(hub.pluginRegistry, {\n open: (request, sessionId) => openSession(request, sessionId),\n close: (sessionId, keepDormant) =>\n hub.closeSession(sessionId, keepDormant ? { keepDormant: true } : undefined),\n // A host session the host moved in here after closing it: listed dormant, like one closed here.\n adopt: async (record) => {\n if (record.workspaceId !== sandboxIdentity.workspaceId)\n throw new Error('The adopted session belongs to another workspace.');\n if (hub.session(record.sessionId) !== undefined) return;\n if (!openSessions.add(record)) throw new Error('The adopted session could not be durably recorded.');\n hub.notifyDormantChanged(record.sessionId);\n },\n });\n // The checkpoint for package installs and removals (upm add/remove), finished syncs and\n // watched changes: every root recomputes, and each scope re-imports only moved URLs.\n const checkAllScopes = (source: ScopeCheckSource = 'upm'): Promise<void> =>\n trackJob('scope_check', async () => {\n const started = performance.now();\n let roots = 1;\n bundler.invalidate();\n syncCheckpoints.invalidate();\n await checkScope(globalRoot, { scope: 'global' });\n for (const workspace of hub.workspaces())\n if (servedOnHost(workspace)) {\n roots += 1;\n await checkScope(workspace.root, { scope: 'workspace', workspaceId: workspace.id });\n }\n // A retry that fails records the workspace again, for the next check rather than this loop.\n const retries = new Map(failedAdmissions);\n failedAdmissions.clear();\n for (const [id, root] of retries) {\n // A workspace removed since it failed stays removed.\n if (!workspaces.list().some((workspace) => workspace.id === id)) continue;\n await admitWorkspace(root).catch((error: unknown) =>\n notice(`Workspace '${root}' is still unavailable and retries at the next check: ${errorMessage(error)}`),\n );\n }\n void telemetry\n .recordEvent('po_server.scope_check', {\n source,\n roots,\n duration_ms: Math.round(performance.now() - started),\n })\n .catch((error: unknown) => notice(`scope check telemetry failed: ${String(error)}`));\n });\n onExtensionCheck?.(() => checkAllScopes('upm'));\n /**\n * Reloads one session's own packages between tool rounds: changed and added packages install\n * with per-package rollback, removed ones are disposed, then the selection gates on the new set.\n * ponytail: provider overrides and MCP plugins keep the set the session opened with; reopen the\n * session to change those.\n */\n reloadSessionPackages = async (sessionId: string) => {\n const artifacts = sessionArtifacts.get(sessionId);\n const host = baseSessionManager.get(sessionId);\n const reconcile = artifacts?.apis.reconcile;\n if (artifacts === undefined || host?.reloadPackages === undefined || reconcile === undefined)\n throw new Error(`Session '${sessionId}' cannot reload its packages here.`);\n return host.runtime.runAtToolBoundary(async () => {\n bundler.invalidate();\n bundler.poisoned.clear();\n const bundle = await artifacts.loadBundle();\n const declared = bundle.entries\n .filter((entry) => entry.scopes.includes('session'))\n .map((entry) => entry.packageName);\n const result = await reconcile(bundle.packages, declared);\n artifacts.bundle = bundle;\n await host.reloadPackages?.(bundle.entries, result.installed);\n return result;\n });\n };\n refreshSessionSelection = async (sessionId, axes) => {\n const host = baseSessionManager.get(sessionId);\n if (host?.refreshSelection === undefined)\n throw new Error(`Session '${sessionId}' cannot refresh its selection here.`);\n await host.runtime.runAtToolBoundary(() => host.refreshSelection!(axes));\n };\n /**\n * A finished background sync goes through the same live reload: the read-only refresh\n * republishes a changed build, and each scope re-imports only packages whose URLs moved.\n * Session packages and the MCP app switch at the next session. The warnings are re-read\n * without requesting another sync, so a sync that could not fix a root never loops.\n */\n pickUpSync = async (source: ScopeCheckSource = 'sync') => {\n await checkAllScopes(source);\n await syncCheckpoint(globalRoot, 'The global scope', false);\n for (const workspace of hub.workspaces())\n if (servedOnHost(workspace))\n await syncCheckpoint(workspace.root, workspaceLabel(workspace.root, workspace.name), false);\n };\n pickUpChange = (source) => {\n void pickUpSync(source).catch((error: unknown) => notice(`Extension reload failed: ${String(error)}`));\n };\n });\n\n const workspaceResumes = new Map<string, Promise<string>>();\n // History is listed on every page view, so each unreadable file is reported once per server.\n const reportedUnreadable = new Set<string>();\n const unreadableHistory = (sessionId: string, error: unknown): void => {\n if (reportedUnreadable.has(sessionId)) return;\n reportedUnreadable.add(sessionId);\n notice(\n `Saved session ${sessionId} is hidden from History: ${error instanceof Error ? error.message : String(error)}`,\n );\n };\n const savedHistory = async (workspaceId: string) => {\n const root = hub.workspaces().find((workspace) => workspace.id === workspaceId && servedOnHost(workspace))?.root;\n if (!root) throw new Error('Workspace not found.');\n return listSavedSessionRecords(\n platform.sessions,\n root,\n new Set(hub.snapshot().map((active) => active.id)),\n workspaceId,\n unreadableHistory,\n );\n };\n const validateExecution = async (target: SavedSessionExecution, workspaceId: string): Promise<void> => {\n const root = hub.workspaces().find((workspace) => workspace.id === workspaceId && servedOnHost(workspace))?.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 ((await resolveWorkspaceRoot(target.cwd)) !== target.repoRoot)\n throw new Error('Saved session checkout is unavailable.');\n };\n const reviving = new Map<string, Promise<void>>();\n const reviveRecord = (record: OpenSessionRecord): Promise<void> => {\n // A container session wakes in its container; its mirror appears once it runs.\n if (router?.owns(record.sessionId) === true) return router.revive(record.sessionId);\n const pending = reviving.get(record.sessionId);\n if (pending) return pending;\n if (sessionManager.get(record.sessionId)) return Promise.resolve();\n // A record taken back from a sandbox whose folder was a container worktree.\n const opening = (async () => {\n if (!(await pathExists(hostFiles, record.cwd, BACKGROUND_CONTEXT))) throw new Error(CONTAINER_WORKTREE_GONE);\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 && (await resolveWorkspaceRoot(record.cwd)) !== record.repoRoot)\n throw new Error('The session checkout has changed.');\n await openSession(\n {\n cwd: record.cwd,\n signal,\n name: record.name,\n ...(record.parentSessionId === undefined ? {} : { parentSessionId: record.parentSessionId }),\n ...(record.sessionProvenance === undefined ? {} : { sessionProvenance: record.sessionProvenance }),\n ...(record.interaction === undefined ? {} : { interaction: record.interaction }),\n },\n record.sessionId,\n record.workspaceId,\n );\n // Groups edited while dormant live only on the record; the journal adopts them now.\n const groups = record.groups ?? [];\n const opened = hub.session(record.sessionId)?.groups ?? [];\n if (groups.length !== opened.length || groups.some((group, index) => opened[index] !== group))\n await hub.runtime(record.sessionId)?.setGroups(groups);\n })();\n reviving.set(record.sessionId, opening);\n void opening.finally(() => reviving.delete(record.sessionId)).catch(() => undefined);\n return opening;\n };\n /** Host records, then the dormant sessions each linked container lists. */\n const allDormant = (): readonly OpenSessionRecord[] => [...openSessions.list(), ...(router?.dormant() ?? [])];\n dormantSessions = allDormant;\n reviveSession = (sessionId) => {\n const record = allDormant().find((item) => item.sessionId === sessionId);\n return record ? reviveRecord(record) : Promise.reject(new Error('The session has no saved record.'));\n };\n cockpit = await serveHeadlessServer({\n port: options.webPort,\n ...(options.host === undefined ? {} : { host: options.host }),\n // A contained server answers only its host, which holds the token.\n ...(sandboxIdentity === undefined\n ? {}\n : { publicRoutes: false, webSocketMaxPayload: CONTAINED_MAX_PAYLOAD_BYTES }),\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 setWorkspaceSandbox: async (workspaceId, sandbox) => {\n const record = workspaces.list().find((workspace) => workspace.id === workspaceId);\n if (record === undefined) return { error: 'Workspace not found.' };\n if (sandbox !== null && sandboxes.get(sandbox) === undefined)\n return { error: `Sandbox provider '${sandbox}' is not registered.` };\n // Refuse before any session moves: a sandbox that cannot start would strand them until it comes back.\n const blocked =\n sandbox === null || sandbox === record.sandbox ? undefined : sandboxes.get(sandbox)?.availability?.();\n if (blocked !== undefined && !blocked.available) return { error: blocked.reason };\n const previous = record.sandbox;\n const switchingOff = previous !== undefined && previous !== (sandbox ?? undefined);\n const switchingOn = sandbox !== null && sandbox !== previous;\n const offProvider = switchingOff ? handoffProvider(sandboxes.get(previous)) : undefined;\n const onProvider = switchingOn ? handoffProvider(sandboxes.get(sandbox)) : undefined;\n const failed = (error: unknown): void => {\n sandboxTransitions.set(workspaceId, { sandboxState: 'failed', sandboxReason: errorMessage(error) });\n refreshWorkspace(workspaceId);\n };\n // Sessions follow the workspace out: the host lets go of its mirrors, the sandbox stops, and only then do its\n // sessions move back to the host.\n if (offProvider !== undefined && handoff !== undefined) {\n sandboxTransitions.set(workspaceId, { sandboxState: 'stopping' });\n refreshWorkspace(workspaceId);\n try {\n await router?.release(workspaceId);\n for (const sessionId of await handoff.switchOff(record, offProvider)) hub.notifyDormantChanged(sessionId);\n } catch (error) {\n failed(error);\n // Linked again if its sandbox still runs.\n router?.start();\n return { error: `The workspace's sessions could not leave its sandbox: ${errorMessage(error)}` };\n }\n }\n sandboxTransitions.delete(workspaceId);\n // Recorded before the handover, so no new session of the workspace starts on the host meanwhile.\n workspaces.setSandbox(workspaceId, sandbox ?? undefined);\n const updated = workspaces.list().find((workspace) => workspace.id === workspaceId) ?? record;\n // A sandboxed workspace is unavailable on the host until its sandbox links. A cleared one is admitted again\n // as a local workspace.\n if (updated.sandbox !== undefined) {\n if (onProvider !== undefined && handoff !== undefined)\n sandboxTransitions.set(workspaceId, { sandboxState: 'starting' });\n const entry = hubEntry(updated, router?.connected(workspaceId) === true);\n hub.registerWorkspace(entry);\n if (onProvider !== undefined && handoff !== undefined) {\n // Saved host sessions and their records move into the sandbox, then it starts. Live host sessions follow\n // as they close; the host scope stays for them, without reloads.\n try {\n for (const sessionId of await handoff.switchOn(updated, onProvider)) hub.notifySessionRemoved(sessionId);\n } catch (error) {\n failed(error);\n return { error: `The workspace's sandbox did not start: ${errorMessage(error)}` };\n }\n // Starting until the host links to it, then running.\n router?.start();\n }\n return { workspace: hub.workspaces().find((workspace) => workspace.id === workspaceId) ?? entry };\n }\n if (servedWorkspaces.has(workspaceId)) {\n const entry = hubEntry(updated, true);\n hub.registerWorkspace(entry);\n return { workspace: entry };\n }\n // Registered unavailable first, so admission serves the scope instead of answering the sandboxed entry.\n hub.registerWorkspace(hubEntry(updated, false));\n const admitted = await admitWorkspace(updated.root);\n return { workspace: hub.workspaces().find((workspace) => workspace.id === workspaceId) ?? admitted };\n },\n workspaceHistory: async (workspaceId) =>\n router?.contains(workspaceId) === true\n ? ((await router.history(workspaceId)) as Awaited<ReturnType<typeof savedHistory>>[number]['summary'][])\n : (await savedHistory(workspaceId)).map((record) => record.summary),\n resumeWorkspaceSession: async (workspaceId, targetSessionId) => {\n if (router?.contains(workspaceId) === true) return router.resumeWorkspace(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)\n throw new Error('Saved Pi 1.0 session not found in this workspace. Earlier sessions cannot be resumed.');\n if (!(await pathExists(hostFiles, target.execution.cwd, BACKGROUND_CONTEXT)))\n throw new Error(CONTAINER_WORKTREE_GONE);\n await validateExecution(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 ...(target.execution.interaction === undefined ? {} : { interaction: target.execution.interaction }),\n },\n target.summary.id,\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 // A container session's history lives in its container.\n if (router?.mirror(session.id) !== undefined)\n return router.sessionHistory(session.id) as ReturnType<typeof listSavedSessions>;\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 platform.sessions,\n workspaceRoot,\n new Set(hub.snapshot().map((active) => active.id)),\n session.workspaceId,\n unreadableHistory,\n );\n },\n readDormantTranscript: async (record, request, context) => {\n // A dormant container session's transcript is read in its container.\n if (router?.owns(record.sessionId) === true) return router.readTranscript(record.sessionId, request);\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 = await resolveWorkspaceRoot(record.cwd);\n if (record.repoRoot !== undefined && record.repoRoot !== owner)\n throw new Error('Saved transcript checkout has changed.');\n return readSqliteTranscript(platform.sessions, record.sessionId, request, context, {\n sessionId: record.sessionId,\n workspaceRoot: owner,\n workspaceId: record.workspaceId,\n groupingRoot: workspaceRoot,\n });\n },\n restartSession: async (session) => {\n if (router?.mirror(session.id) !== undefined) {\n await router.restart(session.id);\n return;\n }\n const record = openSessions.list().find((entry) => entry.sessionId === session.id);\n const workspaceRoot = hub\n .workspaces()\n .find((workspace) => workspace.id === session.workspaceId && workspace.available !== false)?.root;\n if (!workspaceRoot) throw new Error('Session workspace not found.');\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 ...(session.interaction === undefined ? {} : { interaction: session.interaction }),\n },\n session.id,\n 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 if (router?.mirror(session.id) !== undefined) return router.resume(session.id, 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)\n throw new Error('Saved Pi 1.0 session not found in this workspace. Earlier sessions cannot be resumed.');\n await validateExecution(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 ...(target.execution.interaction === undefined ? {} : { interaction: target.execution.interaction }),\n },\n target.summary.id,\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: allDormant,\n removeDormantSession: (record: OpenSessionRecord) => removeSessionOutputs(record.sessionId),\n removeSessionFiles: removeSessionOutputs,\n setDormantGroups: async (record: OpenSessionRecord, groups: readonly string[]) => {\n if (router?.owns(record.sessionId) === true) return router.setDormantGroups(record.sessionId, groups);\n if (!openSessions.add({ ...record, groups: [...groups] }))\n throw new Error('The session groups could not be durably recorded.');\n },\n reviveSession: reviveRecord,\n requestAsset: (request) => webCompositions?.request(request) ?? Promise.resolve(undefined),\n compositions: () => {\n // A sandboxed workspace has no host composition, and its folder is never read here.\n const workspaces = hub.workspaces().filter((workspace) => workspace.sandbox === undefined);\n const decision = {\n cwd: baseCwd,\n launchWorkspaceId,\n workspaces,\n homeDirectory,\n environment: baseEnvironment,\n notice,\n };\n return {\n global: webCompositions?.get({ scope: 'global' }),\n nativeGlobal: webCompositions?.getNative({ scope: 'global' }),\n nativeApp: webCompositions?.apps(),\n publicKey: webCompositions?.publicKey(),\n shell: webCompositions?.shellTrust(),\n template: resolveWebTemplateDecision(decision),\n nativeTemplate: resolveWebTemplateDecision({ ...decision, host: 'native' }),\n workspaces: hub.workspaces().map((workspace) =>\n workspace.sandbox === undefined\n ? {\n ...workspace,\n webComposition: webCompositions?.get({ scope: 'workspace', workspaceId: workspace.id }),\n nativeComposition: webCompositions?.getNative({ scope: 'workspace', workspaceId: workspace.id }),\n }\n : // Listed with no host plugins, so its sessions (mirrors with global compositions) still mount.\n { ...workspace, webComposition: null, nativeComposition: null },\n ),\n };\n },\n telemetry,\n onNotice: notice,\n });\n notice(`protocol on ${cockpit.url}/api/ws`);\n // Containers that run or were taken back show their sessions, live and dormant, through mirrors.\n router?.start();\n let resolveShutdown!: (exitCode: number) => void;\n const shutdown = new Promise<number>((resolve) => {\n resolveShutdown = resolve;\n });\n requestRestart = () => {\n // Only sessions live right now reopen; dormant ones stay dormant.\n const ids = openSessions\n .list()\n .map((record) => record.sessionId)\n .filter((id) => sessionManager.get(id) !== undefined);\n persistRecovery = () => {};\n const details = {\n crashRestores: restorePlan.crashRestores,\n ...(recoveryTunnel === undefined ? {} : { tunnel: recoveryTunnel }),\n };\n recoveryWrites = recoveryWrites.then(async () => {\n try {\n await writeRecycleFile(serverDirectory, ids, details);\n } catch (error) {\n notice(`Could not write the recycle file: ${error instanceof Error ? error.message : String(error)}`);\n }\n notice(`Restarting at idle to release superseded extension versions (${String(ids.length)} sessions reopen).`);\n resolveShutdown(RESTART_EXIT_CODE);\n });\n };\n persistRecovery();\n if (restorePlan.blocked)\n notice(\n 'Automatic crash restore paused after two attempts in 15 minutes. Sessions remain dormant; use Wake to retry.',\n );\n const stop = (): void => {\n cleanShutdown = signal.reason !== 'crash';\n resolveShutdown(0);\n };\n signal.addEventListener('abort', stop, { once: true });\n if (signal.aborted) stop();\n // Serial recovery starts only after listen. Wake joins the same per-session promise.\n recovering = true;\n const restoredSessions = reopenRecycledSessions(\n serverDirectory,\n async (sessionId) => {\n if (signal.aborted || shuttingDown) return;\n const record = openSessions.list().find((entry) => entry.sessionId === sessionId);\n try {\n if (record === undefined) throw new Error('its record is gone.');\n await reviveRecord(record);\n } catch (error) {\n recoverySessionIds.delete(sessionId);\n throw error;\n } finally {\n persistRecovery();\n }\n },\n (sessionId, error) =>\n notice(\n `Session '${sessionId}' did not reopen after the restart: ${error instanceof Error ? error.message : String(error)}`,\n ),\n { sessionIds: restorePlan.sessionIds, removeAfter: false },\n ).catch((error: unknown) => notice(`Crash restore failed: ${String(error)}`));\n let restoredTunnel: Promise<unknown> | undefined;\n if (tunnelToRestore !== undefined && !signal.aborted) {\n restoredTunnel = remoteRuntime\n ?.restoreTunnel(tunnelToRestore)\n .then((result) => {\n if (!result.ok) notice(`Remote access did not restore: ${result.error}`);\n })\n .catch((error: unknown) => notice(`Remote access did not restore: ${String(error)}`))\n .finally(() => {\n recoveryTunnel = remoteRuntime?.tunnelIntent();\n persistRecovery();\n });\n }\n recoveryWork = Promise.allSettled([restoredSessions, restoredTunnel]).then(() => {\n recovering = false;\n idleRestart.poke();\n });\n if (automation !== undefined && !signal.aborted) {\n void automation({\n hub,\n sessionHost: (sessionId) => sessionManager.get(sessionId),\n openSession: (request) => openSession(request),\n closeSession: (sessionId) => closeManagedSession(sessionId),\n signal,\n })\n .then((exitCode) => resolveShutdown(exitCode))\n .catch((error: unknown) => {\n notice(`Native automation failed: ${error instanceof Error ? error.message : String(error)}`);\n resolveShutdown(1);\n });\n }\n try {\n const exitCode = await shutdown;\n if (exitCode === 0 && signal.reason !== 'crash') cleanShutdown = true;\n return exitCode;\n } finally {\n signal.removeEventListener('abort', stop);\n }\n } finally {\n shuttingDown = true;\n persistRecovery = () => {};\n await recoveryWrites;\n const cleanUserStop = isCleanUserStop(cleanShutdown, signal);\n // Started first so container stops overlap the rest of shutdown, and awaited before the global scope unloads.\n const sandboxesStopped =\n cleanUserStop && automation === undefined\n ? withShutdownDeadline(\n () => stopSandboxProviders(sandboxes.list(), notice),\n 'sandbox stop',\n SANDBOX_STOP_DEADLINE_MS,\n ).catch((error: unknown) =>\n notice(`sandbox stop failed: ${error instanceof Error ? error.message : String(error)}`),\n )\n : Promise.resolve();\n if (cleanUserStop) {\n try {\n await recoveryWrites;\n await removeRecycleFile(serverDirectory);\n // Stopping the server is not switching remote access off: a named tunnel comes back next start.\n await keepTunnelIntent(serverDirectory, recoveryTunnel);\n } catch (error) {\n notice(`Could not remove crash recovery state: ${String(error)}`);\n }\n }\n idleRestart.dispose();\n stopIdleRestartPoke();\n stopResourceMonitor();\n executionBudget.close();\n watcher.close();\n stopPersistSessionNames();\n stopNativePush?.();\n for (const stop of stopSandboxWatches.splice(0)) stop();\n modelGateway?.dispose();\n clearInterval(eventLoopMonitor);\n await bounded(telemetry.recordEvent('po_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 await bounded(\n withShutdownDeadline(() => recoveryWork, 'crash recovery shutdown'),\n 'crash recovery shutdown',\n notice,\n );\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(router?.dispose() ?? Promise.resolve(), 'sandbox router shutdown', notice);\n await sandboxesStopped;\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 Promise.allSettled(\n [...repositoryContexts.values()].map((context) =>\n bounded(context.cleanup(), 'repository context cleanup', notice),\n ),\n );\n repositoryContexts.clear();\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4JA,MAAM,8BAA8B;;AAEpC,MAAM,eAAe;;AAErB,MAAM,wBAAwB;;AAG9B,SAAS,eAAe,MAAuB;CAC7C,MAAM,UAAU,KAAK,WAAW,GAAG,KAAK,KAAK,SAAS,GAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI;CACjF,IAAI,QAAQ,YAAY,MAAM,aAAa,OAAO;CAClD,IAAIA,SAAAA,QAAI,OAAO,OAAO,GAAG,OAAO,QAAQ,WAAW,MAAM;CACzD,IAAI,CAACA,SAAAA,QAAI,OAAO,OAAO,GAAG,OAAO;CACjC,MAAM,QAAQ,QAAQ,YAAY;CAClC,OACE,UAAU,SAAU,MAAM,WAAW,SAAS,KAAKA,SAAAA,QAAI,OAAO,MAAM,MAAM,CAAC,CAAC,KAAK,MAAM,MAAM,CAAC,CAAC,CAAC,WAAW,MAAM;AAErH;;;;;;AAOA,SAAS,uBAAuB,aAA6B;CAC3D,MAAM,iBAAiBC,UAAAA,QAAK,QAAQ,WAAW;CAC/C,OAAOA,UAAAA,QAAK,SAASA,UAAAA,QAAK,QAAQ,cAAc,CAAC,MAAM,iBACnDA,UAAAA,QAAK,QAAQ,aAAa,UAAU,IACpC;AACN;AAEA,SAAS,aAAa,OAAwB;CAC5C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;AAGA,SAAS,aAAa,WAAuC;CAC3D,OAAO,UAAU,cAAc,SAAS,UAAU,YAAY,KAAA;AAChE;;AAMA,SAAS,aACP,QACA,WACA,SAA8B,CAAC,GACZ;CACnB,OAAO;EACL,IAAI,OAAO;EACX,MAAM,OAAO;EACb,GAAI,O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