A local-first multi-agent app development platform, built on PenguinHarness
feat: introduce extension (#353)
Myriad-Dreamin23d8be5b1dd2
diff --git a/changelog/unreleased/2026-08-22-extension-mechanism.md b/changelog/unreleased/2026-08-22-extension-mechanism.mdnew file mode 100644index 00000000..a5f9f699--- /dev/null+++ b/changelog/unreleased/2026-08-22-extension-mechanism.md@@ -0,0 +1,20 @@+# An extension mechanism: one entry point, two typed events++- **Date:** 2026-08-22+- **Type:** feature+- **Scope:** `server`, `docs`+- **PR:** [#353](https://github.com/Prism-Shadow/penguin-harness/pull/353)++[中文版](2026-08-22-extension-mechanism.zh.md)++The harness gained an extension seam. An extension package exports one function — `activate(ctx)` — which the server runs once per process while reading `<root>/extensions.json`, before any App exists. Everything after that arrives as typed events: `"initialize"` hands over the definition view, where an extension registers workflow factories, and `"create"` hands over the assembled instance view. Both fire at every App creation, so a hot swap re-delivers them and an extension's registrations can never be seeded into an instance that has been replaced.++## Details++- Which extensions a deployment runs is configuration, not capability compiled into the platform: `<root>/extensions.json` lists package specifiers, each resolved against the installation rather than the platform bundle, so installing or upgrading one is an install-side action. An absent file means no extensions; a file that exists but cannot be read, or is malformed, fails the boot rather than presenting as a healthy server with every configured capability silently missing. An unresolvable entry, a module without an `activate` export, or a failing `activate` is reported and skipped per entry — and whatever that `activate` had already registered for cleanup runs before it is dropped.+- Extension loading runs after the single-instance pre-check, so a process about to exit with code 3 never imports third-party modules and never runs their top-level side effects.+- `ExtensionEvents` maps each event name to its payload — the one place the event vocabulary lives, so adding an event types the platform's emit and every extension's handler together.+- `activate` may be async and is awaited. Subscriptions and `ctx.disposables` are sealed once it settles; a later `on(...)` throws. Event handlers stay synchronous — one that returns a promise is refused, because an App is assembled synchronously around the emit and the rejection could only escape unhandled. A duplicate workflow name is refused too, so ownership never depends on `extensions.json` ordering. Disposables may be async, run concurrently at shutdown with failures isolated, and are awaited under the same 5-second budget as the session manager's wrap-up.+- Workflows are registration plus a plain function call — no Session, no approval, no streaming. Every registered factory is instantiated once per App, in one batch after registration closes.+- The contract an extension package compiles against is declared in the SDK, at `@prismshadow/penguin-core/extension`. `PenguinContext` and `PenguinInterface` are open: the harness contributes the members it owns by augmenting that module, and re-exports both halves from `@prismshadow/penguin-server/extension`. Both subpaths carry no runtime code, so an extension stays a self-contained library.+- The server's boot order, each subsystem's external surface, and the extension lifecycle are documented on a new Server boot page (`packages/docs/content/server-boot.en.md`).diff --git a/changelog/unreleased/2026-08-22-extension-mechanism.zh.md b/changelog/unreleased/2026-08-22-extension-mechanism.zh.mdnew file mode 100644index 00000000..5cb3aee3--- /dev/null+++ b/changelog/unreleased/2026-08-22-extension-mechanism.zh.md@@ -0,0 +1,20 @@+# 扩展机制:一个入口,两个带类型的事件++- **Date:** 2026-08-22+- **Type:** feature+- **Scope:** `server`, `docs`+- **PR:** [#353](https://github.com/Prism-Shadow/penguin-harness/pull/353)++[English](2026-08-22-extension-mechanism.md)++harness 有了扩展缝。扩展包导出一个函数 `activate(ctx)`,服务端在读取 `<root>/extensions.json` 时每进程执行它一次,此时还没有任何 App 存在。此后的一切都以带类型的事件到达:`"initialize"` 交出定义视图,扩展在其中注册 workflow factory;`"create"` 交出组装好的实例视图。两者在每次 App 创建时都会触发,因此热更新会重新投递,扩展的注册不可能只留在已被替换掉的实例里。++## 细节++- 一个部署运行哪些扩展属于配置,而不是编进平台的能力:`<root>/extensions.json` 列出包 specifier,每一条都相对**安装目录**解析而非平台 bundle,因此安装或升级扩展是安装侧的动作。文件不存在即表示没有扩展;文件存在却读不出、或格式错误,则启动失败——而不是装作健康、悄悄丢掉配置要求的全部能力。无法解析的条目、没有 `activate` 导出的模块、或 `activate` 失败,按条目记录并跳过;该 `activate` 此前已登记的清理项会在它被丢弃前执行。+- 扩展加载排在单实例预检之后,因此一个即将以退出码 3 结束的进程不会去 import 第三方模块,也不会执行它们的顶层副作用。+- `ExtensionEvents` 把每个事件名映射到它的载荷——事件词汇表只有这一处,因此新增一个事件会同时为平台的 emit 端和所有扩展 handler 提供类型。+- `activate` 可以是 async,并会被等待。订阅与 `ctx.disposables` 在它 settle 后封闭,此后再调 `on(...)` 会抛错。事件 handler 保持同步——返回 promise 的 handler 会被拒绝,因为 App 是围绕这次 emit 同步组装的,rejection 只能以未处理形式逃逸。workflow 重名同样被拒绝,名字归属不会随 `extensions.json` 顺序改变。disposable 可以是 async,关停时并发执行、单条失败被隔离,并在与会话管理器收尾相同的 5 秒预算内被等待。+- workflow 就是注册加一次普通函数调用——没有 Session、没有审批、没有流式。每个注册的 factory 在注册关闭后整批实例化,每个 App 一次。+- 扩展包所编译依赖的契约声明在 SDK 里,即 `@prismshadow/penguin-core/extension`。`PenguinContext` 与 `PenguinInterface` 是开放的:harness 通过声明合并贡献自己拥有的成员,并从 `@prismshadow/penguin-server/extension` 一并再导出。两个子路径都不携带运行时代码,因此扩展始终是一个自足库。+- 服务端的启动次序、各子系统的对外表面与扩展生命周期,记录在新增的「服务端启动」页面(`packages/docs/content/server-boot.zh.md`)。diff --git a/packages/core/package.json b/packages/core/package.jsonindex 817a0cb3..c72bd900 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -29,6 +29,10 @@"types": "./dist/interfaces/index.d.ts","import": "./dist/interfaces/index.js"},+ "./extension": {+ "types": "./dist/extension/index.d.ts",+ "import": "./dist/extension/index.js"+ },"./model-catalog": {"types": "./dist/state/model-catalog.d.ts","import": "./dist/state/model-catalog.js"diff --git a/packages/core/src/extension/index.ts b/packages/core/src/extension/index.tsnew file mode 100644index 00000000..aa93b91d--- /dev/null+++ b/packages/core/src/extension/index.ts@@ -0,0 +1,93 @@+/**+ * The extension contract: what an extension package compiles against.+ *+ * Types only — the host that drives them lives in whatever embeds this SDK (for the+ * harness, `@prismshadow/penguin-server/extension`). An extension reaches this module with+ * `import type`, so it carries no runtime dependency on either and stays a+ * self-contained library that happens to satisfy an interface.+ *+ * An extension is a module exporting one function:+ *+ * export function activate(ctx: ExtensionContext): void+ *+ * It runs once per process at load time, before any App exists. Everything after that+ * is events ({@link ExtensionEvents}), both fired at EVERY App creation — the packaged+ * boot and each hot-swap boot alike:+ *+ * - `"initialize"` — {@link PenguinInterface}, the harness's DEFINITION view, where+ * factories are registered.+ * - `"create"` — {@link PenguinContext}, an INSTANCE of the harness, assembled after+ * registration closes.+ *+ * `on(...)` and `ctx.disposables` are sealed when `activate` returns: handlers run per+ * App, so subscribing from inside one would accumulate a copy per hot swap. Sealing+ * turns that slow leak into a loud error at the packaged boot.+ *+ * {@link PenguinContext} and {@link PenguinInterface} are OPEN: an embedder contributes+ * the members it owns by augmenting this module, which is why the harness's terminals+ * are not named here. Each layer declares what it actually provides, and no layer has+ * to be reachable from this one.+ */++import type { WorkflowFactory, WorkflowInstances } from "./workflow.js";++export type { WorkflowFactory, WorkflowInstance, WorkflowInstances } from "./workflow.js";++/** A tool factory — RESERVED. The shape lands with the first extension-provided tool. */+export type ToolFactory = unknown;++/** An INSTANCE of the harness. Members an embedder owns flatten on by augmentation. */+export interface PenguinContext {+ /** Instances built from `iface.workflow`. */+ workflows: WorkflowInstances;+}++/** The DEFINITION view of the harness: factories by name. */+export interface PenguinInterface {+ /** A Map whose `set` REFUSES a duplicate name (see the harness's WorkflowFactories). */+ workflow: Map<string, WorkflowFactory>;+ /** RESERVED (see {@link ToolFactory}). */+ tool: Map<string, ToolFactory>;+}++/**+ * Event name → payload, the one place the vocabulary lives: adding an entry types the+ * platform's emit and every extension's handler at once.+ */+export interface ExtensionEvents {+ initialize: PenguinInterface;+ create: PenguinContext;+}++export interface Disposable {+ dispose(): void | Promise<void>;+}++/**+ * What `activate` receives — process-level, NOT the harness instance (that is+ * {@link PenguinContext}, delivered by `"create"`).+ */+export interface ExtensionContext {+ /**+ * Callable only while `activate` runs. Handlers are delivered synchronously and+ * unwrapped — a throwing handler fails that App's boot. A handler must NOT be async:+ * an App is assembled synchronously around the emit, so a promise could not be awaited+ * and its rejection would escape as an unhandled one. Returning a thenable is refused+ * at delivery.+ */+ on<E extends keyof ExtensionEvents>(+ event: E,+ handler: (payload: ExtensionEvents[E]) => void,+ ): void;+ /** Cleanup, disposed concurrently — entries must be mutually independent. */+ disposables: Disposable[];+}++export interface Extension {+ /**+ * May be async: loading awaits it, so a rejection is an ordinary load failure and the+ * subscription window does not seal until it settles. Event handlers, by contrast, are+ * synchronous — see {@link ExtensionContext.on}.+ */+ activate(ctx: ExtensionContext): void | Promise<void>;+}diff --git a/packages/core/src/extension/workflow.ts b/packages/core/src/extension/workflow.tsnew file mode 100644index 00000000..c5402d81--- /dev/null+++ b/packages/core/src/extension/workflow.ts@@ -0,0 +1,26 @@+/**+ * Workflows: the named units an extension registers and anyone can call.+ *+ * Registration plus a plain JS call — nothing more. Anything needing a Session,+ * approval or streaming is a different capability and does not belong on this floor.+ */++/** What a registered workflow does when called. Plain JS in, plain JS out. */+export interface WorkflowInstance {+ run(input: unknown): unknown;+}++/**+ * Called once per App creation, so a stateful factory gets a fresh instance per boot+ * and a hot swap never carries a half-built one across.+ */+export type WorkflowFactory = () => WorkflowInstance;++/** The instances one App built from the registered factories. */+export interface WorkflowInstances {+ /** In registration order. */+ names(): string[];+ get(name: string): WorkflowInstance | undefined;+ /** Throws when no such workflow is registered. */+ run(name: string, input: unknown): unknown;+}diff --git a/packages/core/tsup.config.ts b/packages/core/tsup.config.tsindex db4c07ef..61a0e356 100644--- a/packages/core/tsup.config.ts+++ b/packages/core/tsup.config.ts@@ -12,6 +12,9 @@ export default defineConfig({// producers and parsers without pulling the rest of the SDK surface."src/omnimessage/markers/index.ts","src/interfaces/index.ts",+ // The extension contract: types only, so an extension package compiles against the SDK+ // without depending on whatever embeds it.+ "src/extension/index.ts","src/state/model-catalog.ts",// Hot-update kernel: zero-dependency subpath so web can bundle it directly."src/kernel/index.ts",diff --git a/packages/docs/content/server-boot.en.md b/packages/docs/content/server-boot.en.mdnew file mode 100644index 00000000..77c34e2f--- /dev/null+++ b/packages/docs/content/server-boot.en.md@@ -0,0 +1,130 @@+---+title: Server Boot and Subsystems+description: The assembly order from process entry to HTTP listen, each subsystem's external surface, and where extensions sit in the two-level process/App lifecycle.+---++`server/src/index.ts` is a side-effecting module: importing it starts the server — the contract the CLI relies on to run a server inside its own process. The startup order is written out in `main()`, one `PenguinServer` method per step, the method name being the step name. Assembly itself is split in two — `bootAppDeps(config)` builds the runtime core, publishes its capabilities and boots the platform (the business surface is assembled inside it), while `createApp(deps)` assembles the runtime shell's Hono route table without listening — so tests can take the full app and drive it via `app.request(...)` with no port involved and without going through `index.ts` at all.++This page answers two questions: in what order does the process bring each subsystem up, from entry to listen; and what is each subsystem's **external surface** — the way others depend on it: exported types, HTTP routes, events, or the context members extensions receive.++## Process entry++| Entry | Mechanism |+| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |+| Direct | `node dist/index.js` (`start` in `server/package.json`) |+| CLI (`penguin server` / `penguin web`) | Sets `PORT`/`HOST` env vars, then `import("@prismshadow/penguin-server")` **in the same process** — no fork; `penguin web` additionally polls for readiness and opens the browser |+| Desktop | `utilityProcess.fork` launches a **separate** server process, injecting `PENGUIN_HOME`, `PORT`, `PENGUIN_DESKTOP_TOKEN`, `PENGUIN_PORT_FILE` via env |++All three converge: the same env vars drive the same module. The server's own configuration comes from environment variables only (`server/src/config.ts`); `system_config.yaml` is Agent-level state, read when a Session runs — it plays no part in server boot.++## Boot sequence++```text+main() —— one PenguinServer method per line+│+├─ ① loadEnv · installProxy dotenv first (.env may define HTTP_PROXY itself), then the proxy takes over fetch+├─ ② readConfig env only: PENGUIN_HOME, PORT, HOST, PENGUIN_WEB_DB …+├─ ③ ensureSoleInstance data root held by another live instance → exit code 3 (before the DB opens)+├─ ④ loadExtensions read <root>/extensions.json → import → fill this process's one ExtensionHost+├─ ⑤ buildDeps = bootAppDeps open the DB → runtime core (auth, ChannelHub, HmrHost) → publish the+│ capabilities (db/auth/channels/config/proxy/desktop/extension host) →+│ hmr.ensure() boots the platform: its create() assembles the WHOLE+│ business surface (services, routes, scheduler) and delivers the hooks+├─ ⑥ applyPersistedProxy the DB is open: align the dispatcher with the persisted settings+├─ ⑦ buildApp the runtime shell: guards, /api/auth, /api/desktop, /api/hmr, seam, static+├─ ⑧ seedAdmin built-in admin seed (initial-Project provisioning late-binds via the registry)+├─ ⑨ listen listening starts; the callback writes back the real port, takes the lock, writes the port file, opens the ::1 companion+└─ ⑩ installProcessHandlers signals, the desktop quit path, the process-level error fallback+```++The order is not arbitrary — four of its constraints are hard: the proxy takes over global `fetch` before any outbound request can happen; the instance lock is checked **before** the database opens, because `web.db` is single-writer; extensions finish loading **before** ⑤, and the host enters the registry with the other capabilities before the platform boots, so they are present for the very first App creation; and the platform — the whole business surface with it — finishes booting before `listen`, so **no request is ever served before business and extensions are in place**. `installProcessHandlers` comes last, after `listen`, so shutdown can never fire before there is a listener for it to close.++Extension loading sitting after `ensureSoleInstance` is deliberate too: a process about to exit with code 3 has no business importing third-party modules and running their top-level side effects first.++## Two lifecycles: process and App++The runtime core (the DB, auth, the ChannelHub, the HmrHost) is built once and lives until the process exits. **Everything else is platform-level**: the whole business surface — services, routes, the SessionManager, the Scheduler — together with the terminal manager, extension delivery and workflow instances is rebuilt at every App creation (every boot and every hot swap, a new bundle pushed via `POST /api/hmr/upgrade`).++```text+Process-level (runtime mechanism, once) App-level (the business surface, re-run per boot + per hot swap)+─────────────────────────── ─────────────────────────────────────────────────+SQLite · auth (AuthService) every business service and route (services + http/routes)+ChannelHub (SSE survives swaps) SessionManager · Scheduler+HmrHost · the resource registry TerminalManager (adopts parked ptys)+extensions.json load + activate (⑤ pub.) "initialize" / "create" event delivery · workflow instances+```++**Swap semantics: unparked state HARD-STOPS** — pending approvals are denied, active runs abort, the scheduler dies with its App, and the next App rebuilds everything from the claimed capabilities. Only resources that implement park/adopt (terminal ptys) ride across.++Resources carry an interface contract of their own — but it does not live on the kernel iface: the declaration is itself a registry entry (`resource-interfaces`, group→version by ID prefix, e.g. `{ terminal: 1, platform: 1 }`), written by each App's `create()` and left for its successor. Before adopting anything, the new App reads its predecessor's declaration and compares it with its own compiled-in one: a group both declare at the same version integrates and rides across; a group whose versions differ, or that this build stops declaring, is disposed entry by entry in **reverse registration order** and rebuilt fresh (live objects cannot be strict-parsed the way the context document is, so declaration agreement is the integration criterion). The kernel's park/validate/swap mechanism neither participates in nor knows about this convention — which means the reconciliation policy itself evolves by platform push. Runtime capabilities (`runtime:*`) get the symmetric defense on their side: a bundle carries the capability-contract version it was compiled against, and `claimRuntimeCapabilities` handshakes it against the runtime's published one before trusting any claim — a mismatch declines the whole set and degrades to terminals-only instead of a TypeError at use time.++The dividing line is the **resource registry**: it sits outside the reloadable platform tree, so it survives across Apps. The pty processes are parked in it and the new App merely reclaims their handles, which is why a hot swap is invisible to whoever is typing in a terminal; the ExtensionHost, the DB handle, the auth service and the SSE hub travel the same road — published by the runtime, claimed by each App.++This is not merely tidiness. A pushed bundle is compiled **standalone** — a self-contained ESM file (`bundle: true`, no externals) with its own module graph — so a module-level host singleton on the platform side would, after a push, be that bundle's own empty host, and every configured extension would silently vanish on the first hot push. Claiming rather than importing is what makes the packaged App and the pushed App drive the same host. When the runtime published none, the fallback is an empty host — the honest reading of "this runtime knows nothing about extensions". The same reasoning is spelled out in `terminal/identity.ts`.++## App creation: where extensions run++The full App-creation order is `platformImpl.create` in `server/src/hmr/platform.ts`:++```text+platformImpl.create+│+├─ new TerminalManager(resources) # adopt the ptys the previous instance parked+├─ extensions = extensionHostFrom(resources) # claim the host the runtime loaded in ④ (empty host if none was published)+├─ iface = { workflow: new Map(), tool: new Map() } # a fresh definition view per App+├─ extensions.emit("initialize", iface) # the definition view, to every handler, in activation order+├─ extensions.emit("create", { # the instance view, assembled after registration closes+│ workflows: instantiateWorkflows(iface.workflow), # every factory is called eagerly here+│ terminals,+│ })+├─ caps = claimRuntimeCapabilities(resources) # db/auth/channels/config/proxy/desktop+└─ business assembly (when caps are all present): buildAppDeps → scheduler.start()+ → orphaned-Goal reconciliation → createApp (terminal + business groups in ONE Hono app)+ → one registry write publishes the {deps, app, shutdown} pointer+ → ctx.effect registers the hard stop for the next swap+```++Split by frequency, the extension lifecycle has three tiers:++| Moment | Frequency | What happens |+| ----------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------- |+| Load + `activate(ctx)` | Once per process | Boot step ④ `loadExtensions`: resolve and import each specifier in `extensions.json`, then run its exported `activate` (awaited when async) — the only window where `ctx.on(...)` subscribes and `ctx.disposables` accepts cleanup. A failing entry is rolled back (its disposables run) and skipped; an unreadable or malformed `extensions.json` fails the boot |+| `"initialize"` event | Once per App | Handlers register workflow factories into the fresh `iface` (the `tool` slot is reserved, unused) |+| Workflow instantiation | Once per App | `instantiateWorkflows` calls **every** factory synchronously before the emit — instances are born in one batch at App creation, not on first call |+| `"create"` event | Once per App | Handlers receive the instance view `ctx` (`workflows` + `terminals`) |+| `workflows.run` | Per call | A plain function call: no Session, no approval, no streaming |+| Disposables | Once per process | Awaited (≤5s) in the graceful shutdown; disposers may be async, run concurrently with failures isolated — so they must be mutually independent |++Several behavioral facts follow:++- **Per-App redelivery**: `"initialize"` and `"create"` are redelivered at every App creation, so registrations always land in the current instance — a post-swap App can never run with empty registrations.+- **Instances do not cross a swap**: factories re-run per App, so a stateful workflow never carries the previous instance's state across a hot swap.+- **The subscription window is `activate`, sealed on return**: a handler-time `ctx.on(...)` would accumulate one copy per hot swap, so it throws instead — at the packaged boot, loudly, not as a slow leak. Disposables seal with the same window for the same reason.+- **Handlers are synchronous and unwrapped**: extension *loading* failures (import, or a throwing/rejecting `activate`) are isolated per entry, but event handlers run without a try/catch — a throwing handler fails that platform boot, and a handler that returns a promise is refused for the same reason (an App is assembled synchronously around the emit, so its rejection could only escape unhandled).+- **A duplicate workflow name is refused**: `iface.workflow` is a registry whose `set` throws, so a name cannot change owner depending on `extensions.json` ordering.+- **The event vocabulary is typed and lives in one place**: `ExtensionEvents` maps each name to its payload — adding an event types the platform's emit and every handler at once.++The extension contract (`Extension` / `ExtensionContext` / `ExtensionEvents` / `PenguinInterface` / `PenguinContext`) is declared in the SDK, at `@prismshadow/penguin-core/extension`. `PenguinContext` and `PenguinInterface` are open: the harness contributes the members it owns — `terminals` — by augmenting that module, and re-exports both halves from `@prismshadow/penguin-server/extension`. Both subpaths emit types only. Which extensions exist is the deployment's `<root>/extensions.json`; the harness itself imports no extension.++## Subsystem inventory++Each subsystem's construction site and external surface (step numbers refer to the boot sequence above):++| Subsystem | Constructed | External surface |+| -------------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- |+| Config | `config.ts` `resolveServerConfig` (②) | `ServerConfig`; its only post-listen mutation writes back the real port |+| Single-instance lock | `lock.ts` (③ pre-check, ⑨ acquire) | Package subpath `@prismshadow/penguin-server/lock`; the CLI and Desktop use it for pre-launch probing |+| Database | `db/database.ts` `openDatabase` (first step of ⑤)| Repo classes under `db/repos/*`; WAL, foreign keys, additive `ensureColumn` migrations |+| Auth | `auth/service.ts` (⑤, runtime mechanism) | `/api/auth/*`, the cookie `authMiddleware`, and authentication of terminal WS upgrades |+| Project / Session | `services/*` — **App-level** (assembled in create)| `/api/projects/**`, `/api/sessions/**` (route details in [Server API](/server-api)) |+| Agent runtime | `runtime/session-manager.ts` — **App-level** | Task / approval / abort / compact routes and SSE `GET /:sessionId/stream`; delegates to core via `createAgent` |+| Events | `runtime/channel.ts` `ChannelHub` (⑤, runtime; SSE streams survive swaps)| User-level SSE `GET /api/events`; the `ServerEvent` type family |+| Scheduler | `runtime/scheduler.ts` — **App-level** (started/stopped by create)| The schedules routes; publishes results into the ChannelHub |+| HMR host / platform | `hmr/host.ts` (end of ⑤) | `PlatformApi` (`park` / `info` / `http` / `terminals` / `attachStream`); `POST /api/hmr/upgrade` is a runtime-owned route, never offered to the platform |+| Terminals | `terminal/` — **App-level** | `/api/terminals*` route group (registered into the platform's one Hono app), WS `GET /api/terminals/:id/stream`; ptys are parked and survive swaps |+| Extension host | built by ④ `loadExtensions`, published to the registry in ⑤ | `activate(ctx: ExtensionContext)` + the `ExtensionEvents` registry; the configuration surface is `<root>/extensions.json` |+| Model catalog | No boot-time construction — static core data | `/api/projects/:projectId/models`; the catalog itself lives in `core/src/state/model-catalog.ts` |++One request-time path is worth knowing: the platform's HTTP seam offers every request to the current App's `http(request)` first, and only a `null` return falls through to the runtime's own routes; while a hot swap is in flight, requests queue at the seam for the new App instead of hitting a half-disposed one.++For the overall layering and the core engine boundary see the [Architecture overview](/architecture); for the HTTP route details see the [Server API](/server-api).diff --git a/packages/docs/content/server-boot.zh.md b/packages/docs/content/server-boot.zh.mdnew file mode 100644index 00000000..c3bf5897--- /dev/null+++ b/packages/docs/content/server-boot.zh.md@@ -0,0 +1,128 @@+---+title: Server 启动与子系统+description: 从进程入口到 HTTP 监听的组装顺序、各子系统的对外表面,以及扩展在进程级与 App 级两层生命周期中的位置。+---++`server/src/index.ts` 是一个副作用模块:import 它即启动服务——CLI 就是靠这一条契约在自己进程里跑起 server 的。启动次序写在 `main()` 里,每一步是 `PenguinServer` 的一个方法,方法名即步骤名。组装本身又拆成两个函数——`bootAppDeps(config)` 构建运行时核心、发布能力并启动平台(业务面在平台内组装),`createApp(deps)` 组装运行时壳层的 Hono 路由表但不监听——因此测试可以拿到完整的 app 直接 `app.request(...)`,不占端口,也不经过 `index.ts`。++本页回答两个问题:进程从入口到监听按什么顺序把子系统立起来;每个子系统的**对外表面**(surface)是什么——即别人依赖它的方式:导出类型、HTTP 路由、事件,或扩展拿到的 context 成员。++## 进程入口++| 进入方式 | 机制 |+| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |+| 直接运行 | `node dist/index.js`(`server/package.json` 的 `start`) |+| CLI(`penguin server` / `penguin web`)| 设好 `PORT`/`HOST` 环境变量后**同进程** `import("@prismshadow/penguin-server")`,不 fork;`penguin web` 额外轮询就绪后打开浏览器 |+| Desktop | `utilityProcess.fork` 拉起**独立** server 进程,经环境变量注入 `PENGUIN_HOME`、`PORT`、`PENGUIN_DESKTOP_TOKEN`、`PENGUIN_PORT_FILE` |++三种方式殊途同归:都以同一份环境变量驱动同一个模块。Server 自身的配置只来自环境变量(`server/src/config.ts`);`system_config.yaml` 是 Agent 级状态,在 Session 运行时才被读取,与 server 启动无关。++## 启动时序++```text+main() —— 每行一个 PenguinServer 方法+│+├─ ① loadEnv · installProxy dotenv 先行(.env 自己可能定义 HTTP_PROXY),随后全局代理接管 fetch+├─ ② readConfig 仅环境变量:PENGUIN_HOME、PORT、HOST、PENGUIN_WEB_DB …+├─ ③ ensureSoleInstance 数据根被另一存活实例持有 → 退出码 3(先于开库)+├─ ④ loadExtensions 读 <root>/extensions.json → import → 装进本进程唯一的 ExtensionHost+├─ ⑤ buildDeps = bootAppDeps 开库 → 运行时核心(auth、ChannelHub、HmrHost)→ 发布能力(db/auth/+│ channels/config/proxy/desktop/扩展 host)→ hmr.ensure() 启动平台:+│ 其 create() 组装整个业务面(服务、路由、scheduler)并投递扩展钩子+├─ ⑥ applyPersistedProxy 库已打开,用持久化的代理设置校准 dispatcher+├─ ⑦ buildApp 运行时壳层:守卫、/api/auth、/api/desktop、/api/hmr、seam、静态托管+├─ ⑧ seedAdmin 内置 admin 种子(初始 Project 供给经注册表晚绑定到当前业务面)+├─ ⑨ listen 开始监听;回调里回填真实端口、取实例锁、写端口文件、开 ::1 伴随监听+└─ ⑩ installProcessHandlers 信号、Desktop 退出路径、进程级错误兜底+```++这个顺序不是随意排的,其中四条是硬约束:代理在任何出站请求可能发生之前接管全局 `fetch`;单实例锁在开库**之前**预检,因为 `web.db` 是单写者;扩展在 ⑤ **之前**加载完毕,host 随其他能力一起在平台 boot 前进入注册表,因此首个 App 创建时它们已经在场;平台(连同整个业务面)在 `listen` 之前完成启动,因此**没有任何请求会在业务与扩展就位之前被服务**。收尾的 `installProcessHandlers` 排在 `listen` 之后,这样关停流程不会在监听器存在之前被触发。++扩展加载排在 `ensureSoleInstance` 之后也是有意的:一个即将以退出码 3 退出的进程不应该先去 import 一堆第三方模块、执行它们的顶层副作用。++## 两级生命周期:进程与 App++运行时核心(DB、认证、ChannelHub、HmrHost)随进程构建一次、活到进程退出。**其余全部是平台层**:整个业务面——服务、路由、SessionManager、Scheduler——连同终端管理器、扩展投递、workflow 实例,都在每次 App 创建时重建(每次启动 + 每次热更新,`POST /api/hmr/upgrade` 推送新 bundle)。++```text+进程级(运行时机制,构建一次) App 级(业务面,每次启动 + 每次热更新重跑)+────────────────────────── ────────────────────────────────+SQLite · 认证(AuthService) 全部业务服务与路由(services + http/routes)+ChannelHub(SSE 跨 swap 存活) SessionManager · Scheduler+HmrHost · 资源注册表 TerminalManager(接管寄存的 pty)+extensions.json 加载 + activate(⑤ 发布) "initialize" / "create" 事件投递 · workflow 实例+```++**swap 语义:未实现 park 的状态一律硬中止**——待审批全部拒绝、运行中任务中止、scheduler 随旧 App 死掉,新 App 从认领的能力重建一切。只有实现了 park/adopt 的资源(终端 pty)跨 swap 存活。++资源本身也有接口契约,但它不进 kernel 的 iface——声明本身就是注册表里的一个条目(`resource-interfaces`,按 ID 前缀组记版本,如 `{ terminal: 1, platform: 1 }`),由每代 App 的 `create()` 写入并留给继任者。新 App 在 adopt 任何东西之前读前任的声明、与自己编译期的声明比对:同版本的组整体集成存续;版本不同或本代不再声明的组,按**逆注册序**逐一 dispose 后重建(活对象无法像 context 文档那样 strict-parse,声明一致就是集成的判据)。kernel 的 park/validate/swap 机制不参与也不感知这套约定,因此调和策略本身也随平台热推送演进。运行时能力(`runtime:*`)走另一条对称防线:bundle 编译期携带能力契约版本,`claimRuntimeCapabilities` 先与运行时发布的版本握手,不符则整组拒领、退化为 terminals-only,而不是在使用时抛 TypeError。++分界线是**资源注册表**:它位于可重载的平台树之外,因此跨 App 存活。pty 进程本身寄存在里面,新 App 只是接管句柄——所以热更新对正在敲终端的人不可见;ExtensionHost、DB 句柄、认证服务、SSE hub 走的是同一条路:运行时发布进注册表,每个 App 认领同一份。++这一点不只是整洁问题。推送的 bundle 是**独立编译**的自包含 ESM(`bundle: true`,无 external),拥有自己的模块图;若平台侧持有一个模块级 host 单例,推送后拿到的会是 bundle 自己那个空 host,所有已配置扩展都会在第一次热推送时静默消失。认领而非导入,正是为了让打包的 App 与推送的 App 驱动同一个 host。运行时未发布 host 时回退为空 host——「这个运行时不认识扩展」的诚实读法。同样的理由见 `terminal/identity.ts`。++## App 创建:扩展的舞台++App 创建的完整顺序在 `server/src/hmr/platform.ts` 的 `platformImpl.create`:++```text+platformImpl.create+│+├─ new TerminalManager(resources) # 接管上一实例寄存的 pty+├─ extensions = extensionHostFrom(resources) # 认领运行时在 ④ 加载好的那个 host(未发布则为空 host)+├─ iface = { workflow: new Map(), tool: new Map() } # 每个 App 全新的定义视图+├─ extensions.emit("initialize", iface) # 定义视图,按激活顺序投递给每个 handler+├─ extensions.emit("create", { # 实例视图,注册关闭后组装+│ workflows: instantiateWorkflows(iface.workflow), # 全部 factory 在此被急切调用+│ terminals,+│ })+├─ caps = claimRuntimeCapabilities(resources) # db/auth/channels/config/proxy/desktop+└─ 业务面组装(caps 齐全时):buildAppDeps → scheduler.start() → 孤儿 Goal 回收+ → createApp(终端组 + 业务组注册进同一个 Hono app)+ → 一次注册表写入发布 {deps, app, shutdown} 指针 → ctx.effect 注册 swap 硬中止+```++按频率拆开,扩展生命周期是三层:++| 时机 | 频率 | 发生什么 |+| -------------- | ----------- | ---------------------------------------------------------------------------------------------------- |+| 加载 + `activate(ctx)` | 每进程一次 | 启动步骤 ④ `loadExtensions`:解析 `extensions.json` 里的 specifier、import、执行其导出的 `activate`(async 会被等待)——`ctx.on(...)` 订阅与 `ctx.disposables` 登记只在这个窗口内有效。单条失败会回滚(跑掉它已登记的 disposable)并跳过;`extensions.json` 不可读或格式错误则启动失败 |+| `"initialize"` 事件 | 每 App 一次 | handler 向全新的 `iface` 注册 workflow factory(`tool` 槽位保留未用) |+| workflow 实例化 | 每 App 一次 | `instantiateWorkflows` 在 emit 之前同步调用**全部** factory——实例随 App 创建整批诞生,不是首次调用时 |+| `"create"` | 每 App 一次 | 扩展拿到实例视图 `ctx`(`workflows` + `terminals`) |+| `workflows.run` | 每次调用 | 纯函数调用:无 Session、无审批、无流式 |+| Disposables | 每进程一次 | 优雅关停时被 await(≤5s);disposer 可以是 async,全部并发执行、单条失败被隔离——因此彼此必须独立 |++由此可以读出几条行为事实:++- **每 App 重投递**:`"initialize"` 与 `"create"` 在每次 App 创建时重新投递,注册永远落在当前实例上——热更新后的新 App 不可能带着空注册运行。+- **实例不跨热更新**:factory 每 App 重新执行,带状态的 workflow 不会把上一个实例的状态带过热更新。+- **订阅窗口就是 `activate`,返回即封闭**:handler 里再调 `ctx.on(...)` 会每次热 swap 累积一份,所以它直接抛错——在打包启动时就大声失败,而不是变成慢泄漏。disposables 与订阅同窗封闭,理由相同。+- **handler 同步且不被包裹**:扩展*加载*失败(import,或 `activate` 抛错/reject)按条目隔离,但事件 handler 没有 try/catch——抛错会使该次平台启动失败;返回 promise 的 handler 出于同样理由被拒绝(App 是围绕这次 emit 同步组装的,它的 rejection 只能以未处理形式逃逸)。+- **workflow 重名被拒绝**:`iface.workflow` 是一个 `set` 会抛错的注册表,名字的归属不会随 `extensions.json` 顺序改变。+- **事件词汇表有类型且只有一处**:`ExtensionEvents` 把每个事件名映射到它的载荷——加一个事件,平台的 emit 端和所有 handler 同时获得类型。++扩展契约(`Extension` / `ExtensionContext` / `ExtensionEvents` / `PenguinInterface` / `PenguinContext`)声明在 SDK 里,即 `@prismshadow/penguin-core/extension`。`PenguinContext` 与 `PenguinInterface` 是开放的:harness 通过对该模块做声明合并,贡献自己拥有的成员——`terminals`——并从 `@prismshadow/penguin-server/extension` 一并再导出。两个子路径都只产出类型。哪些扩展存在由部署的 `<root>/extensions.json` 决定,harness 自身不 import 任何扩展。++## 子系统一览++各子系统的构建位置与对外表面(时序编号对应上文启动时序):++| 子系统 | 构建位置 | 对外表面 |+| -------------------- | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |+| 配置 | `config.ts` `resolveServerConfig`(②) | `ServerConfig`;监听后唯一一次改写是回填真实端口 |+| 单实例锁 | `lock.ts`(③ 预检、⑨ 取锁) | 包子路径 `@prismshadow/penguin-server/lock`;CLI 与 Desktop 用它做启动前探测 |+| 数据库 | `db/database.ts` `openDatabase`(⑤ 首步) | `db/repos/*` 仓储类;WAL、外键、增量 `ensureColumn` 迁移 |+| 认证 | `auth/service.ts`(⑤,运行时机制) | `/api/auth/*`、cookie `authMiddleware`、终端 WS 升级的鉴权 |+| Project / Session | `services/*`——**App 级**(平台 create 内组装)| `/api/projects/**`、`/api/sessions/**`(路由细目见 [Server API](/server-api)) |+| Agent 运行时 | `runtime/session-manager.ts`——**App 级** | 任务 / 审批 / 中止 / 压缩路由与 SSE `GET /:sessionId/stream`;内部经 `createAgent` 委托给 core |+| 事件 | `runtime/channel.ts` `ChannelHub`(⑤,运行时;SSE 流跨 swap 存活)| 用户级 SSE `GET /api/events`;`ServerEvent` 类型族 |+| Scheduler | `runtime/scheduler.ts`——**App 级**(create 内启停)| schedules 路由;执行结果发布进 ChannelHub |+| HMR 宿主 / 平台 | `hmr/host.ts`(⑤ 末尾) | `PlatformApi`(`park` / `info` / `http` / `terminals` / `attachStream`);`POST /api/hmr/upgrade` 为运行时自留路由,不经平台 |+| 终端 | `terminal/`——**App 级** | `/api/terminals*` 路由组(注册进平台唯一的 Hono app)、WS `GET /api/terminals/:id/stream`;pty 寄存跨热更新存活 |+| 扩展宿主 | ④ `loadExtensions` 构建,⑤ 发布进资源注册表 | `activate(ctx: ExtensionContext)` + `ExtensionEvents` 事件表;配置面是 `<root>/extensions.json` |+| 模型目录 | 无启动期构建——core 静态数据 | `/api/projects/:projectId/models`;目录本体在 `core/src/state/model-catalog.ts` |++请求期还有一条固定路径值得知道:平台的 HTTP seam 把每个请求先交给当前 App 的 `http(request)`,返回 `null` 才落到运行时自己的路由;热更新进行中时请求在 seam 上排队等新 App 就绪,而不是打到半旧的实例上。++整体分层与 core 引擎的边界见[架构总览](/architecture);HTTP 路由细目见 [Server API](/server-api)。diff --git a/packages/docs/src/lib/nav.ts b/packages/docs/src/lib/nav.tsindex c0fd8d84..b5e55436 100644--- a/packages/docs/src/lib/nav.ts+++ b/packages/docs/src/lib/nav.ts@@ -45,6 +45,7 @@ export const DOCS_NAV: DocsSectionDef[] = [id: "design",pages: pages("architecture",+ "server-boot","omni-message","agent-loop","message-flow",diff --git a/packages/server/package.json b/packages/server/package.jsonindex 2fdc2b5e..24bea7fb 100644--- a/packages/server/package.json+++ b/packages/server/package.json@@ -37,6 +37,10 @@"./version-report": {"types": "./dist/version-report.d.ts","import": "./dist/version-report.js"+ },+ "./extension": {+ "types": "./dist/extension/index.d.ts",+ "import": "./dist/extension/index.js"}},"main": "./dist/index.js",diff --git a/packages/server/src/app.ts b/packages/server/src/app.tsindex 948f0f1b..2252fd63 100644--- a/packages/server/src/app.ts+++ b/packages/server/src/app.ts@@ -56,6 +56,7 @@ import { mintApiToken, storeApiToken } from "./auth/api-token.js";import type { Identity } from "./terminal/identity.js";import { terminalRoutes } from "./terminal/routes.js";import type { TerminalManager } from "./terminal/manager.js";+import { EXTENSIONS_RESOURCE_ID, type ExtensionHost } from "./extension/host.js";import type { AppEnv } from "./auth/middleware.js";import { ADMIN_USER_ID, AuthService } from "./auth/service.js";import { clearInitialAdminPassword } from "./initial-password.js";@@ -245,10 +246,16 @@ export interface BuildDepsOverrides {* 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.+ *+ * `extensions` is the host index.ts's loadExtensions step filled from extensions.json — handed in+ * rather than registered by the caller because the platform boots inside this function,+ * and everything it claims has to be in the registry first. Absent (tests), the platform+ * falls back to an empty host (see extension/index.ts's extensionHostFrom).*/export async function bootAppDeps(config: ServerConfig,overrides: BuildDepsOverrides = {},+ extensions?: ExtensionHost,): Promise<AppDeps> {const db = openDatabase(config.dbPath);@@ -322,6 +329,12 @@ export async function bootAppDeps(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);+ // The registry sweep only STARTS extension disposal (its disposers are sync) — the+ // fallback for exit paths that skip the graceful shutdown. The graceful path awaits+ // host.dispose() itself, bounded (index.ts); dispose is idempotent, so both may fire.+ if (extensions !== undefined) {+ hmr.resources.register(EXTENSIONS_RESOURCE_ID, extensions, () => void extensions.dispose());+ }// Boot the platform now rather than on the first request: the business surface —// services, routes, the scheduler — is assembled inside its create(). The check readsdiff --git a/packages/server/src/extension/host.ts b/packages/server/src/extension/host.tsnew file mode 100644index 00000000..b2629a0e--- /dev/null+++ b/packages/server/src/extension/host.ts@@ -0,0 +1,123 @@+/**+ * The extension host: it owns activation, event delivery and disposal. Kept out of+ * ./index.ts so the published `@prismshadow/penguin-server/extension` subpath stays types+ * only — an extension package cannot take a runtime dependency on the harness even by+ * accident, which is what keeps it a self-contained library.+ */+import type { Resources } from "@prismshadow/penguin-core/kernel";+import type { Disposable, Extension, ExtensionEvents } from "./index.js";++interface ActivatedPlugin {+ handlers: { [E in keyof ExtensionEvents]?: Array<(payload: ExtensionEvents[E]) => void> };+ disposables: Disposable[];+}++/** One host per server process; activation order is delivery order. */+export class ExtensionHost {+ private readonly extensions: ActivatedPlugin[] = [];++ /**+ * Runs `activate` (awaiting it when async), then seals its subscription window.+ *+ * TRANSACTIONAL: an extension may have registered disposables before it threw, and the+ * caller is about to drop it — so those run here, before the failure is reported.+ * Without this the entry is never published and `dispose()` could never reach them.+ */+ async use(extension: Extension): Promise<void> {+ const entry: ActivatedPlugin = { handlers: {}, disposables: [] };+ let sealed = false;+ try {+ await extension.activate({+ on<E extends keyof ExtensionEvents>(+ event: E,+ handler: (payload: ExtensionEvents[E]) => void,+ ) {+ if (sealed) {+ throw new Error(+ `extension subscribed to '${event}' after activate settled — a handler-time ` ++ `subscription would accumulate one copy per hot swap`,+ );+ }+ // Sound, but under a generic key TS folds the mapped type to a union.+ const list = (entry.handlers[event] ??= []) as Array<+ (payload: ExtensionEvents[E]) => void+ >;+ list.push(handler);+ },+ disposables: entry.disposables,+ });+ } catch (err) {+ sealed = true;+ await runDisposables(entry.disposables);+ throw err;+ }+ sealed = true;+ Object.freeze(entry.disposables);+ this.extensions.push(entry);+ }++ emit<E extends keyof ExtensionEvents>(event: E, payload: ExtensionEvents[E]): void {+ for (const extension of this.extensions) {+ for (const handler of extension.handlers[event] ?? []) {+ // An App is assembled synchronously around this call, so a returned promise+ // could not be awaited and its rejection would escape unhandled — possibly+ // killing the process, since boot runs before the process handlers are on.+ // Refusing it fails the boot loudly instead, which is what a throwing handler+ // already does.+ const returned = handler(payload) as { then?: unknown; catch?: unknown } | undefined;+ if (typeof returned?.then === "function") {+ // Neutralize it first: the promise is already running, and throwing below+ // without claiming it would leave its rejection unhandled — exactly the escape+ // this refusal exists to close.+ if (typeof returned.catch === "function") {+ (returned as Promise<unknown>).catch(() => {});+ }+ throw new Error(+ `extension handler for '${event}' returned a promise — event handlers must be ` ++ `synchronous (do async work in activate, or start it without awaiting)`,+ );+ }+ }+ }+ }++ /**+ * Runs every disposable concurrently, settling once all have: a failing one is logged+ * without stranding the rest, and there is deliberately no teardown order. Idempotent+ * — the graceful shutdown awaits it (bounded), the registry sweep only starts it.+ */+ async dispose(): Promise<void> {+ const extensions = this.extensions.splice(0);+ await runDisposables(extensions.flatMap((extension) => [...extension.disposables]));+ }+}++/** Concurrent, failure-isolated teardown — see {@link ExtensionHost.dispose}. */+async function runDisposables(disposables: readonly Disposable[]): Promise<void> {+ await Promise.all(+ disposables.map(async (disposable) => {+ try {+ await disposable.dispose();+ } catch (err) {+ console.warn(+ `[extensions] disposer failed: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+ }),+ );+}++/** Registry key the runtime publishes its loaded host under. */+export const EXTENSIONS_RESOURCE_ID = "runtime:extensions";++/**+ * The host the runtime loaded (see ./loader.ts), or an empty one — the honest reading+ * of "this runtime knows nothing about extensions".+ *+ * CLAIMED, not imported: a pushed bundle is compiled standalone, so a module-level host+ * inside it would be a second, empty one and every configured extension would go missing+ * on the first hot push.+ */+export function extensionHostFrom(resources: Resources): ExtensionHost {+ return resources.claim<ExtensionHost>(EXTENSIONS_RESOURCE_ID) ?? new ExtensionHost();+}diff --git a/packages/server/src/extension/index.ts b/packages/server/src/extension/index.tsnew file mode 100644index 00000000..d60812f1--- /dev/null+++ b/packages/server/src/extension/index.ts@@ -0,0 +1,30 @@+/**+ * The harness's extension surface — the `@prismshadow/penguin-server/extension` subpath.+ *+ * The contract itself lives in `@prismshadow/penguin-core/extension`; what this module adds+ * is the harness's own members, contributed by AUGMENTING that contract rather than by+ * redeclaring it. Core names nothing it cannot reach, this layer names what it owns, and+ * an extension sees one `PenguinContext` either way.+ *+ * Re-exported here so an extension package has one import site for both halves.+ */+import type { TerminalManager } from "../terminal/manager.js";++declare module "@prismshadow/penguin-core/extension" {+ interface PenguinContext {+ terminals: TerminalManager;+ }+}++export type {+ Disposable,+ PenguinContext,+ PenguinInterface,+ Extension,+ ExtensionContext,+ ExtensionEvents,+ ToolFactory,+ WorkflowFactory,+ WorkflowInstance,+ WorkflowInstances,+} from "@prismshadow/penguin-core/extension";diff --git a/packages/server/src/extension/loader.ts b/packages/server/src/extension/loader.tsnew file mode 100644index 00000000..25e4dc14--- /dev/null+++ b/packages/server/src/extension/loader.ts@@ -0,0 +1,114 @@+/**+ * Extension loading: WHICH extensions a deployment runs is CONFIGURATION, not capability+ * baked into the platform. They do not ride the platform bundle and no hot push+ * delivers one — `<root>/extensions.json` lists them and each entry resolves against the+ * INSTALLATION, so installing or upgrading one is an install-side action.+ *+ * Resolution is anchored at `process.argv[1]`, for the same reason the packaged+ * bundle's own resolver is: a bundle running from `hmr/store` has no node_modules of+ * its own, so anchoring at the bundle would find nothing.+ *+ * Failure is per-entry and non-fatal: an unresolvable or malformed extension is reported+ * and skipped, leaving its capability unavailable rather than failing the boot.+ */+import fs from "node:fs/promises";+import { createRequire } from "node:module";+import path from "node:path";+import { pathToFileURL } from "node:url";+import type { Extension } from "./index.js";++/** The config file's name inside the data root. */+export const EXTENSIONS_FILE = "extensions.json";++export interface LoadedExtension {+ specifier: string;+ extension: Extension;+}++export interface ExtensionLoadResult {+ loaded: LoadedExtension[];+ /** specifier → why it was skipped. */+ failed: Map<string, string>;+}++/**+ * An ABSENT file means "no extensions" — the default deployment shape, not an error. Any+ * other outcome is: a file that exists but cannot be read (a permission, a directory in+ * its place, an I/O fault) is indistinguishable from a malformed one for the operator's+ * purposes — something was configured and this process cannot honor it, so running+ * unconfigured would misrepresent what was asked for.+ */+export async function readExtensionList(root: string): Promise<string[]> {+ let text: string;+ try {+ text = await fs.readFile(path.join(root, EXTENSIONS_FILE), "utf8");+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw new Error(+ `${EXTENSIONS_FILE} exists but could not be read: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(text);+ } catch (err) {+ throw new Error(+ `${EXTENSIONS_FILE} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+ const list = (parsed as { extensions?: unknown }).extensions;+ if (!Array.isArray(list) || list.some((entry) => typeof entry !== "string")) {+ throw new Error(`${EXTENSIONS_FILE} must be { "extensions": ["<package specifier>", …] }`);+ }+ return list as string[];+}++/** Resolved against the installation rather than the bundle's location. */+async function importExtension(specifier: string): Promise<unknown> {+ const entry = process.argv[1];+ if (typeof entry === "string" && entry.length > 0) {+ try {+ const resolved = createRequire(entry).resolve(specifier);+ return await import(pathToFileURL(resolved).href);+ } catch {+ // Fall through: a dev checkout resolves the specifier directly.+ }+ }+ return await import(specifier);+}++/** An extension module's contract is one named export: `activate(ctx)`. */+function asExtension(module: unknown): Extension | null {+ const activate = (module as { activate?: unknown }).activate;+ return typeof activate === "function" ? { activate: activate as Extension["activate"] } : null;+}++/**+ * Loads every configured extension.+ *+ * The two failure classes are deliberately different. A PER-ENTRY failure (unresolvable+ * specifier, no `activate` export, a throw at import) is collected and skipped: that+ * capability is unavailable, which a deployment can recover from. A CONFIG-level failure+ * — the list itself unreadable or malformed — THROWS, because there is no honest way to+ * continue: the operator configured something this process cannot even read, and booting+ * with an empty extension set would present as a healthy server that silently dropped every+ * capability the config asked for.+ */+export async function loadExtensions(root: string): Promise<ExtensionLoadResult> {+ const failed = new Map<string, string>();+ const specifiers = await readExtensionList(root);+ const loaded: LoadedExtension[] = [];+ for (const specifier of specifiers) {+ try {+ const extension = asExtension(await importExtension(specifier));+ if (extension === null) {+ failed.set(specifier, "module does not export an activate(ctx) function");+ continue;+ }+ loaded.push({ specifier, extension });+ } catch (err) {+ failed.set(specifier, err instanceof Error ? err.message : String(err));+ }+ }+ return { loaded, failed };+}diff --git a/packages/server/src/extension/workflow.ts b/packages/server/src/extension/workflow.tsnew file mode 100644index 00000000..0dd4eaa2--- /dev/null+++ b/packages/server/src/extension/workflow.ts@@ -0,0 +1,36 @@+/**+ * Building the workflow instance view. The types are the SDK's contract+ * (`@prismshadow/penguin-core/extension`); this is the harness's implementation of it.+ */+import type { WorkflowFactory, WorkflowInstance, WorkflowInstances } from "./index.js";++/**+ * The Map handed to extensions at `"initialize"` — `iface.workflow` itself — with the one+ * guarantee the contract states: a duplicate name is an ERROR, not a silent replacement.+ * A bare Map would make the winner depend on extensions.json ordering, and an extension could+ * take over a name another one already owns without either noticing.+ *+ * Named for what it holds rather than for the concept: a workflow REGISTRY is the App's+ * live workflow set, which holds this map and adds instances, lifetimes and the surfaces+ * an installed workflow needs.+ */+export class WorkflowFactories extends Map<string, WorkflowFactory> {+ override set(name: string, factory: WorkflowFactory): this {+ if (this.has(name)) throw new Error(`workflow '${name}' is already registered`);+ return super.set(name, factory);+ }+}++export function instantiateWorkflows(factories: Map<string, WorkflowFactory>): WorkflowInstances {+ const instances = new Map<string, WorkflowInstance>();+ for (const [name, factory] of factories) instances.set(name, factory());+ return {+ names: () => [...instances.keys()],+ get: (name) => instances.get(name),+ run(name, input) {+ const instance = instances.get(name);+ if (instance === undefined) throw new Error(`no workflow named '${name}'`);+ return instance.run(input);+ },+ };+}diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.tsindex e3c2abd9..56c2c951 100644--- a/packages/server/src/hmr/platform.ts+++ b/packages/server/src/hmr/platform.ts@@ -38,6 +38,9 @@ import {claimRuntimeCapabilities,} from "./capabilities.js";import type { Interfaces, MembersOf } from "./capabilities.js";+import type { PenguinInterface } from "../extension/index.js";+import { extensionHostFrom } from "../extension/host.js";+import { instantiateWorkflows, WorkflowFactories } from "../extension/workflow.js";export interface PlatformApi extends Park {info(): Json;@@ -87,11 +90,10 @@ export const PlatformIface = defineIface<PlatformApi, PlatformCtx>({/*** 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.+ * predecessor declared only at the SAME 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.*/interface ParkedInterfaces extends Interfaces {family: string;@@ -190,6 +192,20 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {// wraps caps.authService, the same object the business routes authenticate with. A// bare kernel has no auth — terminals stay fail-closed there.const identity = identityFrom(caps?.authService ?? null);+ // The extension seam (see ../extension/index.ts): the definition view first, then the+ // instance context, with the workflows built in between — so an extension that registers+ // one always sees it instantiated in the App it registered into. The host is CLAIMED+ // from the registry, never imported (see extensionHostFrom).+ const extensions = extensionHostFrom(ctx.resources);+ const extIface: PenguinInterface = {+ workflow: new WorkflowFactories(),+ tool: new Map(),+ };+ extensions.emit("initialize", extIface);+ extensions.emit("create", {+ workflows: instantiateWorkflows(extIface.workflow),+ terminals,+ });// The business deps, built per App over the runtime's published capabilities — see// app.ts's buildAppDeps and ./capabilities.ts. Null only for a declared bare kernel;diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex e8d54aaf..4da4f108 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -8,7 +8,8 @@* 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+ * lock before the database opens, extensions loaded before the platform boots against them,+ * 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).@@ -28,6 +29,8 @@ import {storeInitialAdminPassword,} from "./initial-password.js";import { applyProxySettings, installGlobalProxyDispatcher } from "./net/proxy.js";+import { ExtensionHost } from "./extension/host.js";+import { loadExtensions } from "./extension/loader.js";import { attachTerminalWebSocket } from "./terminal/ws.js";import { loopbackHostRoles } from "./services/preview-token.js";import { acquireServerLock, liveServerLock, releaseServerLock } from "./lock.js";@@ -45,6 +48,7 @@ async function main(): Promise<void> {server.installProxy();server.readConfig();await server.ensureSoleInstance();+ await server.loadExtensions();await server.buildDeps();server.applyPersistedProxy();server.buildApp();@@ -63,6 +67,8 @@ async function main(): Promise<void> {class PenguinServer {/** Assigned by readConfig(); every later step reads it. */private config!: ServerConfig;+ /** Assigned by loadExtensions(); published to the platform tree by buildDeps(). */+ private extensions!: ExtensionHost;/** Assigned by buildDeps(); the merged runtime + business view (see app.ts). */private deps!: AppDeps;/** Assigned by buildApp(). */@@ -113,13 +119,44 @@ class PenguinServer {}/**- * 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.+ * Extensions are configuration, and reading configuration is the runtime's job: take the+ * specifiers extensions.json names, import them, and register each into this process's one+ * ExtensionHost. Once per process — a hot swap re-delivers the hooks to these same extension+ * objects, which is the host's job, but must never import them again.+ *+ * An extension that fails to load is skipped with a warning instead of taking the server+ * down: the capability it would have provided stays unavailable, which a deployment can+ * recover from, whereas a server that refuses to boot serves nobody.+ */+ async loadExtensions(): Promise<void> {+ this.extensions = new ExtensionHost();+ const result = await loadExtensions(this.config.root);+ for (const { specifier, extension } of result.loaded) {+ // use() runs the extension's activate (awaiting an async one) and rolls back whatever+ // it registered before failing; a throw here is a LOAD failure, isolated per entry+ // like an import failure, not a per-App handler failure.+ try {+ await this.extensions.use(extension);+ } catch (err) {+ result.failed.set(specifier, err instanceof Error ? err.message : String(err));+ }+ }+ for (const [specifier, reason] of result.failed) {+ console.warn(`[extensions] skipped ${specifier}: ${reason}`);+ }+ }++ /**+ * Builds the service graph: opens the database, publishes the runtime capabilities —+ * the loaded extension host among them — and boots the platform, whose create() assembles+ * the whole business surface (services, routes, the scheduler) and delivers the extension+ * hooks. The host is handed in rather than registered here because the platform boots+ * INSIDE bootAppDeps: everything it claims has to be in the registry first, and the+ * registry is the only way a pushed bundle — compiled standalone — can reach these+ * extension objects at all (see extension/index.ts's extensionHostFrom).*/async buildDeps(): Promise<void> {- this.deps = await bootAppDeps(this.config);+ this.deps = await bootAppDeps(this.config, {}, this.extensions);}/**@@ -313,6 +350,14 @@ class PenguinServer {// for wrap-up) — through the instance the host holds, which a hot swap keeps current;// no registry pointer needed.await (await this.deps.hmr.ensure()).api.shutdown();+ // Extension disposables: async-capable and awaited HERE — the one exit path that can+ // await — under the same ≤5s convention as the manager's wrap-up above. The registry+ // sweep below would only fire them without awaiting. Idempotent, so the sweep's+ // fallback firing right after is a no-op.+ await Promise.race([+ this.extensions.dispose(),+ new Promise<void>((resolve) => setTimeout(resolve, 5000).unref()),+ ]);// Disposing the host drains the App's effects (scheduler stop, manager hard-stop) and// sweeps the resource registry (live ptys).this.deps.hmr.dispose();diff --git a/packages/server/test/extension-loader.test.ts b/packages/server/test/extension-loader.test.tsnew file mode 100644index 00000000..9d8aa009--- /dev/null+++ b/packages/server/test/extension-loader.test.ts@@ -0,0 +1,105 @@+/**+ * Behavior tests for extension loading: extensions are CONFIGURATION read from the data+ * root, resolved against the installation, and every failure is per-entry and+ * non-fatal — the capability an extension would have provided stays unavailable rather+ * than the boot failing.+ */+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { mkdtemp, rm, writeFile, mkdir } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { EXTENSIONS_FILE, loadExtensions, readExtensionList } from "../src/extension/loader.js";++let root: string;++beforeEach(async () => {+ root = await mkdtemp(path.join(tmpdir(), "penguin-extensions-"));+});+afterEach(async () => {+ await rm(root, { recursive: true, force: true });+});++async function writeConfig(value: unknown): Promise<void> {+ await writeFile(path.join(root, EXTENSIONS_FILE), JSON.stringify(value), "utf8");+}++/** An extension module on disk, imported by absolute specifier (the dev-checkout path). */+async function writeExtensionModule(name: string, body: string): Promise<string> {+ const dir = path.join(root, "mods");+ await mkdir(dir, { recursive: true });+ const file = path.join(dir, `${name}.mjs`);+ await writeFile(file, body, "utf8");+ return file;+}++describe("extension list", () => {+ it("no config file means no extensions — the default deployment shape, not an error", async () => {+ expect(await readExtensionList(root)).toEqual([]);+ expect(await loadExtensions(root)).toEqual({ loaded: [], failed: new Map() });+ });++ it("reads the configured specifiers in order", async () => {+ await writeConfig({ extensions: ["a", "b"] });+ expect(await readExtensionList(root)).toEqual(["a", "b"]);+ });++ it("a malformed config fails the load rather than presenting as empty", async () => {+ await writeFile(path.join(root, EXTENSIONS_FILE), "{not json", "utf8");+ await expect(readExtensionList(root)).rejects.toThrow(/not valid JSON/);+ // A CONFIG-level failure propagates: booting with an empty extension set would present+ // as healthy while silently dropping every capability the config asked for.+ await expect(loadExtensions(root)).rejects.toThrow(/not valid JSON/);+ });++ it("a config that exists but cannot be read is an error, not 'no extensions'", async () => {+ // A directory in its place stands in for every non-ENOENT read failure (EACCES,+ // EPERM, EISDIR, an I/O fault): something was configured and cannot be honored.+ await mkdir(path.join(root, EXTENSIONS_FILE));+ await expect(readExtensionList(root)).rejects.toThrow(/exists but could not be read/);+ await expect(loadExtensions(root)).rejects.toThrow(/exists but could not be read/);+ });++ it("a config with the wrong shape names the shape it wanted", async () => {+ await writeConfig({ extensions: [1, 2] });+ await expect(readExtensionList(root)).rejects.toThrow(/package specifier/);+ });+});++describe("extension loading", () => {+ it("loads an extension module's exported activate", async () => {+ const file = await writeExtensionModule("ok", "export function activate() {}");+ await writeConfig({ extensions: [file] });+ const result = await loadExtensions(root);+ expect(result.failed.size).toBe(0);+ expect(result.loaded).toHaveLength(1);+ expect(result.loaded[0]!.specifier).toBe(file);+ expect(typeof result.loaded[0]!.extension.activate).toBe("function");+ });++ it("an unresolvable specifier is skipped with its reason, not fatal", async () => {+ const good = await writeExtensionModule("good", "export function activate() {}");+ await writeConfig({ extensions: ["@nope/definitely-not-installed", good] });+ const result = await loadExtensions(root);+ // The good one still loads: failure is per entry.+ expect(result.loaded.map((entry) => entry.specifier)).toEqual([good]);+ expect(result.failed.get("@nope/definitely-not-installed")).toBeTruthy();+ });++ it("a module without an activate export is skipped, saying what was expected", async () => {+ const file = await writeExtensionModule("bad", "export default { activate() {} };");+ await writeConfig({ extensions: [file] });+ const result = await loadExtensions(root);+ // The contract is the NAMED export — an activate tucked inside a default object is+ // not it, and tolerating it would fork the ecosystem into two shapes.+ expect(result.loaded).toEqual([]);+ expect(result.failed.get(file)).toMatch(/activate\(ctx\) function/);+ });++ it("an extension that throws while loading is skipped with its error", async () => {+ const file = await writeExtensionModule("throws", "throw new Error('boom at import');");+ await writeConfig({ extensions: [file] });+ const result = await loadExtensions(root);+ expect(result.loaded).toEqual([]);+ expect(result.failed.get(file)).toMatch(/boom at import/);+ });+});diff --git a/packages/server/test/extension.test.ts b/packages/server/test/extension.test.tsnew file mode 100644index 00000000..efcfe224--- /dev/null+++ b/packages/server/test/extension.test.ts@@ -0,0 +1,336 @@+/**+ * Behavior tests for the extension seam: activate-once and its sealed subscription window,+ * typed event delivery in activation order, the two views (definition iface / flattened+ * instance context), disposables, workflow registration and calling, and re-delivery on+ * the boot a hot swap performs.+ */+import { describe, expect, it, vi } from "vitest";+import { boot, initialDoc } from "@prismshadow/penguin-core/kernel";+import { HotResources } from "../src/hmr/resources.js";+import { packagedPlatform } from "../src/hmr/platform.js";+import { PENGUIN_FAMILY, RUNTIME_INTERFACES_RESOURCE_ID } from "../src/hmr/capabilities.js";+import { EXTENSIONS_RESOURCE_ID, ExtensionHost, extensionHostFrom } from "../src/extension/host.js";+import type { PenguinContext, PenguinInterface } from "../src/extension/index.js";+import { instantiateWorkflows, WorkflowFactories } from "../src/extension/workflow.js";+import type { WorkflowFactory } from "../src/extension/index.js";++function emptyIface(): PenguinInterface {+ // The registry, not a bare Map: that IS the surface an extension gets (see platform.ts).+ return { workflow: new WorkflowFactories(), tool: new Map() };+}++/**+ * A registry whose host declares itself a bare kernel — right family, no capabilities+ * offered. That declaration is what makes a terminals-only boot legal (see+ * capabilities.ts's RuntimeClaim); extension delivery is business-independent, so this is+ * all these tests need behind the platform.+ */+function bareKernel(): HotResources {+ const r = new HotResources();+ r.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });+ return r;+}++/** Boot over `r`, muting the terminals-only warning a bare kernel legitimately prints. */+async function quietBoot(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("extension host", () => {+ it("activate runs once; typed events deliver both views in activation order", async () => {+ const host = new ExtensionHost();+ const log: string[] = [];+ let activations = 0;+ let seenIface: PenguinInterface | null = null;+ let seenCtx: PenguinContext | null = null;+ await host.use({+ activate(extCtx) {+ activations++;+ extCtx.on("initialize", (iface) => {+ seenIface = iface;+ log.push("a:initialize");+ });+ extCtx.on("create", (ctx) => {+ seenCtx = ctx;+ log.push("a:create");+ });+ },+ });+ await host.use({ activate: (extCtx) => extCtx.on("create", () => log.push("b:create")) });++ const iface = emptyIface();+ host.emit("initialize", iface);+ const ctx = { workflows: instantiateWorkflows(iface.workflow) } as PenguinContext;+ host.emit("create", ctx);+ const iface2 = emptyIface();+ host.emit("initialize", iface2);++ // activate ran once per extension, while every event delivery re-walked the handlers.+ expect(activations).toBe(1);+ expect(log).toEqual(["a:initialize", "a:create", "b:create", "a:initialize"]);+ expect(seenIface).toBe(iface2);+ expect(seenCtx).toBe(ctx);+ });++ it("a subscription-less extension is fine, and events with no handlers deliver to no one", async () => {+ const host = new ExtensionHost();+ await host.use({ activate: () => {} });+ expect(() => {+ host.emit("initialize", emptyIface());+ host.emit("create", {} as PenguinContext);+ }).not.toThrow();+ });++ it("the subscription window seals when activate settles", async () => {+ const host = new ExtensionHost();+ let leaked: ((event: "create", handler: (ctx: PenguinContext) => void) => void) | null = null;+ await host.use({+ activate(extCtx) {+ leaked = (event, handler) => extCtx.on(event, handler);+ },+ });+ // A handler-time (or any later) subscription would accumulate one copy per hot+ // swap; the seal turns the leak into a loud error.+ expect(() => leaked!("create", () => {})).toThrow(/after activate settled/);+ });++ it("dispose runs disposables concurrently, awaits async ones, and isolates failures", async () => {+ const host = new ExtensionHost();+ const done: string[] = [];+ let release!: () => void;+ const gate = new Promise<void>((resolve) => (release = resolve));+ await host.use({+ activate(extCtx) {+ extCtx.disposables.push({+ dispose: async () => {+ await gate;+ done.push("slow");+ },+ });+ extCtx.disposables.push({+ dispose: () => {+ throw new Error("sync boom");+ },+ });+ extCtx.disposables.push({ dispose: () => Promise.reject(new Error("async boom")) });+ extCtx.disposables.push({+ dispose: () => {+ done.push("fast");+ },+ });+ },+ });+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ try {+ const pending = host.dispose();+ // Concurrent, not sequential: the fast disposer is not queued behind the gated one.+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(done).toEqual(["fast"]);+ // dispose settles only once the slowest async disposer has.+ release();+ await pending;+ expect(done).toEqual(["fast", "slow"]);+ // Both failure shapes (sync throw, rejected promise) were isolated and reported.+ expect(warn).toHaveBeenCalledTimes(2);++ // Idempotent: a second call finds no extensions and re-runs nothing.+ await host.dispose();+ expect(done).toEqual(["fast", "slow"]);+ expect(warn).toHaveBeenCalledTimes(2);+ } finally {+ warn.mockRestore();+ }+ });+});++describe("extension host — activation is transactional", () => {+ it("an async activate is awaited, so its rejection is an ordinary load failure", async () => {+ const host = new ExtensionHost();+ const order: string[] = [];+ await expect(+ host.use({+ async activate(extCtx) {+ await Promise.resolve();+ // Subscribing AFTER an await still counts as inside the window: the seal+ // waits for activate to settle, not for it to return a promise.+ extCtx.on("create", () => order.push("late-subscription-ran"));+ throw new Error("async boom");+ },+ }),+ ).rejects.toThrow(/async boom/);+ // The failed extension is not published, so nothing it registered is ever delivered.+ host.emit("create", {} as PenguinContext);+ expect(order).toEqual([]);+ });++ it("a failed activate still runs whatever it had already registered for cleanup", async () => {+ const host = new ExtensionHost();+ let disposed = 0;+ await expect(+ host.use({+ activate(extCtx) {+ extCtx.disposables.push({ dispose: () => void disposed++ });+ throw new Error("boom after registering");+ },+ }),+ ).rejects.toThrow(/boom after registering/);+ // Rolled back at the failure — the entry is dropped, so dispose() could never+ // reach these, and a watcher/socket/child would leak for the process's lifetime.+ expect(disposed).toBe(1);+ await host.dispose();+ expect(disposed).toBe(1);+ });++ it("an async event handler is refused, and its rejection cannot escape", async () => {+ const host = new ExtensionHost();+ const rejections: unknown[] = [];+ const onRejection = (reason: unknown): void => void rejections.push(reason);+ process.on("unhandledRejection", onRejection);+ try {+ await host.use({+ activate: (extCtx) =>+ extCtx.on("create", async () => {+ throw new Error("would-be unhandled");+ }),+ });+ expect(() => host.emit("create", {} as PenguinContext)).toThrow(+ /handler for 'create' returned a promise/,+ );+ // The refusal claims the promise, so the boot failure above is the ONLY signal —+ // an escaping rejection could otherwise kill a process still installing handlers.+ await new Promise((resolve) => setImmediate(resolve));+ expect(rejections).toEqual([]);+ } finally {+ process.off("unhandledRejection", onRejection);+ }+ });+});++describe("workflows: registration and plain invocation", () => {+ it("a registered factory becomes a callable instance on the context", () => {+ const iface = emptyIface();+ iface.workflow.set("greet", () => ({ run: (input) => `hello ${String(input)}` }));+ const workflows = instantiateWorkflows(iface.workflow);+ expect(workflows.names()).toEqual(["greet"]);+ expect(workflows.run("greet", "world")).toBe("hello world");+ expect(workflows.get("greet")).toBeDefined();+ });++ it("calling an unregistered workflow says so rather than returning undefined", () => {+ const workflows = instantiateWorkflows(new Map());+ expect(() => workflows.run("nope", null)).toThrow(/no workflow named 'nope'/);+ expect(workflows.get("nope")).toBeUndefined();+ });++ it("each App creation builds fresh instances, so per-instance state never rides a swap", () => {+ const factories = new Map<string, WorkflowFactory>();+ factories.set("counter", () => {+ let n = 0;+ return { run: () => ++n };+ });+ const first = instantiateWorkflows(factories);+ expect(first.run("counter", null)).toBe(1);+ expect(first.run("counter", null)).toBe(2);+ // What a hot swap does: build the App again from the same factories.+ expect(instantiateWorkflows(factories).run("counter", null)).toBe(1);+ });++ it("a duplicate workflow name is refused, not silently replaced", () => {+ const iface = emptyIface();+ iface.workflow.set("same", () => ({ run: () => "A" }));+ // A bare Map would let the winner depend on extensions.json ordering, and an extension+ // could take over a name another one owns without either noticing.+ expect(() => iface.workflow.set("same", () => ({ run: () => "B" }))).toThrow(+ /workflow 'same' is already registered/,+ );+ expect(instantiateWorkflows(iface.workflow).run("same", null)).toBe("A");+ });++ it("registration order is the order the names come back in", () => {+ const factories = new Map<string, WorkflowFactory>();+ for (const name of ["b", "a", "c"]) factories.set(name, () => ({ run: () => name }));+ expect(instantiateWorkflows(factories).names()).toEqual(["b", "a", "c"]);+ });+});++describe("extensionHostFrom", () => {+ it("claims the host the runtime published", () => {+ const host = new ExtensionHost();+ const resources = new HotResources();+ resources.register(EXTENSIONS_RESOURCE_ID, host);+ expect(extensionHostFrom(resources)).toBe(host);+ });++ it("falls back to an empty host when nothing was published", () => {+ const iface: PenguinInterface = emptyIface();+ // No throw, and nothing registers into the iface: no published host means no extensions.+ extensionHostFrom(new HotResources()).emit("initialize", iface);+ expect(iface.workflow.size).toBe(0);+ });+});++describe("extension seam on the real platform", () => {+ it("boots an App when the runtime published no host at all", async () => {+ const inst = await quietBoot(bareKernel());+ try {+ expect(inst.api.info()).toMatchObject({ impl: "packaged" });+ } finally {+ inst.dispose();+ }+ });++ it("every App creation re-delivers both events, and the context carries what it registered", async () => {+ const contexts: PenguinContext[] = [];+ let initializes = 0;+ const host = new ExtensionHost();+ await host.use({+ activate(extCtx) {+ extCtx.on("initialize", (iface) => {+ initializes++;+ iface.workflow.set(`probe-${initializes}`, () => ({+ run: (input) => ({ echoed: input }),+ }));+ });+ extCtx.on("create", (ctx) => contexts.push(ctx));+ },+ });+ // The registry sits outside the reloadable tree and outlives a swap: publishing the+ // host once is what lets both Apps below drive the same loaded extensions.+ const resources = bareKernel();+ resources.register(EXTENSIONS_RESOURCE_ID, host);++ const instA = await quietBoot(resources);+ try {+ expect(initializes).toBe(1);+ expect(contexts).toHaveLength(1);+ const ctx = contexts[0]!;+ // context.* flatten: the platform's own member is directly on the context.+ expect(typeof ctx.terminals.handleIds).toBe("function");+ // …and the workflow this extension registered is instantiated and callable.+ expect(ctx.workflows.names()).toContain("probe-1");+ expect(ctx.workflows.run("probe-1", 42)).toEqual({ echoed: 42 });++ // A second boot is what a hot swap performs: a new App, hooks delivered again.+ const instB = await quietBoot(resources);+ try {+ expect(initializes).toBe(2);+ expect(contexts).toHaveLength(2);+ expect(contexts[1]!.workflows.names()).toContain("probe-2");+ } finally {+ instB.dispose();+ }+ } finally {+ instA.dispose();+ }+ });+});diff --git a/packages/server/tsup.config.ts b/packages/server/tsup.config.tsindex 2a86afbc..dab1ff05 100644--- a/packages/server/tsup.config.ts+++ b/packages/server/tsup.config.ts@@ -20,6 +20,10 @@ export default defineConfig({"reset-admin-password": "src/reset-admin-password.ts","hmr/manifest": "src/hmr/manifest.ts","version-report": "src/version-report.ts",+ // "./extension": the surface extension PACKAGES compile against. Extensions live outside+ // this bundle entirely — they are configuration resolved from the installation,+ // not platform capability.+ "extension/index": "src/extension/index.ts",},format: ["esm"],target: "node24",