Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

refactor(server): refactor server entry for hmr and plugins (#359)

Myriad-Dreaminec2e9d30be3b
diff --git a/changelog/unreleased/2026-08-20-business-surface-rides-the-platform.md b/changelog/unreleased/2026-08-20-business-surface-rides-the-platform.md
new file mode 100644
index 00000000..8b99bb58
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-business-surface-rides-the-platform.md
@@ -0,0 +1,26 @@
+# The whole business surface rides the hot platform
+
+- **Date:** 2026-08-20
+- **Type:** refactor
+- **Scope:** `server`, `cli`, `desktop`
+- **PR:** [#359](https://github.com/Prism-Shadow/penguin-harness/pull/359)
+
+Every business service and route — `/api/me` through `/api/sessions`, the scheduler, the
+session manager — moved out of the runtime shell and into the platform: assembled inside
+`platformImpl.create()` over capabilities the runtime publishes through the resource
+registry (database handle, auth service, channel hub, config, proxy control, desktop
+service), and served through the HTTP seam. A hot push therefore replaces the business
+wholesale; the runtime keeps mechanism only — transport, auth routes, HMR, static hosting.
+
+## Details
+
+- The former `platform/` folder dissolved into its successors: `hmr/` (the swap machinery
+ and the packaged platform), `app.ts` (both surfaces' assembly) and `terminal/`.
+- Each App registers one route table and publishes itself as one unit, so no reader can
+ observe a half-swapped pair; swap semantics for unparked state are a hard stop, with
+ terminals as the parked exception that rides across.
+- The capability handshake is structural: the runtime publishes an interface descriptor
+ (member sets per capability, plus a family), and a booting platform verifies the
+ declaration against the live objects before claiming anything.
+- The startup lifecycle became a sequence of one-method steps led by `main()`; the CLI and
+ desktop dropped a redundant `PENGUIN_HOME` read that `resolveRoot()` already performs.
diff --git a/changelog/unreleased/2026-08-20-business-surface-rides-the-platform.zh.md b/changelog/unreleased/2026-08-20-business-surface-rides-the-platform.zh.md
new file mode 100644
index 00000000..32ed3434
--- /dev/null
+++ b/changelog/unreleased/2026-08-20-business-surface-rides-the-platform.zh.md
@@ -0,0 +1,22 @@
+# 整个业务面骑上了热更新平台
+
+- **Date:** 2026-08-20
+- **Type:** refactor
+- **Scope:** `server`, `cli`, `desktop`
+- **PR:** [#359](https://github.com/Prism-Shadow/penguin-harness/pull/359)
+
+每一个业务服务和路由——从 `/api/me` 到 `/api/sessions`、调度器、会话管理器——都从 runtime 外壳
+搬进了 platform:在 `platformImpl.create()` 里、基于 runtime 通过资源注册表发布的能力(数据库
+句柄、认证服务、频道 hub、config、代理控制、桌面服务)组装,经 HTTP seam 对外服务。因此一次
+热推送就能整体替换业务;runtime 只保留机制——传输、认证路由、HMR、静态托管。
+
+## Details
+
+- 原 `platform/` 目录解散进它的后继者:`hmr/`(交换机械与打包平台)、`app.ts`(两个面的组装)
+ 和 `terminal/`。
+- 每个 App 注册一张路由表、作为一个整体发布自己,读者不可能观察到半交换的状态;未 park 状态的
+ 交换语义是硬停,终端作为 park 的例外跨代存续。
+- 能力握手是结构化的:runtime 发布接口描述符(每个能力的成员集,外加 family),启动中的 platform
+ 在认领之前用声明校验活对象。
+- 启动生命周期变为 `main()` 领衔的一步一方法的序列;CLI 与桌面端删去了 `resolveRoot()` 已经
+ 完成的一次多余 `PENGUIN_HOME` 读取。
diff --git a/packages/cli/src/commands/reset-password.ts b/packages/cli/src/commands/reset-password.ts
index 182b38f3..31012feb 100644
--- a/packages/cli/src/commands/reset-password.ts
+++ b/packages/cli/src/commands/reset-password.ts
@@ -24,7 +24,7 @@ export function registerResetPasswordCommand(server: Command, t: Messages): void
.command("reset-admin-password")
.description(t.resetPassword.desc)
.action(async () => {
- const root = process.env.PENGUIN_HOME ?? resolveRoot();
+ const root = resolveRoot();
const dbPath = process.env.PENGUIN_WEB_DB ?? path.join(root, "web.db");
const result = await resetAdminPassword(root, dbPath);
switch (result.outcome) {
diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts
index b0606fb1..371b5bb3 100644
--- a/packages/cli/src/commands/serve.ts
+++ b/packages/cli/src/commands/serve.ts
@@ -100,7 +100,7 @@ export function cliEntryFor(argv1: string | undefined): string | null {
* DIFFERENT root is untouched. See @prismshadow/penguin-server/lock.
*/
async function existingInstanceUrl(): Promise<string | null> {
- const lock = await liveServerLock(process.env.PENGUIN_HOME ?? resolveRoot());
+ const lock = await liveServerLock(resolveRoot());
return lock === null ? null : `http://localhost:${lock.port}/`;
}
@@ -291,7 +291,7 @@ export function registerServeCommands(program: Command, t: Messages): void {
// initial one (the server removes it on change), so its presence alone gates the
// reminder here. The fresh-start path below needs nothing: the server module
// runs in this same process and prints the notice itself.
- const initialPassword = readInitialAdminPassword(process.env.PENGUIN_HOME ?? resolveRoot());
+ const initialPassword = readInitialAdminPassword(resolveRoot());
if (initialPassword !== null) {
process.stdout.write(renderInitialPasswordNotice("admin", initialPassword) + "\n");
}
diff --git a/packages/core/src/kernel/boot.ts b/packages/core/src/kernel/boot.ts
index fd44bba2..877f1eb1 100644
--- a/packages/core/src/kernel/boot.ts
+++ b/packages/core/src/kernel/boot.ts
@@ -26,6 +26,18 @@ export interface Resources {
register(id: string, resource: unknown, dispose?: () => void): void;
claim<T = unknown>(id: string): T | undefined;
release(id: string): void;
+ /**
+ * Disposes and removes every entry whose id belongs to the group (`terminal` covers
+ * `terminal:*`), in reverse registration order — later entries may depend on earlier
+ * ones, same convention as effects.
+ *
+ * A hook for IMPLEMENTATIONS, not a kernel mechanism: the kernel never calls it, and
+ * upgrade() has no opinion about resource compatibility. An impl's create() uses it to
+ * hard-stop the groups it cannot adopt from its predecessor (penguin does this over a
+ * declaration it leaves in the registry itself — see server hmr/platform.ts). Optional,
+ * so a registry that does not offer it simply carries every group across unchecked.
+ */
+ disposeGroup?(group: string): void;
}
export interface NodeCtx {
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 272c6b88..ddb5c42e 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -1,75 +1,76 @@
/**
- * Hono app assembly: middleware + route mounting + static hosting +
- * error handling.
+ * App assembly, both halves of it.
*
- * `createApp(deps)` is pure assembly (does not listen on a port): tests inject requests via
- * `app.request()`; `buildAppDeps(config)` assembles all services from config (test doubles
- * like SessionLoader can be injected). The startup entry point is in index.ts.
+ * The RUNTIME shell — `createRuntimeApp(deps)` — mounts the mechanism surface: the network
+ * guards, `/api/auth`, `/api/desktop`, `/api/hmr`, the platform seam, and static hosting.
+ * `bootAppDeps(config)` builds the runtime core (database, auth, channels, HmrHost),
+ * publishes its capabilities into the resource registry (see hmr/capabilities.ts), and
+ * boots the platform — which returns the merged view. Neither listens on a port: tests
+ * inject requests via `app.request()`, and the startup entry point is index.ts.
+ *
+ * The BUSINESS surface — `buildAppDeps` + `createApp`, at the bottom of this
+ * file — is what a hot push replaces. Both are called from `platformImpl.create`
+ * (hmr/platform.ts) at every App creation, over the capabilities claimed from the
+ * registry, so every business service and route travels with the platform version rather
+ * than with this build. Swap semantics for anything they hold that is not parked is a
+ * HARD STOP: approvals deny, runs abort, the scheduler dies with its App.
*/
import fs from "node:fs";
import fsp from "node:fs/promises";
import path from "node:path";
import { Hono } from "hono";
-import type { Context, MiddlewareHandler } from "hono";
+import type { MiddlewareHandler } from "hono";
import { bodyLimit } from "hono/body-limit";
+import { bodyLimitBytes } from "./services/attachment-limits.js";
import type { DatabaseSync } from "node:sqlite";
-import type { ProxyEnvPolicy } from "@prismshadow/penguin-core";
import type { ServerConfig } from "./config.js";
-import { mergedNoProxy } from "./net/proxy.js";
+import { applyProxySettings, mergedNoProxy } from "./net/proxy.js";
+import {
+ PLATFORM_CURRENT_RESOURCE_ID,
+ RUNTIME_INTERFACES,
+ RUNTIME_INTERFACES_RESOURCE_ID,
+ RUNTIME_AUTH_RESOURCE_ID,
+ RUNTIME_CHANNELS_RESOURCE_ID,
+ RUNTIME_CONFIG_RESOURCE_ID,
+ RUNTIME_DB_RESOURCE_ID,
+ RUNTIME_DESKTOP_RESOURCE_ID,
+ RUNTIME_HMR_RESOURCE_ID,
+ RUNTIME_OVERRIDES_RESOURCE_ID,
+ RUNTIME_PROXY_RESOURCE_ID,
+ RuntimeCapabilities,
+} from "./hmr/capabilities.js";
+import type { PlatformCurrent, ProxyControl } from "./hmr/capabilities.js";
import { openDatabase } from "./db/database.js";
-import { AgentsRepo } from "./db/repos/agents.js";
import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";
import { ErrorsRepo } from "./db/repos/errors.js";
-import { MembersRepo } from "./db/repos/members.js";
-import { ProjectsRepo } from "./db/repos/projects.js";
import { GoalsRepo } from "./db/repos/goals.js";
import { SchedulesRepo } from "./db/repos/schedules.js";
import { ServerSettingsRepo } from "./db/repos/server-settings.js";
import { SessionsRepo } from "./db/repos/sessions.js";
-import { TraceIndexRepo } from "./db/repos/trace-index.js";
import { UiPrefsRepo } from "./db/repos/ui-prefs.js";
-import { UsageRepo } from "./db/repos/usage.js";
import { UsersRepo } from "./db/repos/users.js";
import type { UserRow } from "./db/repos/users.js";
-import type { ServerEvent } from "./api/types.js";
import { authMiddleware, jsonOnlyWrites, SESSION_COOKIE } from "./auth/middleware.js";
-import { IDENTITY_RESOURCE_ID } from "./platform/terminal/identity.js";
+import { IDENTITY_RESOURCE_ID } from "./terminal/identity.js";
+import type { Identity } from "./terminal/identity.js";
+import { terminalRoutes } from "./terminal/routes.js";
+import type { TerminalManager } from "./terminal/manager.js";
import type { AppEnv } from "./auth/middleware.js";
import { ADMIN_USER_ID, AuthService } from "./auth/service.js";
import { clearInitialAdminPassword } from "./initial-password.js";
import { handleError, HttpError, errorBody } from "./http/errors.js";
-import { adminUsersRoutes } from "./http/routes/admin.js";
-import { adminSettingsRoutes } from "./http/routes/admin-settings.js";
+import { attributedProjectId } from "./http/attribution.js";
import { authRoutes } from "./http/routes/auth.js";
-import { meRoutes } from "./http/routes/me.js";
-import { eventsRoutes, userChannelKey } from "./http/routes/events.js";
-import { projectsRoutes } from "./http/routes/projects.js";
-import { membersRoutes } from "./http/routes/members.js";
-import { modelsRoutes } from "./http/routes/models.js";
-import { chatDefaultsRoutes } from "./http/routes/chat-defaults.js";
-import { commandPolicyRoutes } from "./http/routes/command-policy.js";
-import { vaultRoutes } from "./http/routes/vault.js";
-import { memoryRoutes } from "./http/routes/memory.js";
-import { scheduleRoutes } from "./http/routes/schedules.js";
-import { benchmarksRoutes } from "./http/routes/benchmarks.js";
-import { agentSkillsRoutes, skillLibraryRoutes } from "./http/routes/skills.js";
-import { agentTransferRoutes } from "./http/routes/agent-transfer.js";
-import { agentsRoutes } from "./http/routes/agents.js";
-import { dirsRoutes } from "./http/routes/dirs.js";
-import { agentConfigRoutes } from "./http/routes/agent-config.js";
-import { agentTracesRoutes } from "./http/routes/agent-traces.js";
-import { usageRoutes } from "./http/routes/usage.js";
-import { agentSessionsRoutes, sessionsRoutes } from "./http/routes/sessions.js";
-import { versionRoutes } from "./http/routes/version.js";
import { ChannelHub } from "./runtime/channel.js";
import { ErrorRecorder } from "./runtime/error-recorder.js";
-import { createCoreSessionLoader, SessionManager } from "./runtime/session-manager.js";
+import {
+ createCoreSessionLoader,
+ SessionLoader,
+ SessionManager,
+} from "./runtime/session-manager.js";
import { SessionSources } from "./runtime/session-sources.js";
-import type { SessionLoader } from "./runtime/session-manager.js";
import { Scheduler } from "./runtime/scheduler.js";
-import { TitleGenerator } from "./runtime/title-generator.js";
-import type { TitleNotifier } from "./runtime/title-generator.js";
-import { UsageRecorder } from "./runtime/usage-recorder.js";
+import { TitleGenerator, TitleNotifier } from "./runtime/title-generator.js";
import { AdminService } from "./services/admin-service.js";
import { DesktopService } from "./services/desktop-service.js";
import { desktopRoutes, desktopUpdateRoutes } from "./http/routes/desktop.js";
@@ -96,14 +97,39 @@ import {
requestAuthority,
} from "./services/preview-token.js";
import type { PreviewTokenSigner } from "./services/preview-token.js";
-import { previewRoutes } from "./http/routes/preview.js";
-import { bodyLimitBytes } from "./services/attachment-limits.js";
-/**
- * The request body cap is no longer a constant: it is derived per request from the admin-settable
- * attachment budget (see services/attachment-limits.ts — tasks carry their attachments and images
- * inline as base64 `data:` URLs, which inflates them by 4/3).
- */
+import type { ProxyEnvPolicy } from "@prismshadow/penguin-core";
+import { declined } from "./hmr/hono-seam.js";
+import { AgentsRepo } from "./db/repos/agents.js";
+import { MembersRepo } from "./db/repos/members.js";
+import { ProjectsRepo } from "./db/repos/projects.js";
+import { TraceIndexRepo } from "./db/repos/trace-index.js";
+import { UsageRepo } from "./db/repos/usage.js";
+import { adminUsersRoutes } from "./http/routes/admin.js";
+import { adminSettingsRoutes } from "./http/routes/admin-settings.js";
+import type { ServerEvent } from "./api/types.js";
+import { meRoutes } from "./http/routes/me.js";
+import { eventsRoutes, userChannelKey } from "./http/routes/events.js";
+import { projectsRoutes } from "./http/routes/projects.js";
+import { membersRoutes } from "./http/routes/members.js";
+import { modelsRoutes } from "./http/routes/models.js";
+import { chatDefaultsRoutes } from "./http/routes/chat-defaults.js";
+import { commandPolicyRoutes } from "./http/routes/command-policy.js";
+import { vaultRoutes } from "./http/routes/vault.js";
+import { memoryRoutes } from "./http/routes/memory.js";
+import { scheduleRoutes } from "./http/routes/schedules.js";
+import { benchmarksRoutes } from "./http/routes/benchmarks.js";
+import { agentSkillsRoutes, skillLibraryRoutes } from "./http/routes/skills.js";
+import { agentTransferRoutes } from "./http/routes/agent-transfer.js";
+import { agentsRoutes } from "./http/routes/agents.js";
+import { dirsRoutes } from "./http/routes/dirs.js";
+import { agentConfigRoutes } from "./http/routes/agent-config.js";
+import { agentTracesRoutes } from "./http/routes/agent-traces.js";
+import { usageRoutes } from "./http/routes/usage.js";
+import { agentSessionsRoutes, sessionsRoutes } from "./http/routes/sessions.js";
+import { versionRoutes } from "./http/routes/version.js";
+import { UsageRecorder } from "./runtime/usage-recorder.js";
+import { previewRoutes } from "./http/routes/preview.js";
export interface AppDeps {
config: ServerConfig;
@@ -145,6 +171,13 @@ export interface AppDeps {
desktop: DesktopService | null;
/** HMR host: loads/swaps/persists the platform and web bundles (park/boot kernel). */
hmr: HmrHost;
+ /**
+ * Applies proxy settings to the RUNTIME's global dispatcher. A capability rather than a
+ * direct import on purpose: a pushed bundle carries its own copy of net/proxy.js (and of
+ * undici), so calling its own applyProxySettings would configure a dispatcher
+ * globalThis.fetch never routes through.
+ */
+ proxyControl: ProxyControl;
/** Request log output (minimal one-liner); tests inject a noop. */
log: (line: string) => void;
}
@@ -165,13 +198,353 @@ export interface BuildDepsOverrides {
now?: () => Date;
}
-/** Assemble all services from config (shared by production and tests; tests pass dbPath=":memory:" and a temp root). */
-export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides = {}): AppDeps {
- const db = openDatabase(config.dbPath);
+/**
+ * Assemble the runtime core, publish its capabilities, boot the platform (which builds
+ * the business surface — see app.ts), and return the merged view. Shared
+ * by production and tests; tests pass dbPath=":memory:" and a temp root.
+ */
+export async function bootAppDeps(
+ config: ServerConfig,
+ overrides: BuildDepsOverrides = {},
+): Promise<AppDeps> {
+ const db = openDatabase(config.dbPath);
+
+ const usersRepo = new UsersRepo(db);
+ const authSessionsRepo = new AuthSessionsRepo(db);
+
+ // Hoisted above the services so its registry can be populated before anything boots
+ // against it.
+ const hmr = new HmrHost(config.root);
+
+ // Channel idle reclamation skips active Sessions (running/compacting can go a long time
+ // without a publish, e.g. while waiting for approval). The manager lives platform-side
+ // and is rebuilt by every swap: resolve the CURRENT one through the registry at sweep
+ // time rather than capturing any one incarnation.
+ const channels = new ChannelHub({
+ isActive: (key) => {
+ const manager = hmr.resources.claim<PlatformCurrent>(PLATFORM_CURRENT_RESOURCE_ID)?.deps
+ ?.manager;
+ return manager !== undefined && manager.statusOf(key) !== "idle";
+ },
+ });
+
+ // Any password update for the built-in admin makes the persisted initial-password
+ // plaintext stale (either the password is no longer initial, or a reset replaced it
+ // with an admin-chosen value that is never persisted): drop the file so later startups
+ // stop re-printing a credential that no longer signs in.
+ const onPasswordChanged = (userId: string): void => {
+ if (userId === ADMIN_USER_ID) clearInitialAdminPassword(config.root);
+ };
+ const authService = new AuthService({
+ users: usersRepo,
+ authSessions: authSessionsRepo,
+ // Auth is runtime mechanism, but WHAT a fresh user is provisioned with is business
+ // policy — late-bound through the registry so it always reaches the current App.
+ provisionInitialProject: (user, isAdmin) => {
+ const deps = hmr.resources.claim<PlatformCurrent>(PLATFORM_CURRENT_RESOURCE_ID)?.deps;
+ if (deps == null) {
+ throw new Error("no business platform is running to provision the initial Project");
+ }
+ return deps.projectService.provisionInitialProject(user, isAdmin);
+ },
+ seedAdminPassword: config.seedAdminPassword,
+ onPasswordChanged,
+ sessionTtlMs: config.authSessionTtlMs,
+ sessionRenewMs: config.authSessionRenewMs,
+ ...(overrides.passwordHashCost !== undefined
+ ? { passwordHashCost: overrides.passwordHashCost }
+ : {}),
+ ...(overrides.now ? { now: overrides.now } : {}),
+ });
+
+ // The seam runs before the auth middleware, so a platform serving an API of its own has
+ // no `c.var.user`. Authenticating is the runtime's job, not something a bundle should
+ // re-implement against cookie names and session TTLs — so it is published as a
+ // capability the booting platform claims (see terminal/identity.ts).
+ hmr.resources.register(IDENTITY_RESOURCE_ID, async (request: Request) => {
+ const token = readSessionCookie(request.headers.get("cookie"));
+ const authed = token === null ? null : authService.authenticateWithMeta(token);
+ return authed === null ? null : { userId: authed.user.userId };
+ });
+ // The capability set buildAppDeps claims (see hmr/capabilities.ts) — every
+ // entry must be in place before ensure() below performs the first boot. The interface
+ // descriptor leads: it is what a bundle's handshake reads before trusting any of the rest.
+ hmr.resources.register(RUNTIME_INTERFACES_RESOURCE_ID, RUNTIME_INTERFACES);
+ hmr.resources.register(RUNTIME_CONFIG_RESOURCE_ID, config);
+ hmr.resources.register(RUNTIME_DB_RESOURCE_ID, db);
+ hmr.resources.register(RUNTIME_AUTH_RESOURCE_ID, authService);
+ hmr.resources.register(RUNTIME_CHANNELS_RESOURCE_ID, channels);
+ hmr.resources.register(RUNTIME_PROXY_RESOURCE_ID, applyProxySettings);
+ hmr.resources.register(RUNTIME_HMR_RESOURCE_ID, hmr);
+ hmr.resources.register(RUNTIME_OVERRIDES_RESOURCE_ID, overrides);
+ const desktop = config.desktopToken !== null ? new DesktopService(config.desktopToken) : null;
+ hmr.resources.register(RUNTIME_DESKTOP_RESOURCE_ID, desktop);
+
+ // Boot the platform now rather than on the first request: the business surface —
+ // services, routes, the scheduler — is assembled inside its create().
+ await hmr.ensure();
+ const deps = hmr.resources.claim<PlatformCurrent>(PLATFORM_CURRENT_RESOURCE_ID)?.deps;
+ if (deps == null) {
+ throw new Error("the packaged platform built no business surface");
+ }
+ return deps;
+}
+
+/** Assembles the Hono app (does not listen on a port). */
+export function createRuntimeApp(deps: AppDeps): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+
+ // Error recording is layered in a lambda wrapping onError: handleError stays a
+ // pure function with unchanged behavior (HttpError is mapped as-is, unknown
+ // exceptions are logged with a stack trace and collapsed to 500), and recording
+ // to the DB is just a side-effect layered on top.
+ app.onError((err, c) => {
+ const projectId = attributedProjectId(c, deps);
+ deps.errors.record({
+ source: "http",
+ err,
+ ...(projectId !== undefined ? { ctx: { projectId } } : {}),
+ });
+ return handleError(err, c);
+ });
+ app.notFound((c) => c.json(errorBody("not_found", "Endpoint does not exist."), 404));
+
+ // Request logging: a minimal one-liner (method path status ms).
+ app.use("*", async (c, next) => {
+ const start = performance.now();
+ await next();
+ const ms = Math.round(performance.now() - start);
+ deps.log(`${c.req.method} ${c.req.path} ${c.res.status} ${ms}ms`);
+ });
+
+ // Canonical-host guard (loopback binds only): the App is served on one loopback name and
+ // previews on its counterpart, but the SAME process answers on both. Without this, Agent-
+ // written preview HTML on the preview host could call /api same-origin and — if a session
+ // cookie had ever been set on that host — act as the user. So the preview host serves ONLY
+ // /preview/*: /api answers 401 (it never sets or honors a cookie there, closing both the
+ // login and the stale-cookie paths), and everything else 302s to the canonical App host.
+ // Off when PENGUIN_PREVIEW_ORIGIN is set: previews then
+ // use that origin rather than the loopback counterpart, so 127.0.0.1 is an ordinary App
+ // access point and must not be locked down — deployments enforce the equivalent at the
+ // reverse proxy (route only /preview/* to the App on the preview origin).
+ const previewRoles = deps.config.previewOrigin ? null : loopbackHostRoles(deps.config.host);
+ if (previewRoles) {
+ app.use("*", async (c, next) => {
+ const host = hostOnly(requestAuthority(c.req.url, c.req.header("host"))).toLowerCase();
+ if (host === previewRoles.preview && !c.req.path.startsWith("/preview/")) {
+ if (c.req.path.startsWith("/api/")) {
+ throw new HttpError(401, "unauthorized", "The API is not served on the preview host.");
+ }
+ const url = new URL(c.req.url);
+ url.hostname = previewRoles.app;
+ return c.redirect(url.toString(), 302);
+ }
+ await next();
+ });
+ }
+
+ // API common defenses: request body size cap (20MB) and write-request Content-Type (one of the CSRF MVP defenses).
+ //
+ // The cap has to be measured, not read: a chunked request carries no `content-length` at all,
+ // so a header check alone passes a body of any size — the sinks behind it (task input images,
+ // file attachments, Trace import) then decode whatever arrives. hono's bodyLimit keeps the
+ // header fast path when the length is declared and otherwise counts bytes off the stream,
+ // aborting the moment the total crosses the cap.
+ //
+ // The cap is DERIVED from the admin-settable attachment budget rather than fixed, because the
+ // two must not disagree in either direction: a cap below the budget would reject a request whose
+ // every attachment was individually legal (and with a body-shaped error, not a size-shaped one),
+ // while a cap permanently sized for the largest budget an admin *could* set would keep accepting
+ // 300MB bodies on a server whose limits were left at 10MB. It is re-derived per request, so an
+ // admin's change takes effect immediately; the middleware itself is memoized on the resulting
+ // size so the steady state allocates nothing.
+ let capped: { size: number; mw: MiddlewareHandler } | null = null;
+ app.use("/api/*", (c, next) => {
+ const size = bodyLimitBytes(deps.serverSettingsRepo.getAttachmentLimitsMb());
+ if (capped === null || capped.size !== size) {
+ capped = {
+ size,
+ mw: bodyLimit({
+ maxSize: size,
+ // Its default is a bare text/plain 413; throw the App's own error instead so the
+ // response stays the documented `payload_too_large` body that every client handles.
+ onError: () => {
+ throw new HttpError(
+ 413,
+ "payload_too_large",
+ `Request body exceeds the ${Math.floor(size / (1024 * 1024))}MB limit.`,
+ );
+ },
+ }),
+ };
+ }
+ return capped.mw(c, next);
+ });
+ app.use("/api/*", jsonOnlyWrites);
+
+ // Public routes (no login required).
+ app.route("/api/auth", authRoutes(deps));
+ // Desktop shutdown authenticates with the shell's Bearer token, not the cookie
+ // session, so it mounts outside authMiddleware (and only in desktop mode).
+ if (deps.desktop) {
+ app.route("/api/desktop", desktopRoutes(deps));
+ // The client-update surface is runtime-owned like the rest of /api/desktop (the
+ // platform declines that whole prefix): it reads the updater snapshot the shell
+ // pushes over the parentPort this process wires at startup, and forwards
+ // check/install back. Cookie-authed, unlike the Bearer-token shutdown above, so it
+ // carries the auth middleware on its own subtree — the routes then gate on
+ // `sessionVia === "desktop"`, i.e. the shell's own window.
+ app.use("/api/desktop/update", authMiddleware(deps.authService));
+ app.use("/api/desktop/update/*", authMiddleware(deps.authService));
+ app.route("/api/desktop/update", desktopUpdateRoutes(deps));
+ }
+ // Hot platform APIs authenticate themselves (local-agent Bearer token OR
+ // admin cookie session, see hot/routes.ts), so they mount outside the
+ // cookie-only authMiddleware below.
+ app.route("/api/hmr", hmrRoutes(deps));
+
+ // THE seam: from here down, every route is one the platform may take over by push. Mounted
+ // after /api/hmr (which stays runtime-owned — see http-seam.ts) and before both the auth
+ // gate and the built-in routes, so a pushed platform can add endpoints, replace existing
+ // ones, and decide its own authentication. Declining costs one property read and lands on
+ // the runtime's own routes below, which is what a platform without an `http` handler does.
+ app.use("*", platformHttpSeam(deps.hmr));
+
+ // Every protected business route — /api/me through /api/sessions, and /preview — is
+ // served by the platform through the seam above (see app.ts). What
+ // follows is the runtime's own tail: static hosting and the SPA fallback.
+
+ // Static hosting (production): serves the frontend build output with SPA fallback to
+ // index.html. The source resolves per request — the hot host can point it at a
+ // freshly pushed/restored web dist (in memory) without a restart; when nothing has
+ // been pushed, it falls back to the configured webDist. `hmr.ensure()` is awaited
+ // FIRST: web is only restored from harness.json as part of the platform+cli+web
+ // version's lazy first boot (see HmrHost.restore()), which nothing else here
+ // triggers — without this, a request landing right after a restart (before any
+ // /api/hmr/* call warms the host up) would miss a restored version entirely and
+ // silently fall back to the packaged webDist.
+ registerStaticRoutes(app, async () => {
+ await deps.hmr.ensure();
+ return deps.hmr.resolveWebSource() ?? { kind: "dir", dir: deps.config.webDist };
+ });
+
+ return app;
+}
+
+const CONTENT_TYPES: Record<string, string> = {
+ ".html": "text/html; charset=utf-8",
+ ".js": "text/javascript; charset=utf-8",
+ ".css": "text/css; charset=utf-8",
+ ".json": "application/json",
+ ".svg": "image/svg+xml",
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".ico": "image/x-icon",
+ ".map": "application/json",
+ ".txt": "text/plain; charset=utf-8",
+ ".woff2": "font/woff2",
+};
+
+/** Where registerStaticRoutes reads a request's bytes from, resolved fresh per request. */
+export type WebSource = { kind: "mem"; files: Map<string, Buffer> } | { kind: "dir"; dir: string };
+
+/**
+ * Minimal static file server (avoiding an extra dependency): path traversal
+ * protection + SPA fallback, over either an in-memory pushed/restored dist (the
+ * hot host's primary path — no filesystem at all) or the packaged webDist
+ * directory on disk.
+ */
+function registerStaticRoutes(app: Hono<AppEnv>, resolveSource: () => Promise<WebSource>): void {
+ app.get("*", async (c) => {
+ const reqPath = decodeURIComponent(c.req.path);
+ if (reqPath.startsWith("/api/")) {
+ return c.json(errorBody("not_found", "Endpoint does not exist."), 404);
+ }
+ const rel = reqPath.replace(/^\/+/, "") || "index.html";
+ // Resolved per request: the hot host may retarget it between requests.
+ const source = await resolveSource();
+
+ if (source.kind === "mem") {
+ // No filesystem involved, so no traversal guard is needed: an unknown
+ // key simply isn't in the map, same as a missing file on disk.
+ const servedPath = source.files.has(rel) ? rel : "index.html"; // SPA fallback
+ const content = source.files.get(servedPath);
+ if (content === undefined) {
+ return c.json(errorBody("not_found", "Resource does not exist."), 404);
+ }
+ const type =
+ CONTENT_TYPES[path.extname(servedPath).toLowerCase()] ?? "application/octet-stream";
+ return new Response(new Uint8Array(content), {
+ status: 200,
+ headers: { "Content-Type": type },
+ });
+ }
+
+ const webDist = source.dir;
+ if (!fs.existsSync(webDist)) {
+ return c.json(errorBody("not_found", "Resource does not exist."), 404);
+ }
+ const resolved = path.resolve(webDist, rel);
+ // Guard against path traversal: once resolved, it must still be inside webDist.
+ const base = path.resolve(webDist);
+ const target =
+ resolved === base || resolved.startsWith(base + path.sep)
+ ? resolved
+ : path.join(base, "index.html");
+ let file = target;
+ try {
+ const stat = await fsp.stat(file);
+ if (stat.isDirectory()) file = path.join(file, "index.html");
+ await fsp.access(file);
+ } catch {
+ file = path.join(base, "index.html"); // SPA fallback
+ }
+ let content: Buffer;
+ try {
+ content = await fsp.readFile(file);
+ } catch {
+ return c.json(errorBody("not_found", "Resource does not exist."), 404);
+ }
+ const type = CONTENT_TYPES[path.extname(file).toLowerCase()] ?? "application/octet-stream";
+ return new Response(new Uint8Array(content), {
+ status: 200,
+ headers: { "Content-Type": type },
+ });
+ });
+}
+
+/** The session cookie out of a raw Cookie header (the seam hands over a plain Request). */
+function readSessionCookie(header: string | null): string | null {
+ if (header === null) return null;
+ for (const part of header.split(";")) {
+ const eq = part.indexOf("=");
+ if (eq === -1) continue;
+ if (part.slice(0, eq).trim() !== SESSION_COOKIE) continue;
+ return decodeURIComponent(part.slice(eq + 1).trim());
+ }
+ return null;
+}
+
+// ---------------------------------------------------------------------------
+// The business surface: everything below travels with the platform version.
+// Called from hmr/platform.ts's create() at every App creation — see the module doc.
+// ---------------------------------------------------------------------------
+
+/**
+ * Assembles the business service graph over the claimed runtime capabilities.
+ *
+ * The db handle, auth service, channel hub, config object and hmr host come from the
+ * claim — one live instance per process, shared with the runtime. Everything else is
+ * built fresh per App, which is exactly what makes it hot-swappable.
+ */
+export function buildAppDeps(
+ caps: RuntimeCapabilities,
+ overrides: BuildDepsOverrides = {},
+): AppDeps {
+ const { config, db, authService, channels, hmr } = caps;
const log = overrides.log ?? ((line: string) => console.log(line));
const usersRepo = new UsersRepo(db);
- const authSessionsRepo = new AuthSessionsRepo(db);
const projectsRepo = new ProjectsRepo(db);
const membersRepo = new MembersRepo(db);
const agentsRepo = new AgentsRepo(db);
@@ -217,7 +590,8 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
});
const workspaceFiles = new WorkspaceFilesService();
// Per-process secret: preview tokens are short-lived, so losing them on restart is
- // harmless and there is nothing to persist or rotate.
+ // harmless and there is nothing to persist or rotate. (Per-App is the same trade at a
+ // smaller scale: a push invalidates open previews, and a preview is one reload away.)
const previewTokens = createPreviewTokenSigner();
const benchmarks = new BenchmarkService(config.root, workspaceFiles);
const snapshots = new SnapshotService(config.root);
@@ -230,14 +604,6 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
const updateCheck =
overrides.updateCheck ?? new UpdateCheckService(overrides.now ? { now: overrides.now } : {});
- // Channel idle reclamation skips active Sessions (running/compacting can go a long time
- // without a publish, e.g. while waiting for approval).
- // manager is created after channels: use a lazy predicate (managerRef is assigned by the
- // time the sweep timer fires).
- let managerRef: SessionManager | undefined;
- const channels = new ChannelHub({
- isActive: (key) => managerRef !== undefined && managerRef.statusOf(key) !== "idle",
- });
const recorder = new UsageRecorder(usageRepo, overrides.now ?? (() => new Date()));
const errors = new ErrorRecorder(errorsRepo, overrides.now ?? (() => new Date()));
// Shared by SessionManager (run-state flips) and TitleGenerator (title updates): both are
@@ -283,7 +649,6 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
notifyProjectUsers,
...(overrides.now ? { now: overrides.now } : {}),
});
- managerRef = manager;
const projectService = new ProjectService({
root: config.root,
@@ -303,27 +668,14 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
// Any password update for the built-in admin makes the persisted initial-password
// plaintext stale (either the password is no longer initial, or a reset replaced it
// with an admin-chosen value that is never persisted): drop the file so later startups
- // stop re-printing a credential that no longer signs in.
+ // stop re-printing a credential that no longer signs in. (The runtime's AuthService
+ // carries the same rule for the self-service path; this one covers admin resets.)
const onPasswordChanged = (userId: string): void => {
if (userId === ADMIN_USER_ID) clearInitialAdminPassword(config.root);
};
- const authService = new AuthService({
- users: usersRepo,
- authSessions: authSessionsRepo,
- provisionInitialProject: (user, isAdmin) =>
- projectService.provisionInitialProject(user, isAdmin),
- seedAdminPassword: config.seedAdminPassword,
- onPasswordChanged,
- sessionTtlMs: config.authSessionTtlMs,
- sessionRenewMs: config.authSessionRenewMs,
- ...(overrides.passwordHashCost !== undefined
- ? { passwordHashCost: overrides.passwordHashCost }
- : {}),
- ...(overrides.now ? { now: overrides.now } : {}),
- });
const adminService = new AdminService({
users: usersRepo,
- authSessions: authSessionsRepo,
+ authSessions: new AuthSessionsRepo(db),
projects: projectsRepo,
projectService,
onPasswordChanged,
@@ -341,8 +693,8 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
traceIndex,
proxyEnv,
});
- // Schedule scheduler: active only while the server is running. Only
- // assembled here; start() is called in index.ts (tests drive it via tickOnce, no real timer).
+ // Schedule scheduler: assembled here, started by platform.ts's create() (tests drive it
+ // via tickOnce, no real timer), stopped by the same create()'s dispose effect.
const scheduler = new Scheduler({
root: config.root,
repo: schedulesRepo,
@@ -358,19 +710,6 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),
});
- // Hoisted out of the returned literal so its registry can be populated before anything
- // boots against it.
- const hmr = new HmrHost(config.root);
- // The seam runs before the auth middleware, so a platform serving an API of its own has
- // no `c.var.user`. Authenticating is the runtime's job, not something a bundle should
- // re-implement against cookie names and session TTLs — so it is published as a
- // capability the booting platform claims (see platform/terminal/identity.ts).
- hmr.resources.register(IDENTITY_RESOURCE_ID, async (request: Request) => {
- const token = readSessionCookie(request.headers.get("cookie"));
- const authed = token === null ? null : authService.authenticateWithMeta(token);
- return authed === null ? null : { userId: authed.user.userId };
- });
-
return {
config,
db,
@@ -401,133 +740,70 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
manager,
sessionSources,
errors,
- desktop: config.desktopToken !== null ? new DesktopService(config.desktopToken) : null,
+ desktop: caps.desktop,
hmr,
+ proxyControl: caps.proxyControl,
log,
};
}
-/** Assembles the Hono app (does not listen on a port). */
-export function createApp(deps: AppDeps): Hono<AppEnv> {
+/** Prefixes the runtime serves itself; the platform app declines them unconditionally. */
+const RUNTIME_PREFIXES = ["/api/auth", "/api/desktop", "/api/hmr"];
+
+/**
+ * Assembles the platform's ONE Hono app: every route the platform serves — the terminal
+ * group and the business groups — registered together, so a swap replaces the whole route
+ * table as a unit (routes + auth + error shaping; no listening, no logging).
+ *
+ * `deps` is null when the runtime published no business capabilities (an older runtime, a
+ * bare kernel): the terminal group still serves, everything else declines.
+ */
+export function createApp(
+ deps: AppDeps | null,
+ terminals: TerminalManager,
+ identity: Identity,
+): Hono<AppEnv> {
const app = new Hono<AppEnv>();
// Error recording is layered in a lambda wrapping onError: handleError stays a
// pure function with unchanged behavior (HttpError is mapped as-is, unknown
// exceptions are logged with a stack trace and collapsed to 500), and recording
- // to the DB is just a side-effect layered on top.
+ // to the DB is just a side-effect layered on top — skipped when no business (and so
+ // no errors table access) is running.
app.onError((err, c) => {
- const projectId = attributedProjectId(c, deps);
- deps.errors.record({
- source: "http",
- err,
- ...(projectId !== undefined ? { ctx: { projectId } } : {}),
- });
+ if (deps !== null) {
+ const projectId = attributedProjectId(c, deps);
+ deps.errors.record({
+ source: "http",
+ err,
+ ...(projectId !== undefined ? { ctx: { projectId } } : {}),
+ });
+ }
return handleError(err, c);
});
- app.notFound((c) => c.json(errorBody("not_found", "Endpoint does not exist."), 404));
+ app.notFound(() => declined());
- // Request logging: a minimal one-liner (method path status ms).
- app.use("*", async (c, next) => {
- const start = performance.now();
- await next();
- const ms = Math.round(performance.now() - start);
- deps.log(`${c.req.method} ${c.req.path} ${c.res.status} ${ms}ms`);
- });
+ // The terminal group mounts FIRST and carries its own per-route identity gate: a
+ // matched terminal route ends the chain before the cookie auth below ever runs, and an
+ // unmatched /api/terminals path falls through it into the same auth-then-decline shape
+ // as any other unknown /api path.
+ app.route("/", terminalRoutes(terminals, identity));
- // Canonical-host guard (loopback binds only): the App is served on one loopback name and
- // previews on its counterpart, but the SAME process answers on both. Without this, Agent-
- // written preview HTML on the preview host could call /api same-origin and — if a session
- // cookie had ever been set on that host — act as the user. So the preview host serves ONLY
- // /preview/*: /api answers 401 (it never sets or honors a cookie there, closing both the
- // login and the stale-cookie paths), and everything else 302s to the canonical App host.
- // Off when PENGUIN_PREVIEW_ORIGIN is set: previews then
- // use that origin rather than the loopback counterpart, so 127.0.0.1 is an ordinary App
- // access point and must not be locked down — deployments enforce the equivalent at the
- // reverse proxy (route only /preview/* to the App on the preview origin).
- const previewRoles = deps.config.previewOrigin ? null : loopbackHostRoles(deps.config.host);
- if (previewRoles) {
- app.use("*", async (c, next) => {
- const host = hostOnly(requestAuthority(c.req.url, c.req.header("host"))).toLowerCase();
- if (host === previewRoles.preview && !c.req.path.startsWith("/preview/")) {
- if (c.req.path.startsWith("/api/")) {
- throw new HttpError(401, "unauthorized", "The API is not served on the preview host.");
- }
- const url = new URL(c.req.url);
- url.hostname = previewRoles.app;
- return c.redirect(url.toString(), 302);
- }
- await next();
- });
- }
+ if (deps === null) return app;
- // API common defenses: request body size cap and write-request Content-Type (one of the CSRF
- // MVP defenses).
- //
- // The cap has to be measured, not read: a chunked request carries no `content-length` at all,
- // so a header check alone passes a body of any size — the sinks behind it (task input images,
- // file attachments, Trace import) then decode whatever arrives. hono's bodyLimit keeps the
- // header fast path when the length is declared and otherwise counts bytes off the stream,
- // aborting the moment the total crosses the cap.
- //
- // The cap is DERIVED from the admin-settable attachment budget rather than fixed, because the
- // two must not disagree in either direction: a cap below the budget would reject a request whose
- // every attachment was individually legal (and with a body-shaped error, not a size-shaped one),
- // while a cap permanently sized for the largest budget an admin *could* set would keep accepting
- // 300MB bodies on a server whose limits were left at 10MB. It is re-derived per request, so an
- // admin's change takes effect immediately; the middleware itself is memoized on the resulting
- // size so the steady state allocates nothing.
- let capped: { size: number; mw: MiddlewareHandler } | null = null;
- app.use("/api/*", (c, next) => {
- const size = bodyLimitBytes(deps.serverSettingsRepo.getAttachmentLimitsMb());
- if (capped === null || capped.size !== size) {
- capped = {
- size,
- mw: bodyLimit({
- maxSize: size,
- // Its default is a bare text/plain 413; throw the App's own error instead so the
- // response stays the documented `payload_too_large` body that every client handles.
- onError: () => {
- throw new HttpError(
- 413,
- "payload_too_large",
- `Request body exceeds the ${Math.floor(size / (1024 * 1024))}MB limit.`,
- );
- },
- }),
- };
+ // Runtime-owned prefixes decline before anything else runs — in particular before the
+ // auth gate below, which would otherwise 401 an unauthenticated /api/auth/login instead
+ // of letting the runtime's own public route serve it.
+ app.use("*", async (c, next) => {
+ if (RUNTIME_PREFIXES.some((p) => c.req.path === p || c.req.path.startsWith(`${p}/`))) {
+ return declined();
}
- return capped.mw(c, next);
+ await next();
});
- app.use("/api/*", jsonOnlyWrites);
-
- // Public routes (no login required).
- app.route("/api/auth", authRoutes(deps));
- // Desktop shutdown authenticates with the shell's Bearer token, not the cookie
- // session, so it mounts outside authMiddleware (and only in desktop mode).
- if (deps.desktop) {
- app.route("/api/desktop", desktopRoutes(deps));
- }
- // Hot platform APIs authenticate themselves (local-agent Bearer token OR
- // admin cookie session, see hot/routes.ts), so they mount outside the
- // cookie-only authMiddleware below.
- app.route("/api/hmr", hmrRoutes(deps));
-
- // THE seam: from here down, every route is one the platform may take over by push. Mounted
- // after /api/hmr (which stays runtime-owned — see http-seam.ts) and before both the auth
- // gate and the built-in routes, so a pushed platform can add endpoints, replace existing
- // ones, and decide its own authentication. Declining costs one property read and lands on
- // the runtime's own routes below, which is what a platform without an `http` handler does.
- app.use("*", platformHttpSeam(deps.hmr));
- // Protected routes: cookie -> auth_session -> user.
- const auth = authMiddleware(deps.authService);
- app.use("/api/*", auth);
+ // Protected routes: cookie -> auth_session -> user, over the runtime's auth service.
+ app.use("/api/*", authMiddleware(deps.authService));
app.route("/api/me", meRoutes(deps));
- // Cookie-authed (unlike the Bearer-token shutdown above): the page reads updater state
- // and posts check/install here, gated to the shell's own window inside the routes.
- if (deps.desktop) {
- app.route("/api/desktop/update", desktopUpdateRoutes(deps));
- }
app.route("/api/version", versionRoutes(deps));
app.route("/api/admin/users", adminUsersRoutes(deps));
app.route("/api/admin/settings", adminSettingsRoutes(deps));
@@ -555,151 +831,11 @@ export function createApp(deps: AppDeps): Hono<AppEnv> {
// Workspace HTML preview on the separate preview origin: deliberately outside /api and
// outside the auth middleware — that origin never receives the session cookie, so the
- // signed token in the path is the only credential. Mounted before static hosting so the
- // SPA fallback cannot swallow it.
+ // signed token in the path is the only credential.
app.route("/preview", previewRoutes(deps));
- // Static hosting (production): serves the frontend build output with SPA fallback to
- // index.html. The source resolves per request — the hot host can point it at a
- // freshly pushed/restored web dist (in memory) without a restart; when nothing has
- // been pushed, it falls back to the configured webDist. `hmr.ensure()` is awaited
- // FIRST: web is only restored from harness.json as part of the platform+cli+web
- // version's lazy first boot (see HmrHost.restore()), which nothing else here
- // triggers — without this, a request landing right after a restart (before any
- // /api/hmr/* call warms the host up) would miss a restored version entirely and
- // silently fall back to the packaged webDist.
- registerStaticRoutes(app, async () => {
- await deps.hmr.ensure();
- return deps.hmr.resolveWebSource() ?? { kind: "dir", dir: deps.config.webDist };
- });
-
+ // An unknown /api path a logged-in caller reaches falls to notFound → decline → the
+ // runtime answers its own 404; unauthenticated callers are already 401'd above, which
+ // is the same shape the one-app assembly produced.
return app;
}
-
-/**
- * The Project an error is attributed to: only
- * attributed when the URL has a `:projectId` **and** the requester genuinely has
- * access to that Project; otherwise recorded as unattributed (`project_id IS
- * NULL`, visible only to admins).
- *
- * onError also has to handle requests that **haven't passed permission checks
- * yet** — a 401 from being logged out, a 404 from not being a member, both get
- * recorded here. Attributing directly from the URL parameter would let anyone
- * (not necessarily a member of that Project, or even logged in) pick a projectId
- * and hammer it repeatedly to pollute another user's Project with error stats.
- * Traces that can't be attributed simply fall into the admin view (unattributed
- * errors are only visible to admins by design anyway), which is exactly where
- * unauthorized probing belongs.
- *
- * Two defenses here, because this code runs on the error-handling path:
- * - `c.var.user`'s static type is non-null, but authMiddleware never sets it
- * **before** throwing the 401 when logged out, so at runtime it may actually be
- * undefined — it can only be read safely, never destructured directly.
- * - Exceptions are swallowed entirely: throwing here would break onError itself
- * (possibly recursively); any judgment failure falls back to unattributed.
- */
-function attributedProjectId(c: Context<AppEnv>, deps: AppDeps): string | undefined {
- try {
- const projectId = c.req.param("projectId");
- if (projectId === undefined) return undefined;
- const user = c.get("user") as UserRow | undefined;
- if (user === undefined) return undefined;
- return deps.projectService.canAccess(user.userId, projectId) ? projectId : undefined;
- } catch {
- return undefined;
- }
-}
-
-const CONTENT_TYPES: Record<string, string> = {
- ".html": "text/html; charset=utf-8",
- ".js": "text/javascript; charset=utf-8",
- ".css": "text/css; charset=utf-8",
- ".json": "application/json",
- ".svg": "image/svg+xml",
- ".png": "image/png",
- ".jpg": "image/jpeg",
- ".ico": "image/x-icon",
- ".map": "application/json",
- ".txt": "text/plain; charset=utf-8",
- ".woff2": "font/woff2",
-};
-
-/** Where registerStaticRoutes reads a request's bytes from, resolved fresh per request. */
-export type WebSource = { kind: "mem"; files: Map<string, Buffer> } | { kind: "dir"; dir: string };
-
-/**
- * Minimal static file server (avoiding an extra dependency): path traversal
- * protection + SPA fallback, over either an in-memory pushed/restored dist (the
- * hot host's primary path — no filesystem at all) or the packaged webDist
- * directory on disk.
- */
-function registerStaticRoutes(app: Hono<AppEnv>, resolveSource: () => Promise<WebSource>): void {
- app.get("*", async (c) => {
- const reqPath = decodeURIComponent(c.req.path);
- if (reqPath.startsWith("/api/")) {
- return c.json(errorBody("not_found", "Endpoint does not exist."), 404);
- }
- const rel = reqPath.replace(/^\/+/, "") || "index.html";
- // Resolved per request: the hot host may retarget it between requests.
- const source = await resolveSource();
-
- if (source.kind === "mem") {
- // No filesystem involved, so no traversal guard is needed: an unknown
- // key simply isn't in the map, same as a missing file on disk.
- const servedPath = source.files.has(rel) ? rel : "index.html"; // SPA fallback
- const content = source.files.get(servedPath);
- if (content === undefined) {
- return c.json(errorBody("not_found", "Resource does not exist."), 404);
- }
- const type =
- CONTENT_TYPES[path.extname(servedPath).toLowerCase()] ?? "application/octet-stream";
- return new Response(new Uint8Array(content), {
- status: 200,
- headers: { "Content-Type": type },
- });
- }
-
- const webDist = source.dir;
- if (!fs.existsSync(webDist)) {
- return c.json(errorBody("not_found", "Resource does not exist."), 404);
- }
- const resolved = path.resolve(webDist, rel);
- // Guard against path traversal: once resolved, it must still be inside webDist.
- const base = path.resolve(webDist);
- const target =
- resolved === base || resolved.startsWith(base + path.sep)
- ? resolved
- : path.join(base, "index.html");
- let file = target;
- try {
- const stat = await fsp.stat(file);
- if (stat.isDirectory()) file = path.join(file, "index.html");
- await fsp.access(file);
- } catch {
- file = path.join(base, "index.html"); // SPA fallback
- }
- let content: Buffer;
- try {
- content = await fsp.readFile(file);
- } catch {
- return c.json(errorBody("not_found", "Resource does not exist."), 404);
- }
- const type = CONTENT_TYPES[path.extname(file).toLowerCase()] ?? "application/octet-stream";
- return new Response(new Uint8Array(content), {
- status: 200,
- headers: { "Content-Type": type },
- });
- });
-}
-
-/** The session cookie out of a raw Cookie header (the seam hands over a plain Request). */
-function readSessionCookie(header: string | null): string | null {
- if (header === null) return null;
- for (const part of header.split(";")) {
- const eq = part.indexOf("=");
- if (eq === -1) continue;
- if (part.slice(0, eq).trim() !== SESSION_COOKIE) continue;
- return decodeURIComponent(part.slice(eq + 1).trim());
- }
- return null;
-}
diff --git a/packages/server/src/hmr/README.md b/packages/server/src/hmr/README.md
index 98bbd423..c2d55aa8 100644
--- a/packages/server/src/hmr/README.md
+++ b/packages/server/src/hmr/README.md
@@ -9,7 +9,7 @@ and hot-swaps everything else. Read this before changing anything here (or in
| Layer | Lives in | How it ships |
| ------------ | ----------------------------------------------- | --------------------------------- |
| **runtime** | `hmr/`, `packages/desktop/`, server transport | Rebuild + redeploy every install |
-| **platform** | `packages/server/src/platform/` | One HTTP push, seconds, no restart|
+| **platform** | `packages/server/src/hmr/platform.ts` + `app.ts` | One HTTP push, seconds, no restart|
| **workflow** | An agent's own folder | Installed/reloaded per agent |
| **state** | Parked context documents / runtime resources | Rides across swaps, not restarts |
diff --git a/packages/server/src/hmr/capabilities.ts b/packages/server/src/hmr/capabilities.ts
new file mode 100644
index 00000000..a4ce2758
--- /dev/null
+++ b/packages/server/src/hmr/capabilities.ts
@@ -0,0 +1,286 @@
+/**
+ * The runtime→platform capability contract: what the runtime publishes through the
+ * resource registry for the booting platform to claim.
+ *
+ * The registry is the only channel the kernel offers a booting platform (ctx carries
+ * `resources`, nothing else), and everything here is published for one of two reasons:
+ *
+ * - it is runtime MECHANISM the platform must not re-implement (authentication, the SSE
+ * channel hub, the proxy dispatcher — a pushed bundle carries its own copy of every
+ * module, so a bundle-side `applyProxySettings` would configure the bundle's undici
+ * instance while `globalThis.fetch` still routes through the runtime's);
+ * - or it is a live object that must be ONE per process (the SQLite handle — web.db is
+ * single-writer; the ServerConfig object — the listen callback writes the real port
+ * back into it and every reader must observe that write).
+ *
+ * A platform booted by a runtime that publishes none of this (an older runtime, or a
+ * bare kernel in tests) simply builds no business surface — the capability being absent
+ * IS the signal, and terminals keep working regardless.
+ *
+ * The reverse direction is ONE entry: the pointer to the current App ({@link
+ * PlatformCurrent}) — deps, route table and graceful wrap-up published together in a
+ * single registry write.
+ */
+import type { DatabaseSync } from "node:sqlite";
+import type { Resources } from "@prismshadow/penguin-core/kernel";
+import type { ServerConfig } from "../config.js";
+import type { AuthService } from "../auth/service.js";
+import type { ChannelHub } from "../runtime/channel.js";
+import type { ProxySettings } from "../net/proxy.js";
+import type { HmrHost } from "../hmr/host.js";
+import type { DesktopService } from "../services/desktop-service.js";
+import type { AppDeps } from "../app.js";
+
+/**
+ * What one side of the seam speaks: a family, and a Go-style structural interface per
+ * name — the member set a consumer depends on, not a version number.
+ *
+ * Live objects cannot be strict-parsed the way a parked context document is (a claim is a
+ * cast), so this descriptor is the agreement that stands in for a schema. It is
+ * structural for the same reason the kernel's iface is (see boot()'s method-set check):
+ * satisfaction is implicit — anything carrying those members satisfies it — and it can be
+ * verified against the LIVE object rather than trusted. A number cannot be: it says
+ * nothing about what is actually there, it has to be remembered and bumped by hand, and
+ * every bump is global, so widening `db` would decline a bundle that only ever touches
+ * `terminal`. A member set narrows that automatically: adding a member cannot break a
+ * consumer that never named it, and removing one is caught by name at the claim.
+ *
+ * `family` names whose vocabulary these interface names belong to. Two descriptors of
+ * different families share nothing — the same name means something else over there — so a
+ * platform that does not want to inherit penguin's interfaces changes its family and
+ * inherits none of them, rather than having to disagree with each entry one by one.
+ */
+export interface Interfaces {
+ /** Whose vocabulary the names below belong to; {@link PENGUIN_FAMILY} for this build. */
+ family: string;
+ /** The members a consumer of that interface depends on. */
+ [name: string]: string | readonly string[];
+}
+
+/**
+ * Member names of `T`, checked by the compiler: a name `T` does not carry is an error
+ * here, so a rename or a removal breaks the build at the declaration instead of drifting
+ * into a descriptor that describes a shape nothing has. This is what keeps a hand-written
+ * member set honest — the runtime check in {@link lacksMembers} verifies the live object,
+ * and this verifies the list itself against the type it claims to describe.
+ *
+ * Names only: a changed SIGNATURE is out of reach of both checks, since the wire form is
+ * strings. That is the documented limit of a structural descriptor carried across a
+ * module boundary.
+ */
+export type MembersOf<T> = readonly (keyof T & string)[];
+
+/** The family the interfaces this repo defines belong to. */
+export const PENGUIN_FAMILY = "penguin";
+
+/**
+ * The interfaces the RUNTIME publishes for a platform to claim: per `runtime:*`
+ * capability, the members a claimer reaches for. The runtime registers this descriptor
+ * and a bundle checks it — and the live objects behind it — against the copy compiled
+ * into itself, so a mismatch declines the claim at boot instead of surfacing as a
+ * TypeError inside a request or a sweep timer.
+ *
+ * `proxy` is a bare callable: an empty member set means "nothing beyond being there".
+ */
+interface RuntimeInterfaces extends Interfaces {
+ family: string;
+ config: MembersOf<ServerConfig>;
+ db: MembersOf<DatabaseSync>;
+ auth: MembersOf<AuthService>;
+ channels: MembersOf<ChannelHub>;
+ proxy: MembersOf<ProxyControl>;
+ hmr: MembersOf<HmrHost>;
+ desktop: MembersOf<DesktopService>;
+}
+
+export const RUNTIME_INTERFACES: RuntimeInterfaces = {
+ family: PENGUIN_FAMILY,
+ config: [
+ "root",
+ "host",
+ "port",
+ "dbPath",
+ "webDist",
+ "previewOrigin",
+ "seedAdminPassword",
+ "authSessionTtlMs",
+ "authSessionRenewMs",
+ "desktopToken",
+ "portFile",
+ "trustProxy",
+ ],
+ db: ["prepare", "exec", "close"],
+ auth: [
+ "authenticateWithMeta",
+ "seedAdmin",
+ "adminPasswordIsInitial",
+ "login",
+ "logout",
+ "changePassword",
+ "loginDesktop",
+ "setPasswordDesktop",
+ ],
+ channels: ["get", "peek", "broadcast", "dispose"],
+ proxy: [],
+ hmr: ["resources", "ensure", "resolveWebSource", "dispose"],
+ desktop: ["onShutdownRequest", "requestShutdown", "verifyToken", "redeemLoginToken"],
+};
+
+export const RUNTIME_INTERFACES_RESOURCE_ID = "runtime:interfaces";
+
+/** The member set an entry names, or [] when the entry is absent or is the family tag. */
+function members(descriptor: Interfaces, name: string): readonly string[] | undefined {
+ const entry = descriptor[name];
+ return Array.isArray(entry) ? entry : undefined;
+}
+
+/**
+ * The mismatch between what a side offers and what the claimer requires, or null when
+ * every required interface is offered with at least the members named. Go semantics: the
+ * offering side may carry more, never less. A different family short-circuits — the names
+ * are not comparable at all.
+ */
+export function interfaceMismatch(
+ offered: Interfaces | undefined,
+ required: Interfaces,
+): string | null {
+ if (offered === undefined) return "no interface descriptor published";
+ if (offered.family !== required.family) {
+ return `family '${String(offered.family)}' != '${String(required.family)}'`;
+ }
+ for (const name of Object.keys(required)) {
+ if (name === "family") continue;
+ const need = members(required, name) ?? [];
+ const have = members(offered, name);
+ if (have === undefined) return `${name}: not offered`;
+ const missing = need.filter((m) => !have.includes(m));
+ if (missing.length > 0) return `${name}: missing ${missing.join(", ")}`;
+ }
+ return null;
+}
+
+/**
+ * Whether a live object actually carries the members its interface names — the same check
+ * boot() runs on an impl against its iface, applied to a claimed capability. This is what
+ * a structural descriptor buys over a number: the declaration is verified, not trusted.
+ */
+export function lacksMembers(value: unknown, need: readonly string[]): string[] {
+ if (value === null || (typeof value !== "object" && typeof value !== "function")) {
+ return [...need];
+ }
+ return need.filter((m) => (value as Record<string, unknown>)[m] === undefined);
+}
+
+export const RUNTIME_CONFIG_RESOURCE_ID = "runtime:config";
+export const RUNTIME_DB_RESOURCE_ID = "runtime:db";
+export const RUNTIME_AUTH_RESOURCE_ID = "runtime:auth-service";
+export const RUNTIME_CHANNELS_RESOURCE_ID = "runtime:channels";
+export const RUNTIME_PROXY_RESOURCE_ID = "runtime:proxy-control";
+export const RUNTIME_HMR_RESOURCE_ID = "runtime:hmr-host";
+/**
+ * Desktop mode's one service (one-shot login + shutdown token holder). Registered even
+ * when null: desktop-ness is the runtime's lifecycle fact, but the business surface
+ * reads it too (`/api/me` reports desktopMode; single-user mode closes the multi-user
+ * admin surfaces), so the claim must distinguish "not desktop" from "not published".
+ */
+export const RUNTIME_DESKTOP_RESOURCE_ID = "runtime:desktop";
+/** Test-only: BuildDepsOverrides published by bootAppDeps for the platform boot to claim. */
+export const RUNTIME_OVERRIDES_RESOURCE_ID = "runtime:overrides";
+/** Reverse direction: THE pointer to the current App (see {@link PlatformCurrent}). */
+export const PLATFORM_CURRENT_RESOURCE_ID = "platform:current";
+
+/**
+ * The {@link Interfaces} descriptor each App leaves for its successor, naming the
+ * live-object contracts it parks by ID-prefix group (`terminal` covers every `terminal:*`
+ * entry). The NEXT App's create() compares it against its own compiled-in declaration and
+ * integrates a group only at the SAME version and family, hard-stopping the rest (reverse
+ * registration order) before it adopts anything. Riding the registry, not the kernel
+ * iface, keeps the swap mechanism untouched and the policy itself hot-pushable.
+ *
+ * Deliberately colon-free: an ID without a group can never be swept by disposeGroup —
+ * the declaration must outlive the App that wrote it (its dispose effect does NOT
+ * release it) to inform the successor.
+ */
+export const RESOURCE_IFACES_RESOURCE_ID = "resource-interfaces";
+
+/**
+ * The one object a swap publishes — deps, route table and wrap-up together, so flipping
+ * to a new App is a single registry write and no reader can ever see a half-swapped pair
+ * (new deps with the old routes, or the reverse). Everything runtime-side that needs the
+ * current App resolves this pointer at use time: the seam middleware dispatches into
+ * `app`, auth late-binds provisioning through `deps`, index.ts's shutdown awaits
+ * `shutdown`.
+ */
+export interface PlatformCurrent {
+ /** The business deps this App built, or null when the runtime published no capabilities. */
+ deps: AppDeps | null;
+ /** The App's whole Hono route table (terminal + business), fetch-shaped for cross-bundle safety. */
+ app: { fetch(request: Request): Response | Promise<Response> };
+ /** Process-exit graceful drain (manager ≤5s wrap-up); absent when no business runs. */
+ shutdown?: () => Promise<void>;
+}
+
+/** Applies proxy settings to the RUNTIME's global dispatcher (see net/proxy.ts). */
+export type ProxyControl = (settings: ProxySettings) => void;
+
+/** Everything buildAppDeps needs, claimed in one place. */
+export interface RuntimeCapabilities {
+ config: ServerConfig;
+ db: DatabaseSync;
+ authService: AuthService;
+ channels: ChannelHub;
+ proxyControl: ProxyControl;
+ hmr: HmrHost;
+ /** Null on a non-desktop server (a real value, not an absent capability). */
+ desktop: DesktopService | null;
+}
+
+/**
+ * Claims the full capability set, or null when any piece is missing — a partial claim
+ * would build a business surface over half a runtime, which is worse than the honest
+ * "this runtime publishes no business capabilities" degradation.
+ */
+export function claimRuntimeCapabilities(resources: Resources): RuntimeCapabilities | null {
+ // The handshake first: a runtime speaking different interfaces (or one too old to
+ // publish a descriptor at all) must not be claimed against — the members behind the IDs
+ // are exactly what the descriptor stands for.
+ const mismatch = interfaceMismatch(
+ resources.claim<Interfaces>(RUNTIME_INTERFACES_RESOURCE_ID),
+ RUNTIME_INTERFACES,
+ );
+ if (mismatch !== null) {
+ console.warn(`[platform] runtime interfaces: ${mismatch}; declining the claim`);
+ return null;
+ }
+ const config = resources.claim<ServerConfig>(RUNTIME_CONFIG_RESOURCE_ID);
+ const db = resources.claim<DatabaseSync>(RUNTIME_DB_RESOURCE_ID);
+ const authService = resources.claim<AuthService>(RUNTIME_AUTH_RESOURCE_ID);
+ const channels = resources.claim<ChannelHub>(RUNTIME_CHANNELS_RESOURCE_ID);
+ const proxyControl = resources.claim<ProxyControl>(RUNTIME_PROXY_RESOURCE_ID);
+ const hmr = resources.claim<HmrHost>(RUNTIME_HMR_RESOURCE_ID);
+ if (!config || !db || !authService || !channels || !proxyControl || !hmr) return null;
+ // Desktop is nullable by meaning, so it sits outside the all-present check.
+ const desktop = resources.claim<DesktopService | null>(RUNTIME_DESKTOP_RESOURCE_ID) ?? null;
+ // …then the objects themselves. A descriptor is a claim about what is there; this is
+ // the part that checks it, so an honest-but-wrong runtime is caught here rather than at
+ // the first call site. `desktop` is exempt when null — that is a value, not a shortfall.
+ const live: Array<[string, unknown]> = [
+ ["config", config],
+ ["db", db],
+ ["auth", authService],
+ ["channels", channels],
+ ["proxy", proxyControl],
+ ["hmr", hmr],
+ ...(desktop === null ? [] : ([["desktop", desktop]] as Array<[string, unknown]>)),
+ ];
+ for (const [name, value] of live) {
+ const need = RUNTIME_INTERFACES[name];
+ if (!Array.isArray(need)) continue;
+ const lacking = lacksMembers(value, need);
+ if (lacking.length > 0) {
+ console.warn(`[platform] runtime ${name} lacks ${lacking.join(", ")}; declining the claim`);
+ return null;
+ }
+ }
+ return { config, db, authService, channels, proxyControl, hmr, desktop };
+}
diff --git a/packages/server/src/platform/entry.ts b/packages/server/src/hmr/entry.ts
similarity index 100%
rename from packages/server/src/platform/entry.ts
rename to packages/server/src/hmr/entry.ts
diff --git a/packages/server/src/platform/hono-seam.ts b/packages/server/src/hmr/hono-seam.ts
similarity index 100%
rename from packages/server/src/platform/hono-seam.ts
rename to packages/server/src/hmr/hono-seam.ts
diff --git a/packages/server/src/hmr/host.ts b/packages/server/src/hmr/host.ts
index b3ae9864..d0126c69 100644
--- a/packages/server/src/hmr/host.ts
+++ b/packages/server/src/hmr/host.ts
@@ -74,8 +74,8 @@ import type { Instance, Json } from "@prismshadow/penguin-core/kernel";
import { boot, initialDoc, upgrade } from "@prismshadow/penguin-core/kernel";
import { HotResources } from "./resources.js";
import type { Manifest } from "./manifest.js";
-import type { PlatformApi } from "../platform/platform.js";
-import { packagedPlatform } from "../platform/platform.js";
+import type { PlatformApi } from "../hmr/platform.js";
+import { packagedPlatform } from "../hmr/platform.js";
import type { AnyIface, AnyImpl } from "@prismshadow/penguin-core/kernel";
/**
diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.ts
new file mode 100644
index 00000000..f618d0f5
--- /dev/null
+++ b/packages/server/src/hmr/platform.ts
@@ -0,0 +1,225 @@
+/**
+ * THE platform: the one hot-swappable unit this build of the server packages.
+ *
+ * The repo carries exactly one platform — versions exist BETWEEN deployments
+ * (this packaged build vs the next bundle pushed over HTTP), not as parallel
+ * files. When a future build changes the context shape, it bumps `version`
+ * and ships the migrator alongside the new schema; the previous shape lives
+ * only in already-parked documents out in the world.
+ *
+ * PLATFORM LAYER — WHERE POLICY BELONGS. Anything a deployment might want to
+ * change (business APIs, what an agent sees, how a capability behaves) goes
+ * here rather than in the runtime, and reaches installations by one HTTP push
+ * instead of a rebuild. Worth remembering when something looks like it must
+ * live in the shell: this code runs INSIDE the server process, so in-process
+ * effects (e.g. extending process.env for the shells agents spawn) are
+ * deliverable from boot() with no runtime change. See ../hmr/README.md.
+ *
+ * This packaged platform carries the WHOLE business surface (see app.ts):
+ * every business service and route is assembled inside create() over the runtime's
+ * published capabilities, and serves through the seam in ../hmr/http-seam.ts — it
+ * sees every request before the runtime's own routes do and answers null for the
+ * ones it does not own. A pushed bundle therefore replaces the business wholesale:
+ * adding or changing an endpoint or a service needs no runtime change.
+ */
+import type { WebSocket } from "ws";
+import type { Impl, Json, Park } from "@prismshadow/penguin-core/kernel";
+import { defineIface, schema, type } from "@prismshadow/penguin-core/kernel";
+import type { PlatformBundle } from "../hmr/host.js";
+import { TerminalManager } from "../terminal/manager.js";
+import type { TerminalSession } from "../terminal/session.js";
+import { identityFrom } from "../terminal/identity.js";
+import { bindTerminalStream } from "../terminal/stream.js";
+import { buildAppDeps, createApp, type AppDeps, type BuildDepsOverrides } from "../app.js";
+import { seamHttp } from "./hono-seam.js";
+import {
+ PENGUIN_FAMILY,
+ PLATFORM_CURRENT_RESOURCE_ID,
+ RESOURCE_IFACES_RESOURCE_ID,
+ RUNTIME_OVERRIDES_RESOURCE_ID,
+ claimRuntimeCapabilities,
+} from "./capabilities.js";
+import type { Interfaces, MembersOf, PlatformCurrent } from "./capabilities.js";
+
+export interface PlatformApi extends Park {
+ info(): Json;
+ /**
+ * The HTTP seam (hmr/http-seam.ts): every request is offered here first, and null
+ * declines it to the runtime's own routes. This is how a business API ships by push
+ * instead of by rebuilding and redeploying every installation.
+ */
+ http(request: Request): Promise<Response | null>;
+ /**
+ * In-process accessors for the one thing the seam cannot carry: a live socket. The
+ * runtime's ws transport authenticates an upgrade, then asks for the session and hands
+ * the socket back for the platform's protocol to drive.
+ */
+ terminals(): TerminalManager;
+ attachStream(ws: WebSocket, session: TerminalSession, url: URL, log: (l: string) => void): void;
+}
+
+/**
+ * `terminals` is the linear-state half of this document: the pty processes themselves live
+ * in the runtime's resource registry (they must — a swap disposes this tree), and the
+ * document carries only their handle ids so the next instance can claim them back.
+ */
+export type PlatformCtx = { motd: string; terminals?: string[] };
+
+export const PlatformIface = defineIface<PlatformApi, PlatformCtx>({
+ name: "platform",
+ version: 1,
+ context: schema<PlatformCtx>(type({ motd: "string", "terminals?": "string[]" })),
+ methods: ["park", "info", "http", "terminals", "attachStream"],
+});
+
+/**
+ * The resource interfaces this platform parks, by ID-prefix group (see
+ * RESOURCE_IFACES_RESOURCE_ID in ./capabilities.ts): create() integrates a group its
+ * predecessor declared only at the same family AND version, and hard-stops it otherwise.
+ * `terminal` is the spawn primitive — a live pty behind a deliberately stable contract,
+ * expected to stay at v1 across upgrades that change everything else; `platform` is the
+ * current-App pointer. A platform that does not want to inherit any of penguin's parked
+ * resources declares a different `family` instead of arguing with each version.
+ */
+interface ParkedInterfaces extends Interfaces {
+ family: string;
+ terminal: MembersOf<TerminalSession>;
+ platform: MembersOf<PlatformCurrent>;
+}
+
+export const DECLARED_RESOURCES: ParkedInterfaces = {
+ family: PENGUIN_FAMILY,
+ // A parked pty, as its adopters use it — EVERY member reached after adoption, not a
+ // representative sample: the manager (id, seq, ownerUserId, alive, info, onExit, kill,
+ // dispose), the routes (capture, write, rename, exit) and the stream binding
+ // (onOutput, resize, releaseSize, restoreStream). A short list would let a predecessor
+ // satisfy the descriptor and still TypeError on the first keystroke after a swap,
+ // which is exactly what this check exists to prevent.
+ terminal: [
+ "id",
+ "seq",
+ "ownerUserId",
+ "alive",
+ "exit",
+ "info",
+ "rename",
+ "capture",
+ "write",
+ "resize",
+ "releaseSize",
+ "restoreStream",
+ "onOutput",
+ "onExit",
+ "kill",
+ "dispose",
+ ],
+ // The current-App pointer (see PlatformCurrent).
+ platform: ["deps", "app"],
+};
+
+export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
+ async create(ctx, context) {
+ // Resource-interface reconciliation, BEFORE anything is adopted: integrate the groups
+ // the predecessor declared at the version this build also declares, hard-stop the
+ // rest — a version bump or a dropped group means this create() does not speak the
+ // contract behind those handles, and adopting them anyway is how a swap turns into a
+ // TypeError. A predecessor from before the declaration existed reads as `{}`:
+ // nothing provable, nothing disposed on its behalf (pre-declaration behavior).
+ const inherited = ctx.resources.claim<Interfaces>(RESOURCE_IFACES_RESOURCE_ID);
+ const inheritable = inherited !== undefined && inherited.family === DECLARED_RESOURCES.family;
+ for (const [group, offered] of Object.entries(inherited ?? {})) {
+ if (group === "family") continue;
+ // Wrong family, wrong version, or a group this build no longer declares: this
+ // create() cannot speak the contract behind those handles.
+ const need = DECLARED_RESOURCES[group];
+ const offers =
+ Array.isArray(need) && Array.isArray(offered) && need.every((m) => offered.includes(m));
+ if (!inheritable || !offers) ctx.resources.disposeGroup?.(group);
+ }
+ // Overwritten (never released — see the ID's doc) so the NEXT App reads this build's
+ // declaration, whatever generation it is.
+ ctx.resources.register(RESOURCE_IFACES_RESOURCE_ID, DECLARED_RESOURCES);
+
+ const terminals = new TerminalManager(ctx.resources);
+ // Shells started before this instance existed are still running in the registry: claim
+ // them back so a push is invisible to whoever was typing in one.
+ terminals.adopt(context.terminals ?? []);
+ const identity = identityFrom(ctx.resources);
+
+ // The business deps, built per App over the runtime's published capabilities — see
+ // app.ts's buildAppDeps and ./capabilities.ts. A runtime that publishes nothing
+ // (an older runtime, a bare kernel) gets a terminals-only platform rather than a
+ // failed boot.
+ let deps: AppDeps | null = null;
+ const caps = claimRuntimeCapabilities(ctx.resources);
+ if (caps === null) {
+ console.warn("[platform] runtime publishes no business capabilities; terminals only");
+ } else {
+ const overrides = ctx.resources.claim<BuildDepsOverrides>(RUNTIME_OVERRIDES_RESOURCE_ID);
+ deps = buildAppDeps(caps, overrides ?? {});
+ // Schedule scheduler: startup reconciliation (missed, don't backfill) + periodic
+ // scan; only active while this App is.
+ await deps.scheduler.start();
+ // Goal mode runs only in SessionManager memory: a hard crash (SIGKILL, power loss)
+ // can leave goal_state rows stuck `active` with no runner behind them — and so can
+ // the previous App, whose manager a swap hard-aborts. Reconcile them to `aborted`
+ // now — nothing is running in THIS App yet — so the chat banner never restores a
+ // phantom "running" goal. GOAL.yaml on disk stays `active` as the resume point.
+ deps.goalsRepo.abortOrphanedActive();
+ }
+
+ // ONE app, ONE pointer: every route this App serves — terminal group and business
+ // groups — registers into a single Hono table, and the swap publishes deps + table +
+ // wrap-up as a single registry write, so no reader can observe a half-swapped pair.
+ const app = createApp(deps, terminals, identity);
+ const business = deps;
+ const current: PlatformCurrent = {
+ deps,
+ app,
+ // Process exit wants the manager's graceful ≤5s drain, which a synchronous dispose
+ // effect cannot await — carried on the pointer for index.ts's shutdown to call.
+ ...(business === null ? {} : { shutdown: () => business.manager.shutdown(5000) }),
+ };
+ ctx.resources.register(PLATFORM_CURRENT_RESOURCE_ID, current);
+ ctx.effect(() => {
+ // Swap semantics for unparked state: HARD STOP. Pending approvals converge to
+ // deny, active runs abort, the scheduler's timer dies with this App; the next
+ // App rebuilds all of it. Only parked resources (terminals) ride across.
+ if (business !== null) {
+ business.scheduler.stop();
+ void business.manager.shutdown(0);
+ }
+ ctx.resources.release(PLATFORM_CURRENT_RESOURCE_ID);
+ });
+
+ const http = seamHttp(app);
+
+ return {
+ // Deliberately NOT disposing the terminals here (no ctx.effect): the shells are
+ // resources, and outliving a swap is the whole point. Process exit sweeps them
+ // through the registry's own disposers.
+ park: () => ({ motd: context.motd, terminals: terminals.handleIds() }),
+ info: () => ({
+ impl: "packaged",
+ ifaceVersion: PlatformIface.version,
+ motd: context.motd,
+ terminals: terminals.handleIds().length,
+ }),
+ http,
+ terminals: () => terminals,
+ attachStream: (ws, session, url, log) => bindTerminalStream(ws, session, url, log),
+ };
+ },
+};
+
+/**
+ * The packaged bundle the runtime boots when nothing has been pushed yet — code AND its
+ * initial context together, so the runtime never hardcodes a business value of its own
+ * (see hmr/host.ts's PlatformBundle: every bundle, packaged or pushed, carries `context`).
+ */
+export const packagedPlatform: PlatformBundle = {
+ id: "packaged",
+ iface: PlatformIface,
+ impl: platformImpl,
+ context: { motd: "hello from the penguin hot platform" } satisfies PlatformCtx,
+};
diff --git a/packages/server/src/hmr/resources.ts b/packages/server/src/hmr/resources.ts
index a0ed6f4f..57a26461 100644
--- a/packages/server/src/hmr/resources.ts
+++ b/packages/server/src/hmr/resources.ts
@@ -18,6 +18,11 @@ export class HotResources implements Resources {
private readonly map = new Map<string, { resource: unknown; dispose?: () => void }>();
register(id: string, resource: unknown, dispose?: () => void): void {
+ // Delete before set: Map.set on an existing key KEEPS its original insertion
+ // position, so a re-registration (a successor adopting a pty, say) would still be
+ // disposed in the old owner's slot — and both sweeps below claim to run in reverse
+ // REGISTRATION order, which later entries depending on earlier ones rely on.
+ this.map.delete(id);
this.map.set(id, { resource, dispose });
}
@@ -30,11 +35,33 @@ export class HotResources implements Resources {
}
/**
- * Process-exit sweep: run every registered disposer. Not part of any upgrade path —
- * resources are meant to outlive swaps. A throwing disposer must not strand the rest.
+ * The reconciliation hook a booting App calls (never the kernel — see the interface in
+ * core's boot.ts): disposes and removes every entry of one ID-prefix group (`terminal`
+ * covers `terminal:*`), in reverse registration order — later entries may depend on
+ * earlier ones, the same convention effects follow. Called only for groups whose
+ * declared resource interface the two sides of a swap disagree on; a throwing disposer
+ * must not strand the rest.
+ */
+ disposeGroup(group: string): void {
+ const prefix = `${group}:`;
+ const ids = [...this.map.keys()].filter((id) => id.startsWith(prefix));
+ for (const id of ids.reverse()) {
+ try {
+ this.map.get(id)?.dispose?.();
+ } catch {
+ // Best-effort: the group is being discarded regardless.
+ }
+ this.map.delete(id);
+ }
+ }
+
+ /**
+ * Process-exit sweep: run every registered disposer, newest first (later registrations
+ * may depend on earlier ones). Not part of any upgrade path — resources are meant to
+ * outlive swaps. A throwing disposer must not strand the rest.
*/
disposeAll(): void {
- for (const entry of this.map.values()) {
+ for (const entry of [...this.map.values()].reverse()) {
try {
entry.dispose?.();
} catch {
diff --git a/packages/server/src/http/attribution.ts b/packages/server/src/http/attribution.ts
new file mode 100644
index 00000000..eccfc0fe
--- /dev/null
+++ b/packages/server/src/http/attribution.ts
@@ -0,0 +1,43 @@
+/**
+ * Error→Project attribution, shared by the runtime shell's onError (app.ts) and the
+ * business app's (app.ts). A leaf module so the platform bundle can import
+ * it without dragging the runtime shell into its graph.
+ */
+import type { Context } from "hono";
+import type { AppDeps } from "../app.js";
+import type { AppEnv } from "../auth/middleware.js";
+import type { UserRow } from "../db/repos/users.js";
+
+/**
+ * The Project an error is attributed to: only
+ * attributed when the URL has a `:projectId` **and** the requester genuinely has
+ * access to that Project; otherwise recorded as unattributed (`project_id IS
+ * NULL`, visible only to admins).
+ *
+ * onError also has to handle requests that **haven't passed permission checks
+ * yet** — a 401 from being logged out, a 404 from not being a member, both get
+ * recorded here. Attributing directly from the URL parameter would let anyone
+ * (not necessarily a member of that Project, or even logged in) pick a projectId
+ * and hammer it repeatedly to pollute another user's Project with error stats.
+ * Traces that can't be attributed simply fall into the admin view (unattributed
+ * errors are only visible to admins by design anyway), which is exactly where
+ * unauthorized probing belongs.
+ *
+ * Two defenses here, because this code runs on the error-handling path:
+ * - `c.var.user`'s static type is non-null, but authMiddleware never sets it
+ * **before** throwing the 401 when logged out, so at runtime it may actually be
+ * undefined — it can only be read safely, never destructured directly.
+ * - Exceptions are swallowed entirely: throwing here would break onError itself
+ * (possibly recursively); any judgment failure falls back to unattributed.
+ */
+export function attributedProjectId(c: Context<AppEnv>, deps: AppDeps): string | undefined {
+ try {
+ const projectId = c.req.param("projectId");
+ if (projectId === undefined) return undefined;
+ const user = c.get("user") as UserRow | undefined;
+ if (user === undefined) return undefined;
+ return deps.projectService.canAccess(user.userId, projectId) ? projectId : undefined;
+ } catch {
+ return undefined;
+ }
+}
diff --git a/packages/server/src/http/routes/admin-settings.ts b/packages/server/src/http/routes/admin-settings.ts
index 36d24d6c..a6f94e2c 100644
--- a/packages/server/src/http/routes/admin-settings.ts
+++ b/packages/server/src/http/routes/admin-settings.ts
@@ -116,7 +116,10 @@ export function adminSettingsRoutes(deps: AppDeps): Hono<AppEnv> {
}
// Mirror the app switch + address into the process: rebuilds the global fetch
// dispatcher (live change, no restart; a no-op when nothing effectively changed).
- applyProxySettings({
+ // Through the claimed capability, not a direct import: this route runs inside the
+ // platform bundle, whose own copy of net/proxy.js drives a dispatcher that
+ // globalThis.fetch never routes through (see AppDeps.proxyControl).
+ deps.proxyControl({
proxyForApp: deps.serverSettingsRepo.getProxyForApp(),
proxyUrl: deps.serverSettingsRepo.getProxyUrl(),
});
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 434b6703..61240b03 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -1,22 +1,26 @@
/**
- * Server startup entry point: dotenv → config → assembly → listen
- * → graceful shutdown.
+ * Server process entry point: the whole startup lifecycle, as one ordered sequence.
*
- * SIGINT / SIGTERM: interrupt all active runs (pending approvals converge to deny), wait
- * ≤5s for wrap-up, then close HTTP and SQLite. Tests never go through this file
- * (injected via app.request() instead).
- * There's also a process-level error fallback (uncaughtException / unhandledRejection):
- * persist + log, with the fatal one still shutting down per existing semantics (see the
- * comment below).
+ * Importing this module STARTS the server — the CLI runs a server in its own process by
+ * `await import("@prismshadow/penguin-server")` and nothing else, so main() is invoked at
+ * module scope rather than exported.
+ *
+ * main() comes first in the file and is the sequence itself: each step is one PenguinServer
+ * method, named after what it does and appearing in the order main() calls it. The order
+ * carries real constraints — the proxy dispatcher before any outbound request, the instance
+ * lock before the database opens, the platform (and with it the whole business surface) before the first request is
+ * served — so each step documents the constraint it stands on.
+ *
+ * Tests never go through this file (they inject via app.request() instead).
*/
import fs from "node:fs";
import path from "node:path";
import type { Server as HttpServer } from "node:http";
import { config as loadDotenv } from "dotenv";
import { serve } from "@hono/node-server";
-import { buildAppDeps, createApp } from "./app.js";
+import { bootAppDeps, createRuntimeApp, type AppDeps } from "./app.js";
import { ADMIN_USER_ID } from "./auth/service.js";
-import { resolveServerConfig } from "./config.js";
+import { resolveServerConfig, type ServerConfig } from "./config.js";
import {
clearInitialAdminPassword,
readInitialAdminPassword,
@@ -25,142 +29,260 @@ import {
} from "./initial-password.js";
import { applyProxySettings, installGlobalProxyDispatcher } from "./net/proxy.js";
import { attachTerminalWebSocket } from "./terminal/ws.js";
+import { PLATFORM_CURRENT_RESOURCE_ID } from "./hmr/capabilities.js";
+import type { PlatformCurrent } from "./hmr/capabilities.js";
import { loopbackHostRoles } from "./services/preview-token.js";
import { acquireServerLock, liveServerLock, releaseServerLock } from "./lock.js";
import { shellPortOf, wireShellUpdatePort } from "./services/desktop-update-port.js";
-loadDotenv({ quiet: true });
+/**
+ * The startup lifecycle: one line per step, in the order they have to happen.
+ *
+ * This is the file's table of contents — each call below is a PenguinServer method, and
+ * reading them top to bottom is the whole of what starting a server does.
+ */
+async function main(): Promise<void> {
+ const server = new PenguinServer();
+ server.loadEnv();
+ server.installProxy();
+ server.readConfig();
+ await server.ensureSoleInstance();
+ await server.buildDeps();
+ server.applyPersistedProxy();
+ server.buildApp();
+ await server.seedAdmin();
+ server.listen();
+ server.installProcessHandlers();
+}
-// Outbound proxy support, installed at the earliest point (right after dotenv, which may
-// itself define HTTP_PROXY): replaces globalThis.fetch with undici's and sets the global
-// dispatcher, starting from the defaults (app switch on, no explicit address). The
-// persisted values can only be read once the database is open, so they are applied via
-// applyProxySettings right after buildAppDeps below — nothing in between makes an
-// outbound request. See net/proxy.ts.
-installGlobalProxyDispatcher();
+/**
+ * One server process, one method per lifecycle step.
+ *
+ * The steps are not independent: each reads what the ones before it produced. main() is
+ * the only caller and runs them in order, which is what lets the spine fields below be
+ * read without a null check from the step after the one that assigns them.
+ */
+class PenguinServer {
+ /** Assigned by readConfig(); every later step reads it. */
+ private config!: ServerConfig;
+ /** Assigned by buildDeps(); the merged runtime + business view (see app.ts). */
+ private deps!: AppDeps;
+ /** Assigned by buildApp(). */
+ private app!: ReturnType<typeof createRuntimeApp>;
+ /** Assigned by listen(). */
+ private httpServer!: ReturnType<typeof serve>;
-/** Exit code for "another server already owns this data root" (see lock.ts). */
-const EXIT_ALREADY_RUNNING = 3;
+ /** The `::1` companion listener, when one was opened — see openIpv6Loopback(). */
+ private ipv6Loopback: ReturnType<typeof serve> | null = null;
-const config = resolveServerConfig();
-
-// Single instance per data root: web.db is single-writer and the scheduler must not run
-// twice, so refuse to start when a live server already owns this root — BEFORE opening
-// the database. The CLI and the desktop shell pre-check the same lock for a friendlier
-// path (open / attach to the existing instance); this is the in-process backstop.
-const existingLock = await liveServerLock(config.root);
-if (existingLock) {
- console.error(
- `Another PenguinHarness server is already running on this data root (pid ${existingLock.pid}).`,
- );
- console.error(`Existing instance: http://localhost:${existingLock.port}/`);
- process.exit(EXIT_ALREADY_RUNNING);
-}
+ private shuttingDown = false;
+
+ /** `.env` may itself define HTTP_PROXY, so it is loaded before the dispatcher reads one. */
+ loadEnv(): void {
+ loadDotenv({ quiet: true });
+ }
+
+ /**
+ * Outbound proxy support, installed at the earliest point: replaces globalThis.fetch
+ * with undici's and sets the global dispatcher, starting from the defaults (app switch
+ * on, no explicit address). The persisted values can only be read once the database is
+ * open, so they arrive later through applyPersistedProxy() — nothing in between makes an
+ * outbound request. See net/proxy.ts.
+ */
+ installProxy(): void {
+ installGlobalProxyDispatcher();
+ }
-const deps = buildAppDeps(config);
-// The database is open now: bring the dispatcher in line with the persisted proxy
-// settings (absent rows read as the defaults: app switch on, no explicit address)
-// before the first possible outbound request (update check, LLM calls — all behind
-// HTTP handlers).
-applyProxySettings({
- proxyForApp: deps.serverSettingsRepo.getProxyForApp(),
- proxyUrl: deps.serverSettingsRepo.getProxyUrl(),
-});
-const app = createApp(deps);
-
-// Built-in admin seed (idempotent): creates admin and adopts default_project when the
-// users table is empty. The returned initial password (random unless pinned via
-// PENGUIN_SEED_ADMIN_PASSWORD) is persisted in the data root while it remains the
-// initial one, and EVERY startup re-prints the framed reminder until the password is
-// changed (any password update for admin removes the file — see initial-password.ts).
-// Never printed (or persisted) in desktop mode: the seed there is fully random by design
-// (config.ts) and sign-in goes through the shell's one-shot token, so showing it would
-// only leak a credential into a log nobody needs.
-const seededAdminPassword = await deps.authService.seedAdmin();
-if (config.desktopToken === null) {
- if (seededAdminPassword !== null) {
- storeInitialAdminPassword(config.root, seededAdminPassword);
- }
- if (deps.authService.adminPasswordIsInitial()) {
- const initialPassword = seededAdminPassword ?? readInitialAdminPassword(config.root);
- // Roots seeded before the password was persisted have no file: stay silent — the
- // plaintext is unrecoverable, and a reminder with nothing to type is pure nagging.
- if (initialPassword !== null) {
- console.log(renderInitialPasswordNotice(ADMIN_USER_ID, initialPassword));
+ /** Resolves the process configuration, which comes from the environment only (config.ts). */
+ readConfig(): void {
+ this.config = resolveServerConfig();
+ }
+
+ /**
+ * Single instance per data root: web.db is single-writer and the scheduler must not run
+ * twice, so refuse to start when a live server already owns this root — BEFORE opening
+ * the database. The CLI and the desktop shell pre-check the same lock for a friendlier
+ * path (open / attach to the existing instance); this is the in-process backstop.
+ */
+ async ensureSoleInstance(): Promise<void> {
+ const existing = await liveServerLock(this.config.root);
+ if (existing === null) return;
+ console.error(
+ `Another PenguinHarness server is already running on this data root (pid ${existing.pid}).`,
+ );
+ console.error(`Existing instance: http://localhost:${existing.port}/`);
+ process.exit(EXIT_ALREADY_RUNNING);
+ }
+
+ /**
+ * Builds the service graph: opens the database, publishes the runtime capabilities, and
+ * boots the platform — whose create() assembles the whole business surface (services,
+ * routes, the scheduler) and reconciles crash-orphaned Goals. Everything is therefore in
+ * place before the server serves anything.
+ */
+ async buildDeps(): Promise<void> {
+ this.deps = await bootAppDeps(this.config);
+ }
+
+ /**
+ * The database is open now: bring the dispatcher in line with the persisted proxy
+ * settings (absent rows read as the defaults: app switch on, no explicit address) before
+ * the first possible outbound request (update check, LLM calls — all behind HTTP
+ * handlers).
+ */
+ applyPersistedProxy(): void {
+ applyProxySettings({
+ proxyForApp: this.deps.serverSettingsRepo.getProxyForApp(),
+ proxyUrl: this.deps.serverSettingsRepo.getProxyUrl(),
+ });
+ }
+
+ /** Assembles the runtime shell's middleware and routes. Nothing is listening yet. */
+ buildApp(): void {
+ this.app = createRuntimeApp(this.deps);
+ }
+
+ /**
+ * Built-in admin seed (idempotent): creates admin and adopts default_project when the
+ * users table is empty. The returned initial password (random unless pinned via
+ * PENGUIN_SEED_ADMIN_PASSWORD) is persisted in the data root while it remains the
+ * initial one, and EVERY startup re-prints the framed reminder until the password is
+ * changed (any password update for admin removes the file — see initial-password.ts).
+ * Never printed (or persisted) in desktop mode: the seed there is fully random by design
+ * (config.ts) and sign-in goes through the shell's one-shot token, so showing it would
+ * only leak a credential into a log nobody needs.
+ */
+ async seedAdmin(): Promise<void> {
+ const seededPassword = await this.deps.authService.seedAdmin();
+ if (this.config.desktopToken !== null) return;
+ if (seededPassword !== null) {
+ storeInitialAdminPassword(this.config.root, seededPassword);
+ }
+ if (this.deps.authService.adminPasswordIsInitial()) {
+ const initialPassword = seededPassword ?? readInitialAdminPassword(this.config.root);
+ // Roots seeded before the password was persisted have no file: stay silent — the
+ // plaintext is unrecoverable, and a reminder with nothing to type is pure nagging.
+ if (initialPassword !== null) {
+ console.log(renderInitialPasswordNotice(ADMIN_USER_ID, initialPassword));
+ }
+ } else {
+ // Heal: the flag was cleared while the file survived (e.g. the password was changed
+ // under a build that predates the file) — a stale plaintext must not outlive it.
+ clearInitialAdminPassword(this.config.root);
}
- } else {
- // Heal: the flag was cleared while the file survived (e.g. the password was changed
- // under a build that predates the file) — a stale plaintext must not outlive it.
- clearInitialAdminPassword(config.root);
}
-}
-// Schedule scheduler: startup reconciliation (missed, don't backfill) + periodic scan; only active while the server is running.
-await deps.scheduler.start();
+ /**
+ * Opens the HTTP listener. Everything that needs the port the OS actually handed out
+ * (PORT=0 asks for an ephemeral one) waits for onListening().
+ */
+ listen(): void {
+ this.httpServer = serve(
+ { fetch: this.app.fetch, hostname: this.config.host, port: this.config.port },
+ (info) => this.onListening(info.port),
+ );
+ attachTerminalWebSocket(this.httpServer as unknown as HttpServer, this.terminalWebSocketDeps());
+ }
-// Goal mode runs only in SessionManager memory: a hard crash (SIGKILL, power loss) can leave
-// goal_state rows stuck `active` with no runner behind them. Reconcile them to `aborted` now —
-// nothing is running yet, so any `active` row is a crash orphan — so the chat banner never
-// restores a phantom "running" goal. GOAL.yaml on disk stays `active` as the resume point.
-deps.goalsRepo.abortOrphanedActive();
+ /**
+ * Signals, the desktop quit path and the process-level error fallback. Registered after
+ * listen(), so shutdown() can never fire before there is a listener for it to close.
+ */
+ installProcessHandlers(): void {
+ process.on("SIGINT", () => void this.shutdown("SIGINT"));
+ process.on("SIGTERM", () => void this.shutdown("SIGTERM"));
-// On a loopback bind the App is canonicalized onto one name (`localhost`) and its
-// counterpart is reserved for previews, so advertise the canonical name — the other one
-// only 302s back here for App routes (see the canonical-host guard in app.ts).
-const appHost = loopbackHostRoles(config.host)?.app ?? config.host;
+ // Desktop shell quit path: POST /api/desktop/shutdown lands here — the same graceful
+ // shutdown as the signals, reachable over HTTP because a Windows child kill is a hard
+ // TerminateProcess with no signal delivery.
+ this.deps.desktop?.onShutdownRequest(() => void this.shutdown("desktop-shutdown"));
-/**
- * Second loopback listener so the preview origin is actually reachable.
- *
- * Workspace HTML previews are served from the loopback counterpart of the host the App
- * is used on (`127.0.0.1` <-> `localhost`). On most
- * systems `localhost` resolves to `::1` first, so a server bound only to `127.0.0.1`
- * would leave every preview URL refusing connections. Binding `::1` as well closes that
- * gap. Failure is non-fatal — the App keeps working, previews just fall back.
- *
- * Created inside the main listener's callback so it reuses the ACTUAL bound port: with
- * PORT=0 both listeners resolving 0 independently would land on two different ports and
- * every preview URL (same port, counterpart host) would refuse connections.
- */
-let ipv6Loopback: ReturnType<typeof serve> | null = null;
+ // Client-update relay: under the shell this process is an Electron utilityProcess and
+ // carries process.parentPort; wire it to the desktop service so the update routes can
+ // read the shell's updater snapshot and forward check/install. Absent port (a plain
+ // `penguin server|web` run, or tests) wires nothing.
+ if (this.deps.desktop !== null) {
+ const shellPort = shellPortOf(process);
+ if (shellPort !== null) wireShellUpdatePort(this.deps.desktop, shellPort);
+ }
-/** Port announcement (PENGUIN_PORT_FILE): tmp + rename, so a polling reader never sees a partial write. */
-function writePortFile(file: string, port: number): void {
- fs.mkdirSync(path.dirname(file), { recursive: true });
- const tmp = `${file}.${process.pid}.tmp`;
- fs.writeFileSync(tmp, `${port}\n`);
- fs.renameSync(tmp, file);
-}
+ // Process-level error fallback: once a background fire-and-forget promise (title
+ // generation, Session drive, etc.) throws, the error reaches the process without
+ // passing through any catch — persist it first for a record, then handle each case
+ // according to its nature.
+ process.on("uncaughtException", (err) => {
+ console.error(`[server] Uncaught exception: ${err.stack ?? err.message}`);
+ this.deps.errors.record({ source: "process", err, code: "uncaught_exception" });
+ // From this point the process state can't be trusted (the error was never converged
+ // by any catch): don't swallow it — wrap up per existing shutdown semantics and exit
+ // with a nonzero code (equivalent to Node's default crash exit, just with an extra
+ // persist and graceful wrap-up).
+ // Must exit even if shutdown itself errors — never let "caught a fatal error" turn
+ // into "the process limps along in a broken state".
+ void this.shutdown("uncaughtException", 1).catch(() => process.exit(1));
+ });
+ process.on("unhandledRejection", (reason) => {
+ const err = reason instanceof Error ? reason : new Error(String(reason));
+ console.error(`[server] Unhandled promise rejection: ${err.stack ?? err.message}`);
+ this.deps.errors.record({ source: "process", err, code: "unhandled_rejection" });
+ // Unlike uncaughtException, this **doesn't** exit: a rejected promise is a localized
+ // failure of some background task, and the process state isn't compromised; dragging
+ // down the entire service for it (Node's default behavior) isn't worth it — persist +
+ // log, then keep serving.
+ });
+ }
+
+ /** Everything derived from the actual bound port, run once the listener is up. */
+ private onListening(port: number): void {
+ console.log(`penguin-server started: http://${this.appHost()}:${port}`);
+ console.log(`Data root: ${this.config.root}`);
+ console.log(`SQLite: ${this.config.dbPath}`);
+ if (this.config.desktopToken !== null) console.log("Desktop mode: enabled");
+ // PORT=0 asked for an ephemeral port: record the real one so everything derived from
+ // the server's own port is correct — Workspace preview URLs above all, which are built
+ // from the bind port on purpose (see resolvePreviewTarget) and would otherwise point at
+ // port 0 and fail to load. deps.config is this same object, so both route call sites
+ // (me.ts, sessions.ts) observe the update.
+ this.config.port = port;
+ // The root exists by now (openDatabase created it), and the pre-start check found no
+ // live owner — record ourselves as this root's server.
+ acquireServerLock(this.config.root, {
+ pid: process.pid,
+ port,
+ startedAt: new Date().toISOString(),
+ });
+ if (this.config.portFile !== null) writePortFile(this.config.portFile, port);
+ if (this.config.host === "127.0.0.1" || this.config.host === "localhost") {
+ this.openIpv6Loopback(port);
+ }
+ }
-/** Terminal WebSocket wiring, shared by every listener this process opens. */
-const terminalWebSocketDeps = {
- hmr: deps.hmr,
- authService: deps.authService,
- log: (line: string) => console.log(line),
-};
-
-const server = serve({ fetch: app.fetch, hostname: config.host, port: config.port }, (info) => {
- console.log(`penguin-server started: http://${appHost}:${info.port}`);
- console.log(`Data root: ${config.root}`);
- console.log(`SQLite: ${config.dbPath}`);
- if (config.desktopToken !== null) console.log("Desktop mode: enabled");
- // PORT=0 asked for an ephemeral port: record the real one so everything derived from
- // the server's own port is correct — Workspace preview URLs above all, which are built
- // from the bind port on purpose (see resolvePreviewTarget) and would otherwise point at
- // port 0 and fail to load. deps.config is this same object, so both route call sites
- // (me.ts, sessions.ts) observe the update.
- config.port = info.port;
- // The root exists by now (openDatabase created it), and the pre-start check found no
- // live owner — record ourselves as this root's server.
- acquireServerLock(config.root, {
- pid: process.pid,
- port: info.port,
- startedAt: new Date().toISOString(),
- });
- if (config.portFile !== null) writePortFile(config.portFile, info.port);
- if (config.host === "127.0.0.1" || config.host === "localhost") {
- ipv6Loopback = serve({ fetch: app.fetch, hostname: "::1", port: info.port });
- ipv6Loopback.on("error", (err: NodeJS.ErrnoException) => {
+ /**
+ * On a loopback bind the App is canonicalized onto one name (`localhost`) and its
+ * counterpart is reserved for previews, so advertise the canonical name — the other one
+ * only 302s back here for App routes (see the canonical-host guard in app.ts).
+ */
+ private appHost(): string {
+ return loopbackHostRoles(this.config.host)?.app ?? this.config.host;
+ }
+
+ /**
+ * Second loopback listener so the preview origin is actually reachable.
+ *
+ * Workspace HTML previews are served from the loopback counterpart of the host the App
+ * is used on (`127.0.0.1` <-> `localhost`). On most systems `localhost` resolves to
+ * `::1` first, so a server bound only to `127.0.0.1` would leave every preview URL
+ * refusing connections. Binding `::1` as well closes that gap. Failure is non-fatal —
+ * the App keeps working, previews just fall back.
+ *
+ * Takes the ACTUAL bound port rather than resolving the configured one again: with
+ * PORT=0 both listeners resolving 0 independently would land on two different ports and
+ * every preview URL (same port, counterpart host) would refuse connections.
+ */
+ private openIpv6Loopback(port: number): void {
+ const loopback = serve({ fetch: this.app.fetch, hostname: "::1", port });
+ this.ipv6Loopback = loopback;
+ loopback.on("error", (err: NodeJS.ErrnoException) => {
console.warn(
`[server] IPv6 loopback listener unavailable (${err.code ?? err.message}); previews via localhost may not resolve.`,
);
@@ -168,83 +290,73 @@ const server = serve({ fetch: app.fetch, hostname: config.host, port: config.por
// The terminal stream is a WebSocket upgrade, which never reaches the Hono fetch
// handler — it has to be bound on each Node listener, this one included, or the
// terminal only works on whichever address the browser happened to resolve.
- attachTerminalWebSocket(ipv6Loopback as unknown as HttpServer, terminalWebSocketDeps);
+ attachTerminalWebSocket(loopback as unknown as HttpServer, this.terminalWebSocketDeps());
+ }
+
+ /** Terminal WebSocket wiring, shared by every listener this process opens. */
+ private terminalWebSocketDeps() {
+ return {
+ hmr: this.deps.hmr,
+ authService: this.deps.authService,
+ log: (line: string) => console.log(line),
+ };
}
-});
-attachTerminalWebSocket(server as unknown as HttpServer, terminalWebSocketDeps);
-/** Removes the instance lock and port file (best-effort; runs on both exit paths). */
-function cleanupInstanceFiles(): void {
- releaseServerLock(config.root);
- if (config.portFile !== null) {
+ /**
+ * Graceful shutdown, idempotent across every path that can trigger it: interrupt all
+ * active runs (pending approvals converge to deny), wait ≤5s for wrap-up, then close
+ * HTTP and SQLite.
+ */
+ private async shutdown(signal: string, exitCode = 0): Promise<void> {
+ if (this.shuttingDown) return;
+ this.shuttingDown = true;
+ console.log(`Received ${signal}, shutting down…`);
+ // The CURRENT App's graceful drain (manager: interrupt runs, deny approvals, wait ≤5s
+ // for wrap-up) — claimed through the registry rather than deps, which after a hot swap
+ // would point at an already-disposed business incarnation.
+ const current = this.deps.hmr.resources.claim<PlatformCurrent>(PLATFORM_CURRENT_RESOURCE_ID);
+ if (current?.shutdown !== undefined) await current.shutdown();
+ // Disposing the host drains the App's effects (scheduler stop, manager hard-stop) and
+ // sweeps the resource registry (live ptys).
+ this.deps.hmr.dispose();
+ this.deps.channels.dispose();
+ this.ipv6Loopback?.close();
+ this.httpServer.close(() => {
+ this.deps.db.close();
+ this.cleanupInstanceFiles();
+ process.exit(exitCode);
+ });
+ // Fallback: a long-lived SSE connection may block the close callback, so force exit after 1s.
+ setTimeout(() => {
+ this.cleanupInstanceFiles();
+ process.exit(exitCode);
+ }, 1000).unref();
+ }
+
+ /** Removes the instance lock and port file (best-effort; runs on both exit paths). */
+ private cleanupInstanceFiles(): void {
+ releaseServerLock(this.config.root);
+ if (this.config.portFile === null) return;
try {
- fs.rmSync(config.portFile, { force: true });
+ fs.rmSync(this.config.portFile, { force: true });
} catch {
// Best-effort: a stale port file is rewritten by the next server.
}
}
}
-let shuttingDown = false;
-async function shutdown(signal: string, exitCode = 0): Promise<void> {
- if (shuttingDown) return;
- shuttingDown = true;
- console.log(`Received ${signal}, shutting down…`);
- deps.scheduler.stop();
- await deps.manager.shutdown(5000);
- deps.hmr.dispose();
- deps.channels.dispose();
- ipv6Loopback?.close();
- server.close(() => {
- deps.db.close();
- cleanupInstanceFiles();
- process.exit(exitCode);
- });
- // Fallback: a long-lived SSE connection may block the close callback, so force exit after 1s.
- setTimeout(() => {
- cleanupInstanceFiles();
- process.exit(exitCode);
- }, 1000).unref();
-}
+/** Exit code for "another server already owns this data root" (see lock.ts). */
+const EXIT_ALREADY_RUNNING = 3;
-process.on("SIGINT", () => void shutdown("SIGINT"));
-process.on("SIGTERM", () => void shutdown("SIGTERM"));
-
-// Desktop shell quit path: POST /api/desktop/shutdown lands here — the same graceful
-// shutdown as the signals, reachable over HTTP because a Windows child kill is a hard
-// TerminateProcess with no signal delivery.
-deps.desktop?.onShutdownRequest(() => void shutdown("desktop-shutdown"));
-
-// Client-update relay: under the shell this process is an Electron utilityProcess and
-// carries process.parentPort; wire it to the desktop service so the update routes can
-// read the shell's updater snapshot and forward check/install. Absent port (a plain
-// `penguin server|web` run, or tests) wires nothing.
-if (deps.desktop !== null) {
- const shellPort = shellPortOf(process);
- if (shellPort !== null) wireShellUpdatePort(deps.desktop, shellPort);
+/** Port announcement (PENGUIN_PORT_FILE): tmp + rename, so a polling reader never sees a partial write. */
+function writePortFile(file: string, port: number): void {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.tmp`;
+ fs.writeFileSync(tmp, `${port}\n`);
+ fs.renameSync(tmp, file);
}
-// Process-level error fallback: once a background
-// fire-and-forget promise (title generation, Session drive, etc.) throws, the error
-// reaches the process without passing through any catch — persist it first for a
-// record, then handle each case according to its nature.
-process.on("uncaughtException", (err) => {
- console.error(`[server] Uncaught exception: ${err.stack ?? err.message}`);
- deps.errors.record({ source: "process", err, code: "uncaught_exception" });
- // From this point the process state can't be trusted (the error was never converged
- // by any catch): don't swallow it — wrap up per existing shutdown semantics and exit
- // with a nonzero code (equivalent to Node's default crash exit, just with an extra
- // persist and graceful wrap-up).
- // Must exit even if shutdown itself errors — never let "caught a fatal error" turn
- // into "the process limps along in a broken state".
- void shutdown("uncaughtException", 1).catch(() => process.exit(1));
-});
-process.on("unhandledRejection", (reason) => {
- const err = reason instanceof Error ? reason : new Error(String(reason));
- console.error(`[server] Unhandled promise rejection: ${err.stack ?? err.message}`);
- deps.errors.record({ source: "process", err, code: "unhandled_rejection" });
- // Unlike uncaughtException, this **doesn't** exit: a rejected promise is a localized
- // failure of some background task, and the process state isn't compromised; dragging
- // down the entire service for it (Node's default behavior) isn't worth it — persist +
- // log, then keep serving.
-});
+// Runs on import, which is what starting this server means. It is the last line of the
+// file because main() reaches PenguinServer, whose declaration has to have been evaluated
+// by the time the call happens.
+await main();
diff --git a/packages/server/src/platform/platform.ts b/packages/server/src/platform/platform.ts
deleted file mode 100644
index 24cbc289..00000000
--- a/packages/server/src/platform/platform.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-/**
- * THE platform: the one hot-swappable unit this build of the server packages.
- *
- * The repo carries exactly one platform — versions exist BETWEEN deployments
- * (this packaged build vs the next bundle pushed over HTTP), not as parallel
- * files. When a future build changes the context shape, it bumps `version`
- * and ships the migrator alongside the new schema; the previous shape lives
- * only in already-parked documents out in the world.
- *
- * PLATFORM LAYER — WHERE POLICY BELONGS. Anything a deployment might want to
- * change (business APIs, what an agent sees, how a capability behaves) goes
- * here rather than in the runtime, and reaches installations by one HTTP push
- * instead of a rebuild. Worth remembering when something looks like it must
- * live in the shell: this code runs INSIDE the server process, so in-process
- * effects (e.g. extending process.env for the shells agents spawn) are
- * deliverable from boot() with no runtime change. See ../hmr/README.md.
- *
- * This packaged default is deliberately a bare stub: the runtime (HmrHost,
- * routes.ts) is mechanism only, and carries no business methods of its own.
- * A real business platform is pushed over HTTP and serves its own HTTP through
- * the seam in ../hmr/http-seam.ts: it sees every request before the runtime's
- * own routes do and answers null for the ones it does not own, so adding or
- * changing an endpoint needs no runtime change.
- */
-import type { WebSocket } from "ws";
-import type { Impl, Json, Park } from "@prismshadow/penguin-core/kernel";
-import { defineIface, schema, type } from "@prismshadow/penguin-core/kernel";
-import type { PlatformBundle } from "../hmr/host.js";
-import { TerminalManager } from "./terminal/manager.js";
-import type { TerminalSession } from "./terminal/session.js";
-import { terminalHttp } from "./terminal/routes.js";
-import { identityFrom } from "./terminal/identity.js";
-import { bindTerminalStream } from "./terminal/stream.js";
-
-export interface PlatformApi extends Park {
- info(): Json;
- /**
- * The HTTP seam (hmr/http-seam.ts): every request is offered here first, and null
- * declines it to the runtime's own routes. This is how a business API ships by push
- * instead of by rebuilding and redeploying every installation.
- */
- http(request: Request): Promise<Response | null>;
- /**
- * In-process accessors for the one thing the seam cannot carry: a live socket. The
- * runtime's ws transport authenticates an upgrade, then asks for the session and hands
- * the socket back for the platform's protocol to drive.
- */
- terminals(): TerminalManager;
- attachStream(ws: WebSocket, session: TerminalSession, url: URL, log: (l: string) => void): void;
-}
-
-/**
- * `terminals` is the linear-state half of this document: the pty processes themselves live
- * in the runtime's resource registry (they must — a swap disposes this tree), and the
- * document carries only their handle ids so the next instance can claim them back.
- */
-export type PlatformCtx = { motd: string; terminals?: string[] };
-
-export const PlatformIface = defineIface<PlatformApi, PlatformCtx>({
- name: "platform",
- version: 1,
- context: schema<PlatformCtx>(type({ motd: "string", "terminals?": "string[]" })),
- methods: ["park", "info", "http", "terminals", "attachStream"],
-});
-
-export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
- create(ctx, context) {
- const terminals = new TerminalManager(ctx.resources);
- // Shells started before this instance existed are still running in the registry: claim
- // them back so a push is invisible to whoever was typing in one.
- terminals.adopt(context.terminals ?? []);
- const http = terminalHttp(terminals, identityFrom(ctx.resources));
-
- return {
- // Deliberately NOT disposing the terminals here (no ctx.effect): the shells are
- // resources, and outliving a swap is the whole point. Process exit sweeps them
- // through the registry's own disposers.
- park: () => ({ motd: context.motd, terminals: terminals.handleIds() }),
- info: () => ({
- impl: "packaged",
- ifaceVersion: PlatformIface.version,
- motd: context.motd,
- terminals: terminals.handleIds().length,
- }),
- http,
- terminals: () => terminals,
- attachStream: (ws, session, url, log) => bindTerminalStream(ws, session, url, log),
- };
- },
-};
-
-/**
- * The packaged bundle the runtime boots when nothing has been pushed yet — code AND its
- * initial context together, so the runtime never hardcodes a business value of its own
- * (see hmr/host.ts's PlatformBundle: every bundle, packaged or pushed, carries `context`).
- */
-export const packagedPlatform: PlatformBundle = {
- id: "packaged",
- iface: PlatformIface,
- impl: platformImpl,
- context: { motd: "hello from the penguin hot platform" } satisfies PlatformCtx,
-};
diff --git a/packages/server/src/platform/terminal/frames.ts b/packages/server/src/terminal/frames.ts
similarity index 100%
rename from packages/server/src/platform/terminal/frames.ts
rename to packages/server/src/terminal/frames.ts
diff --git a/packages/server/src/platform/terminal/identity.ts b/packages/server/src/terminal/identity.ts
similarity index 100%
rename from packages/server/src/platform/terminal/identity.ts
rename to packages/server/src/terminal/identity.ts
diff --git a/packages/server/src/platform/terminal/input-mode.ts b/packages/server/src/terminal/input-mode.ts
similarity index 100%
rename from packages/server/src/platform/terminal/input-mode.ts
rename to packages/server/src/terminal/input-mode.ts
diff --git a/packages/server/src/platform/terminal/manager.ts b/packages/server/src/terminal/manager.ts
similarity index 98%
rename from packages/server/src/platform/terminal/manager.ts
rename to packages/server/src/terminal/manager.ts
index 7538395d..68fa0557 100644
--- a/packages/server/src/platform/terminal/manager.ts
+++ b/packages/server/src/terminal/manager.ts
@@ -14,8 +14,8 @@
import fsp from "node:fs/promises";
import type { Resources } from "@prismshadow/penguin-core/kernel";
import path from "node:path";
-import { HttpError } from "../../http/errors.js";
-import { spawnHelperHint } from "../../terminal/spawn-helper.js";
+import { HttpError } from "../http/errors.js";
+import { spawnHelperHint } from "../terminal/spawn-helper.js";
import {
TerminalSession,
expandHomePath,
diff --git a/packages/server/src/platform/terminal/output-coalescer.ts b/packages/server/src/terminal/output-coalescer.ts
similarity index 100%
rename from packages/server/src/platform/terminal/output-coalescer.ts
rename to packages/server/src/terminal/output-coalescer.ts
diff --git a/packages/server/src/platform/terminal/pty-module.ts b/packages/server/src/terminal/pty-module.ts
similarity index 98%
rename from packages/server/src/platform/terminal/pty-module.ts
rename to packages/server/src/terminal/pty-module.ts
index 2d43ab70..46bbcf75 100644
--- a/packages/server/src/platform/terminal/pty-module.ts
+++ b/packages/server/src/terminal/pty-module.ts
@@ -16,7 +16,7 @@
import { createRequire } from "node:module";
import path from "node:path";
import type { Resources } from "@prismshadow/penguin-core/kernel";
-import { ASSETS_RESOURCE_ID } from "../../hmr/host.js";
+import { ASSETS_RESOURCE_ID } from "../hmr/host.js";
/** The slice of node-pty this package uses (kept narrow so the fallback stays checkable). */
export interface NodePty {
diff --git a/packages/server/src/platform/terminal/routes.ts b/packages/server/src/terminal/routes.ts
similarity index 78%
rename from packages/server/src/platform/terminal/routes.ts
rename to packages/server/src/terminal/routes.ts
index 344570b0..28639cdb 100644
--- a/packages/server/src/platform/terminal/routes.ts
+++ b/packages/server/src/terminal/routes.ts
@@ -1,11 +1,12 @@
/**
- * Terminal control plane: `/api/terminals`, served by the PLATFORM through the HTTP seam.
+ * Terminal control plane: `/api/terminals`, one route group of the platform's Hono app.
*
- * A Hono app on the seam contract (see ../hono-seam.ts): unknown paths and methods fall
- * to notFound, which declines to whatever is next in line — so this app owns exactly the
- * six routes below and nothing else under its prefix. The identity gate is attached
- * per-route, not as a prefix middleware, so a request nothing here serves declines
- * BEFORE authentication, same as a request outside the prefix.
+ * Mounted by app.ts's createApp beside the business route groups, so all
+ * platform routes register into ONE app and swap as one unit. This group owns exactly
+ * the six routes below and nothing else under its prefix: unknown paths and methods fall
+ * to the parent app's notFound, which declines to the runtime. The identity gate is
+ * attached per-route, not as a prefix middleware, so a request nothing here serves
+ * declines BEFORE authentication, same as a request outside the prefix.
*
* Identity is resolved through a runtime capability, not re-implemented here: the seam
* runs BEFORE the auth middleware (app.ts mounts it there on purpose, so a push can
@@ -30,9 +31,8 @@
*/
import { Hono } from "hono";
import type { MiddlewareHandler } from "hono";
-import { HttpError } from "../../http/errors.js";
-import { badRequest } from "../../http/validate.js";
-import { declined, seamHttp } from "../hono-seam.js";
+import { HttpError } from "../http/errors.js";
+import { badRequest } from "../http/validate.js";
import type { TerminalManager } from "./manager.js";
import type { IdentifiedUser, Identity } from "./identity.js";
@@ -82,15 +82,6 @@ function json(body: unknown, status = 200): Response {
});
}
-/** The App's error body shape, so a platform failure reads like every other API error. */
-function errorResponse(err: unknown): Response {
- if (err instanceof HttpError) {
- return json({ error: { code: err.code, message: err.message } }, err.status);
- }
- const message = err instanceof Error ? err.message : String(err);
- return json({ error: { code: "internal", message } }, 500);
-}
-
async function readBody(request: Request): Promise<Record<string, unknown>> {
try {
return (await request.json()) as Record<string, unknown>;
@@ -102,18 +93,15 @@ async function readBody(request: Request): Promise<Record<string, unknown>> {
type TerminalEnv = { Variables: { user: IdentifiedUser } };
/**
- * Serves the terminal API, or returns null for a request this platform does not own.
- * `identity` is the runtime's capability; a request it cannot attribute is 401 here rather
- * than falling through, because falling through would hand an unauthenticated caller
- * whatever older handler sits behind the seam.
+ * The terminal route group, mounted into the platform's one Hono app beside the business
+ * groups (see app.ts's createApp). Decline (unknown path/method) and error
+ * shaping belong to the parent app; what stays here is the routes and their identity
+ * gate. `identity` is the runtime's capability; a request it cannot attribute is 401
+ * here rather than falling through, because falling through would hand an
+ * unauthenticated caller whatever older handler sits behind the seam.
*/
-export function terminalHttp(
- manager: TerminalManager,
- identity: Identity,
-): (request: Request) => Promise<Response | null> {
+export function terminalRoutes(manager: TerminalManager, identity: Identity): Hono<TerminalEnv> {
const app = new Hono<TerminalEnv>();
- app.notFound(() => declined());
- app.onError((err) => errorResponse(err));
const gate: MiddlewareHandler<TerminalEnv> = async (c, next) => {
const user = await identity(c.req.raw);
@@ -157,7 +145,7 @@ export function terminalHttp(
return json({ ok: true });
});
- return seamHttp(app);
+ return app;
}
async function create(request: Request, manager: TerminalManager, ownerUserId: string) {
diff --git a/packages/server/src/platform/terminal/session.ts b/packages/server/src/terminal/session.ts
similarity index 99%
rename from packages/server/src/platform/terminal/session.ts
rename to packages/server/src/terminal/session.ts
index df760e5f..52299045 100644
--- a/packages/server/src/platform/terminal/session.ts
+++ b/packages/server/src/terminal/session.ts
@@ -22,7 +22,7 @@ import type { Resources } from "@prismshadow/penguin-core/kernel";
import { loadNodePty } from "./pty-module.js";
import { defaultTerminalShell, shellArgs } from "./shell.js";
import { TerminalInputModeTracker } from "./input-mode.js";
-import { ensureSpawnHelperExecutable } from "../../terminal/spawn-helper.js";
+import { ensureSpawnHelperExecutable } from "../terminal/spawn-helper.js";
import {
captureLines,
renderRestoreAnsi,
diff --git a/packages/server/src/platform/terminal/shell.ts b/packages/server/src/terminal/shell.ts
similarity index 100%
rename from packages/server/src/platform/terminal/shell.ts
rename to packages/server/src/terminal/shell.ts
diff --git a/packages/server/src/platform/terminal/size-ownership.ts b/packages/server/src/terminal/size-ownership.ts
similarity index 100%
rename from packages/server/src/platform/terminal/size-ownership.ts
rename to packages/server/src/terminal/size-ownership.ts
diff --git a/packages/server/src/platform/terminal/snapshot.ts b/packages/server/src/terminal/snapshot.ts
similarity index 100%
rename from packages/server/src/platform/terminal/snapshot.ts
rename to packages/server/src/terminal/snapshot.ts
diff --git a/packages/server/src/platform/terminal/stream.ts b/packages/server/src/terminal/stream.ts
similarity index 100%
rename from packages/server/src/platform/terminal/stream.ts
rename to packages/server/src/terminal/stream.ts
diff --git a/packages/server/src/terminal/ws.ts b/packages/server/src/terminal/ws.ts
index 2537a482..ebd2f9ec 100644
--- a/packages/server/src/terminal/ws.ts
+++ b/packages/server/src/terminal/ws.ts
@@ -5,7 +5,7 @@
* handler returns one whole Response — so the runtime keeps what an upgrade needs: the
* handshake itself, the Origin check, and the session-cookie authentication it already
* owns. The moment the socket is live it is handed to the platform, which owns the
- * protocol that flows over it (platform/terminal/stream.ts): frames, coalescing, restore
+ * protocol that flows over it (terminal/stream.ts): frames, coalescing, restore
* and backpressure are all pushable, the socket plumbing is not.
*
* Auth: the session cookie rides along on the upgrade request, so the same credential as
diff --git a/packages/server/test/auth.test.ts b/packages/server/test/auth.test.ts
index efca8d9b..8501ee2f 100644
--- a/packages/server/test/auth.test.ts
+++ b/packages/server/test/auth.test.ts
@@ -6,7 +6,7 @@ import fs from "node:fs/promises";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { MeResponse, ProjectsResponse } from "../src/api/types.js";
-import { buildAppDeps } from "../src/app.js";
+import { bootAppDeps } from "../src/app.js";
import { generateInitialAdminPassword } from "../src/auth/service.js";
import {
apiClient,
@@ -38,14 +38,15 @@ describe("auth", () => {
});
it("registration is closed: no register endpoint", async () => {
- // Not logged in: no such route under /api/auth, falls into the protected-section 401.
+ // /api/auth is the runtime's own public namespace (the business platform declines it
+ // wholesale), so an unknown path in it is an honest 404, logged in or not.
const anon = await t.app.request("/api/auth/register", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ userId: "alice", password: "password-123" }),
});
- expect(anon.status).toBe(401);
- // Logged in: falls through to notFound -> 404, proving the route has indeed been removed.
+ expect(anon.status).toBe(404);
+ // Logged in: same 404, proving the route has indeed been removed.
const admin = await loginAdmin(t.app);
const res = await apiClient(t.app, admin.cookie).post("/api/auth/register", {
userId: "alice",
@@ -196,7 +197,10 @@ describe("auth", () => {
it("seedAdmin rejects an override below the password policy before creating the account", async () => {
const root = await makeTempRoot();
- const deps = buildAppDeps({ ...testConfig(root), seedAdminPassword: "x" }, { log: () => {} });
+ const deps = await bootAppDeps(
+ { ...testConfig(root), seedAdminPassword: "x" },
+ { log: () => {} },
+ );
try {
await expect(deps.authService.seedAdmin()).rejects.toThrow(/at least 8 characters/);
// Rejected before any insert: no half-created privileged account to retry around.
diff --git a/packages/server/test/desktop.test.ts b/packages/server/test/desktop.test.ts
index bd91c5a7..a583f430 100644
--- a/packages/server/test/desktop.test.ts
+++ b/packages/server/test/desktop.test.ts
@@ -110,13 +110,13 @@ describe("desktop shutdown endpoint", () => {
const plain = await createTestApp();
try {
- // Outside desktop mode the route is not mounted; the request falls through to the
- // cookie auth middleware, which rejects the cookieless caller with 401.
+ // Outside desktop mode the route is not mounted, and /api/desktop is the runtime's
+ // own namespace (the business platform declines it wholesale): an honest 404.
const res = await plain.app.request("/api/desktop/shutdown", {
method: "POST",
headers: { authorization: `Bearer ${TEST_DESKTOP_TOKEN}` },
});
- expect(res.status).toBe(401);
+ expect(res.status).toBe(404);
} finally {
await plain.cleanup();
}
diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.ts
index 05deb0ad..abb0e02d 100644
--- a/packages/server/test/helpers.ts
+++ b/packages/server/test/helpers.ts
@@ -8,7 +8,7 @@ import os from "node:os";
import path from "node:path";
import type { Hono } from "hono";
import type { OmniMessage } from "@prismshadow/penguin-core";
-import { buildAppDeps, createApp } from "../src/app.js";
+import { bootAppDeps, createRuntimeApp } from "../src/app.js";
import type { AppDeps, BuildDepsOverrides } from "../src/app.js";
import { openDatabase } from "../src/db/database.js";
import { TraceIndexRepo } from "../src/db/repos/trace-index.js";
@@ -80,14 +80,14 @@ export async function createTestApp(options: TestAppOptions = {}): Promise<TestA
const { beforeSeed, config, ...overrides } = options;
const root = await makeTempRoot();
if (beforeSeed) await beforeSeed(root);
- const deps = buildAppDeps(
+ const deps = await bootAppDeps(
{ ...testConfig(root), ...config },
{ log: () => {}, passwordHashCost: TEST_PASSWORD_HASH_COST, ...overrides },
);
// Consistent with the startup entrypoint: seed the built-in admin (owning default_project),
// keeping the password it returns (only null if a beforeSeed hook ever pre-created users).
const adminPassword = (await deps.authService.seedAdmin()) ?? TEST_ADMIN_PASSWORD;
- const app = createApp(deps);
+ const app = createRuntimeApp(deps);
return {
app,
deps,
diff --git a/packages/server/test/hmr-http-seam.test.ts b/packages/server/test/hmr-http-seam.test.ts
index 5bf85905..cb76600e 100644
--- a/packages/server/test/hmr-http-seam.test.ts
+++ b/packages/server/test/hmr-http-seam.test.ts
@@ -75,9 +75,13 @@ describe("platform HTTP seam", () => {
it("routes the platform declines still reach the runtime's own", async () => {
await pushPlatform(t.app, cookie, bundle);
- const me = await api.get("/api/me");
- expect(me.status).toBe(200);
- expect(((await me.json()) as { user: { userId: string } }).user.userId).toBe("admin");
+ // The runtime's own routes are the mechanism surface (auth, hmr, desktop, static):
+ // login still works with a fixture platform in place, because the fixture declines
+ // /api/auth and the runtime serves it. Business routes are NOT runtime fallbacks —
+ // /api/me travels with the business platform, which this push replaced.
+ const login = await loginAdmin(t.app);
+ expect(login.user.userId).toBe("admin");
+ expect((await api.get("/api/me")).status).toBe(404);
});
it("cannot claim the upgrade channel — one bad push must not lock the box out", async () => {
@@ -101,9 +105,9 @@ describe("platform HTTP seam", () => {
expect(body.error.message).toContain("deliberate platform failure");
});
- it("a platform with no http handler leaves every runtime route as it was", async () => {
- // The packaged stub has none: this is the state every installation starts in, and the
- // state an older pushed bundle stays in.
+ it("the packaged platform serves the business surface out of the box", async () => {
+ // This is the state every installation starts in: no push has happened, and the
+ // packaged platform's business routes answer through the seam.
expect((await api.get("/api/me")).status).toBe(200);
expect((await api.get("/api/demo/ping")).status).toBe(404);
});
@@ -181,21 +185,23 @@ describe("platform HTTP seam: the reachable API changes with each push", () => {
const PROBED = ["/api/demo/ping", "/api/demo/pong", "/api/me"];
it("adding, swapping and removing routes changes what the server answers", async () => {
- // Baseline: the runtime knows /api/me and nothing about the demo endpoints.
+ // Baseline: the packaged business platform serves /api/me; nothing serves the demo
+ // endpoints. ("runtime" below just means "no servedBy field in the body".)
expect(await reachable(PROBED)).toEqual({
"/api/demo/ping": "404",
"/api/demo/pong": "404",
"/api/me": "200 runtime",
});
- // Push #1 ADDS one endpoint.
+ // Push #1 ADDS one endpoint — and, because the business surface travels WITH the
+ // platform, replaces the packaged business wholesale: /api/me is gone with it.
expect(
(await pushPlatform(t.app, cookie, platformServing(["/api/demo/ping"], "v1"))).status,
).toBe(200);
expect(await reachable(PROBED)).toEqual({
"/api/demo/ping": "200 v1",
"/api/demo/pong": "404",
- "/api/me": "200 runtime",
+ "/api/me": "404",
});
// Push #2 SWAPS the route set: the first endpoint is gone, a different one appears.
@@ -205,26 +211,31 @@ describe("platform HTTP seam: the reachable API changes with each push", () => {
expect(await reachable(PROBED)).toEqual({
"/api/demo/ping": "404",
"/api/demo/pong": "200 v2",
- "/api/me": "200 runtime",
+ "/api/me": "404",
});
- // Push #3 REMOVES both: the API is back to exactly what the runtime serves.
+ // Push #3 REMOVES both: only the runtime's mechanism surface remains reachable.
expect((await pushPlatform(t.app, cookie, platformServing([], "v3"))).status).toBe(200);
expect(await reachable(PROBED)).toEqual({
"/api/demo/ping": "404",
"/api/demo/pong": "404",
- "/api/me": "200 runtime",
+ "/api/me": "404",
});
});
- it("a route the platform takes over goes back to the runtime's own when it stops serving it", async () => {
- const runtimeVersion = (await (await api.get("/api/version")).json()) as { version: string };
+ it("a route the platform stops serving vanishes with it — the runtime holds no business fallback", async () => {
+ // The packaged business platform serves /api/version…
+ expect((await api.get("/api/version")).status).toBe(200);
+ // …a pushed platform can take the path over…
await pushPlatform(t.app, cookie, platformServing(["/api/version"], "takeover"));
expect(await (await api.get("/api/version")).json()).toMatchObject({ servedBy: "takeover" });
+ // …and a push that drops it leaves the path unserved: business routes live and die
+ // with the platform version, never as a runtime copy that could answer with stale
+ // semantics.
await pushPlatform(t.app, cookie, platformServing([], "released"));
- expect(await (await api.get("/api/version")).json()).toEqual(runtimeVersion);
+ expect((await api.get("/api/version")).status).toBe(404);
});
});
diff --git a/packages/server/test/hmr-resources.test.ts b/packages/server/test/hmr-resources.test.ts
new file mode 100644
index 00000000..9f99c9b4
--- /dev/null
+++ b/packages/server/test/hmr-resources.test.ts
@@ -0,0 +1,325 @@
+/**
+ * Resource-interface reconciliation across a swap — a registry convention, not a kernel
+ * mechanism: each App's create() leaves its declaration (RESOURCE_IFACES_RESOURCE_ID)
+ * for its successor, which integrates a group only at the same version and hard-stops
+ * the rest, in reverse registration order, before adopting anything. Plus the registry's
+ * ordering contract and the runtime-capability version handshake (hmr/capabilities.ts).
+ */
+import { describe, expect, it, vi } from "vitest";
+import { boot, initialDoc, upgrade } from "@prismshadow/penguin-core/kernel";
+import { HotResources } from "../src/hmr/resources.js";
+import { TerminalManager } from "../src/terminal/manager.js";
+import type { TerminalSession } from "../src/terminal/session.js";
+import { DECLARED_RESOURCES as PARKED, packagedPlatform } from "../src/hmr/platform.js";
+import {
+ RESOURCE_IFACES_RESOURCE_ID,
+ RUNTIME_AUTH_RESOURCE_ID,
+ PENGUIN_FAMILY,
+ RUNTIME_INTERFACES,
+ RUNTIME_INTERFACES_RESOURCE_ID,
+ RUNTIME_CHANNELS_RESOURCE_ID,
+ RUNTIME_CONFIG_RESOURCE_ID,
+ RUNTIME_DB_RESOURCE_ID,
+ RUNTIME_HMR_RESOURCE_ID,
+ RUNTIME_PROXY_RESOURCE_ID,
+ claimRuntimeCapabilities,
+} from "../src/hmr/capabilities.js";
+
+/** Boots the packaged platform against `r` (capability-less: terminals-only, quiet). */
+async function bootPlatform(r: HotResources) {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ try {
+ return await boot(
+ packagedPlatform.impl,
+ packagedPlatform.iface,
+ initialDoc(packagedPlatform.iface, packagedPlatform.context),
+ r,
+ );
+ } finally {
+ warn.mockRestore();
+ }
+}
+
+describe("HotResources ordering", () => {
+ it("disposeGroup kills only the group, newest first", () => {
+ const r = new HotResources();
+ const order: string[] = [];
+ r.register("spawn:a", 1, () => order.push("a"));
+ r.register("other:x", 2, () => order.push("x"));
+ r.register("spawn:b", 3, () => order.push("b"));
+ r.disposeGroup("spawn");
+ expect(order).toEqual(["b", "a"]);
+ expect(r.claim("spawn:a")).toBeUndefined();
+ expect(r.claim("other:x")).toBe(2);
+ // A throwing disposer must not strand the rest of the group.
+ r.register("spawn:c", 4, () => {
+ throw new Error("boom");
+ });
+ r.register("spawn:d", 5, () => order.push("d"));
+ r.disposeGroup("spawn");
+ expect(order).toEqual(["b", "a", "d"]);
+ expect(r.claim("spawn:c")).toBeUndefined();
+ });
+
+ it("disposeAll runs newest first", () => {
+ const r = new HotResources();
+ const order: string[] = [];
+ r.register("a", 1, () => order.push("a"));
+ r.register("b", 2, () => order.push("b"));
+ r.disposeAll();
+ expect(order).toEqual(["b", "a"]);
+ });
+
+ it("a re-registered id counts as the NEWEST, not as its first registration", () => {
+ // Map.set on an existing key keeps its original insertion position, so without a
+ // delete-before-set the sweeps would dispose a re-registered entry (a successor
+ // adopting a pty, say) in its previous owner's slot — while both sweeps promise
+ // reverse REGISTRATION order, which later-depends-on-earlier relies on.
+ const r = new HotResources();
+ const order: string[] = [];
+ r.register("a", 1, () => order.push("a-old"));
+ r.register("b", 2, () => order.push("b"));
+ r.register("a", 3, () => order.push("a-new"));
+ r.disposeAll();
+ expect(order).toEqual(["a-new", "b"]);
+ });
+
+ it("the same holds inside a group", () => {
+ const r = new HotResources();
+ const order: string[] = [];
+ r.register("terminal:1", 1, () => order.push("1-old"));
+ r.register("terminal:2", 2, () => order.push("2"));
+ r.register("terminal:1", 3, () => order.push("1-new"));
+ r.disposeGroup("terminal");
+ expect(order).toEqual(["1-new", "2"]);
+ });
+});
+
+describe("resource-interface reconciliation at create()", () => {
+ it("a group whose declaration offers every member this build names rides across", async () => {
+ const r = new HotResources();
+ const dispose = vi.fn();
+ r.register(RESOURCE_IFACES_RESOURCE_ID, PARKED);
+ r.register("terminal:pty1", "live", dispose);
+ const inst = await bootPlatform(r);
+ try {
+ expect(dispose).not.toHaveBeenCalled();
+ expect(r.claim("terminal:pty1")).toBe("live");
+ } finally {
+ inst.dispose();
+ }
+ });
+
+ it("a predecessor missing a member this build names hard-stops the group", async () => {
+ const r = new HotResources();
+ const dispose = vi.fn();
+ r.register(RESOURCE_IFACES_RESOURCE_ID, {
+ family: PENGUIN_FAMILY,
+ terminal: ["id"],
+ platform: PARKED.platform,
+ });
+ r.register("terminal:pty1", "live", dispose);
+ const inst = await bootPlatform(r);
+ try {
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(r.claim("terminal:pty1")).toBeUndefined();
+ // …and the declaration is overwritten with this build's, for the NEXT App.
+ expect(r.claim(RESOURCE_IFACES_RESOURCE_ID)).toEqual(PARKED);
+ } finally {
+ inst.dispose();
+ }
+ });
+
+ it("a group this build stops declaring is disposed — unused resources must not leak", async () => {
+ const r = new HotResources();
+ const dispose = vi.fn();
+ // Everything this build still declares is offered in full; only `sandbox` is extra.
+ r.register(RESOURCE_IFACES_RESOURCE_ID, { ...PARKED, sandbox: ["start"] });
+ const keep = vi.fn();
+ r.register("terminal:pty1", "live", keep);
+ r.register("sandbox:provider", "live", dispose);
+ const inst = await bootPlatform(r);
+ try {
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(r.claim("sandbox:provider")).toBeUndefined();
+ // …and the groups this build DOES declare are untouched.
+ expect(keep).not.toHaveBeenCalled();
+ expect(r.claim("terminal:pty1")).toBe("live");
+ } finally {
+ inst.dispose();
+ }
+ });
+
+ it("a predecessor of a different family is not inherited from at all — nothing rides across", async () => {
+ const r = new HotResources();
+ const dispose = vi.fn();
+ // Same group name, same version, different vocabulary: `terminal` means something
+ // else over there, so this build must not adopt those handles.
+ r.register(RESOURCE_IFACES_RESOURCE_ID, { ...PARKED, family: "acme" });
+ r.register("terminal:pty1", "live", dispose);
+ const inst = await bootPlatform(r);
+ try {
+ expect(dispose).toHaveBeenCalledTimes(1);
+ expect(r.claim("terminal:pty1")).toBeUndefined();
+ } finally {
+ inst.dispose();
+ }
+ });
+
+ it("a predecessor from before the declaration existed disposes nothing (pre-declaration behavior)", async () => {
+ const r = new HotResources();
+ const dispose = vi.fn();
+ r.register("terminal:pty1", "live", dispose);
+ const inst = await bootPlatform(r);
+ try {
+ expect(dispose).not.toHaveBeenCalled();
+ expect(r.claim("terminal:pty1")).toBe("live");
+ } finally {
+ inst.dispose();
+ }
+ });
+
+ it("the declaration outlives its App to inform the successor", async () => {
+ const r = new HotResources();
+ const inst = await bootPlatform(r);
+ inst.dispose();
+ expect(r.claim(RESOURCE_IFACES_RESOURCE_ID)).toEqual(PARKED);
+ });
+
+ it("rides a real kernel swap: same declaration on both sides keeps the group", async () => {
+ const r = new HotResources();
+ const inst = await bootPlatform(r);
+ const dispose = vi.fn();
+ r.register("terminal:pty1", "live", dispose);
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const result = await upgrade({
+ current: inst,
+ impl: packagedPlatform.impl,
+ iface: packagedPlatform.iface,
+ resources: r,
+ });
+ warn.mockRestore();
+ expect(result.status).toBe("ok");
+ expect(dispose).not.toHaveBeenCalled();
+ expect(r.claim("terminal:pty1")).toBe("live");
+ if (result.status === "ok") result.instance.dispose();
+ });
+});
+
+describe("the parked-pty declaration", () => {
+ it("covers every member adoption reaches — a shorter list would TypeError after a swap", () => {
+ // The descriptor is the PROOF that adopting a predecessor's pty is safe, so it has to
+ // name everything the adopters touch. This drives the real adoption path against a
+ // session that answers ONLY the declared members and throws on anything else: shorten
+ // DECLARED_RESOURCES.terminal and this test names the member that would have blown up
+ // on the first keystroke after a push.
+ const declared = new Set<string>(PARKED.terminal);
+ const stub: Record<string, unknown> = {
+ id: "t1",
+ seq: 1,
+ ownerUserId: "u1",
+ alive: true,
+ exit: null,
+ info: () => ({ id: "t1", name: "sh" }),
+ rename: () => undefined,
+ capture: () => ({ lines: [] }),
+ write: () => undefined,
+ resize: () => undefined,
+ releaseSize: () => undefined,
+ restoreStream: () => "",
+ onOutput: () => () => undefined,
+ onExit: () => () => undefined,
+ kill: () => undefined,
+ dispose: () => undefined,
+ };
+ const strict = new Proxy(stub, {
+ get(target, prop, receiver) {
+ // Symbols and promise-probing are the runtime's own business, not the contract's.
+ if (typeof prop === "string" && prop !== "then" && !declared.has(prop)) {
+ throw new Error(`adoption reached an undeclared member: ${prop}`);
+ }
+ return Reflect.get(target, prop, receiver) as unknown;
+ },
+ }) as unknown as TerminalSession;
+
+ const r = new HotResources();
+ r.register("terminal:t1", strict);
+ const manager = new TerminalManager(r);
+ manager.adopt(["t1"]);
+ // What a fresh App does with an adopted pty right away.
+ expect(manager.handleIds()).toEqual(["t1"]);
+ expect(manager.list("u1").map((s) => s.id)).toEqual(["t1"]);
+ expect(manager.require("t1", "u1")).toBe(strict);
+ });
+});
+
+describe("runtime capability handshake", () => {
+ /** Live objects that actually carry the members RUNTIME_INTERFACES names. */
+ function stubCaps(r: HotResources): void {
+ const carrying = (name: string): Record<string, unknown> => {
+ const need = RUNTIME_INTERFACES[name];
+ const obj: Record<string, unknown> = {};
+ if (Array.isArray(need)) for (const m of need) obj[m] = () => undefined;
+ return obj;
+ };
+ r.register(RUNTIME_CONFIG_RESOURCE_ID, carrying("config"));
+ r.register(RUNTIME_DB_RESOURCE_ID, carrying("db"));
+ r.register(RUNTIME_AUTH_RESOURCE_ID, carrying("auth"));
+ r.register(RUNTIME_CHANNELS_RESOURCE_ID, carrying("channels"));
+ r.register(RUNTIME_PROXY_RESOURCE_ID, () => {});
+ r.register(RUNTIME_HMR_RESOURCE_ID, carrying("hmr"));
+ }
+
+ it("declines when the runtime publishes no descriptor (a runtime older than the handshake)", () => {
+ const r = new HotResources();
+ stubCaps(r);
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ expect(claimRuntimeCapabilities(r)).toBeNull();
+ warn.mockRestore();
+ });
+
+ it("declines when one interface is missing a member the claimer names", () => {
+ const r = new HotResources();
+ stubCaps(r);
+ r.register(RUNTIME_INTERFACES_RESOURCE_ID, { ...RUNTIME_INTERFACES, auth: ["login"] });
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ expect(claimRuntimeCapabilities(r)).toBeNull();
+ warn.mockRestore();
+ });
+
+ it("claims on a matching descriptor", () => {
+ const r = new HotResources();
+ stubCaps(r);
+ r.register(RUNTIME_INTERFACES_RESOURCE_ID, RUNTIME_INTERFACES);
+ expect(claimRuntimeCapabilities(r)).not.toBeNull();
+ });
+
+ it("declines when the descriptor is honest but the live object is not", () => {
+ // What a member set buys over a number: the declaration is verified, not trusted.
+ const r = new HotResources();
+ stubCaps(r);
+ r.register(RUNTIME_AUTH_RESOURCE_ID, { login: () => undefined }); // missing the rest
+ r.register(RUNTIME_INTERFACES_RESOURCE_ID, RUNTIME_INTERFACES);
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ expect(claimRuntimeCapabilities(r)).toBeNull();
+ warn.mockRestore();
+ });
+
+ it("declines a different family outright — the names are not comparable", () => {
+ const r = new HotResources();
+ stubCaps(r);
+ r.register(RUNTIME_INTERFACES_RESOURCE_ID, { ...RUNTIME_INTERFACES, family: "acme" });
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ expect(claimRuntimeCapabilities(r)).toBeNull();
+ warn.mockRestore();
+ });
+
+ it("an interface the claimer never names may differ freely", () => {
+ // The whole point of per-interface versions: a bump the claimer never touches must
+ // not decline the claim. `extra` is not in RUNTIME_INTERFACES, so it is not required.
+ const r = new HotResources();
+ stubCaps(r);
+ r.register(RUNTIME_INTERFACES_RESOURCE_ID, { ...RUNTIME_INTERFACES, extra: ["x"] });
+ expect(claimRuntimeCapabilities(r)).not.toBeNull();
+ });
+});
diff --git a/packages/server/test/terminal-shell.test.ts b/packages/server/test/terminal-shell.test.ts
index 180f50e5..f665db5f 100644
--- a/packages/server/test/terminal-shell.test.ts
+++ b/packages/server/test/terminal-shell.test.ts
@@ -4,7 +4,7 @@
* never does.
*/
import { describe, expect, it } from "vitest";
-import { resolveDefaultShell, shellArgs } from "../src/platform/terminal/shell.js";
+import { resolveDefaultShell, shellArgs } from "../src/terminal/shell.js";
const NO_PATH = { onPath: () => false };
const HAS = (...names: string[]) => ({ onPath: (cmd: string) => names.includes(cmd) });
diff --git a/packages/server/test/terminal-stream.test.ts b/packages/server/test/terminal-stream.test.ts
index 386777fc..a689543c 100644
--- a/packages/server/test/terminal-stream.test.ts
+++ b/packages/server/test/terminal-stream.test.ts
@@ -18,7 +18,7 @@ import {
TerminalStreamOpcode,
decodeTerminalFrame,
encodeTerminalFrame,
-} from "../src/platform/terminal/frames.js";
+} from "../src/terminal/frames.js";
const TEST_TIMEOUT = 20_000;
diff --git a/packages/server/test/terminal.test.ts b/packages/server/test/terminal.test.ts
index 3b3a999d..33b60e22 100644
--- a/packages/server/test/terminal.test.ts
+++ b/packages/server/test/terminal.test.ts
@@ -12,20 +12,20 @@ import os from "node:os";
import path from "node:path";
import xterm from "@xterm/headless";
import { createTestApp, loginAdmin, apiClient } from "./helpers.js";
-import { TerminalManager, MAX_TERMINALS_PER_USER } from "../src/platform/terminal/manager.js";
-import { expandHomePath } from "../src/platform/terminal/session.js";
+import { TerminalManager, MAX_TERMINALS_PER_USER } from "../src/terminal/manager.js";
+import { expandHomePath } from "../src/terminal/session.js";
import { repairSpawnHelpers } from "../src/terminal/spawn-helper.js";
-import { TerminalInputModeTracker } from "../src/platform/terminal/input-mode.js";
-import { TerminalOutputCoalescer } from "../src/platform/terminal/output-coalescer.js";
-import { applyTerminalSize, releaseTerminalSize } from "../src/platform/terminal/size-ownership.js";
-import { captureLines, renderRestoreAnsi } from "../src/platform/terminal/snapshot.js";
-import { resolveKeys } from "../src/platform/terminal/routes.js";
+import { TerminalInputModeTracker } from "../src/terminal/input-mode.js";
+import { TerminalOutputCoalescer } from "../src/terminal/output-coalescer.js";
+import { applyTerminalSize, releaseTerminalSize } from "../src/terminal/size-ownership.js";
+import { captureLines, renderRestoreAnsi } from "../src/terminal/snapshot.js";
+import { resolveKeys } from "../src/terminal/routes.js";
import {
TerminalStreamOpcode,
decodeTerminalFrame,
encodeTerminalFrame,
parseResizePayload,
-} from "../src/platform/terminal/frames.js";
+} from "../src/terminal/frames.js";
const { Terminal } = xterm;
diff --git a/packages/server/tsup.config.ts b/packages/server/tsup.config.ts
index 162f3a85..0ff15803 100644
--- a/packages/server/tsup.config.ts
+++ b/packages/server/tsup.config.ts
@@ -6,7 +6,7 @@ export default defineConfig({
// reset-admin-password are side-effect-free for CLI pre-checks and the offline
// admin-password rescue); "./hmr/manifest" is the host-less harness.json reader the
// CLI's thin loader resolves the current cli bundle through. There is deliberately no
- // "./platform" subpath: src/platform/entry.ts (this package's platform artifact
+ // "./platform" subpath: src/hmr/entry.ts (this package's platform artifact
// compile target — see its own module doc) is compiled straight from source by
// esbuild in scripts/deploy.mjs, never through this package's published dist,
// so it has no reason to be a tsup entry or a subpath export.
diff --git a/scripts/deploy.mjs b/scripts/deploy.mjs
index c8ddefe5..452e3eed 100644
--- a/scripts/deploy.mjs
+++ b/scripts/deploy.mjs
@@ -31,7 +31,7 @@ import { unsafePlaintextTarget } from "./deploy-target-safety.mjs";
const require = createRequire(import.meta.url);
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const WEB_DIST = path.join(ROOT, "packages", "web", "dist");
-const PLATFORM_ENTRY = path.join(ROOT, "packages", "server", "src", "platform", "entry.ts");
+const PLATFORM_ENTRY = path.join(ROOT, "packages", "server", "src", "hmr", "entry.ts");
const CLI_ENTRY = path.join(ROOT, "packages", "cli", "src", "index.ts");
const PLATFORM_BUNDLE = path.join(os.tmpdir(), `penguin-deploy-platform-${process.pid}.mjs`);
const CLI_BUNDLE = path.join(os.tmpdir(), `penguin-deploy-cli-${process.pid}.mjs`);