Skip to content

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

refactor: rearrange server as a module tree (#599)

Myriad-Dreamind446ae33afc2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 664747c8..116ece4a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -220,6 +220,15 @@ jobs:
with:
build: ${{ matrix.build }}
+ # The server's own `test` script runs `gen:ifaces` first, because src/ifaces.json is
+ # generated and not committed and src/platform.ts imports it at load. The server
+ # shards here call `exec vitest` instead — the script cannot take `--shard` — so they
+ # skip that half and every file that reaches platform.ts fails to resolve it. The
+ # other platforms run the script and never notice.
+ - name: Generate the interface table
+ if: startsWith(matrix.shard, 'server')
+ run: pnpm --filter @prismshadow/penguin-server gen:ifaces
+
# One retry, and only here. Per-test flakes are already absorbed inside vitest
# (`retry` in core's and the server's configs, Windows only); what this covers is the
# failure that has no failing test at all — a tinypool `ERR_IPC_CHANNEL_CLOSED` raised
diff --git a/.gitignore b/.gitignore
index 1a6a22fe..d135232d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -44,5 +44,6 @@ packages/landing/.blog-assets/
# generated by scripts/gen-ifaces.mjs (pnpm gen:ifaces); typecheck, build and test regenerate it
packages/server/src/ifaces.json
+plugins/*/ifaces.json
# rendered by scripts/iface-page.mjs (pnpm ifaces:page); CI publishes it
dist-ifaces/
diff --git a/changelog/unreleased/2026-08-29-module-tree.md b/changelog/unreleased/2026-08-29-module-tree.md
new file mode 100644
index 00000000..9ab7a033
--- /dev/null
+++ b/changelog/unreleased/2026-08-29-module-tree.md
@@ -0,0 +1,35 @@
+# The server is a module tree, checked by signature before it boots
+
+- **Date:** 2026-08-29
+- **Type:** refactor
+- **Scope:** `core`, `server`, `web`, `tooling`
+- **PR:** [#543](https://github.com/Prism-Shadow/penguin-harness/pull/543)
+- **Breaking:** the `@prismshadow/penguin-server` package no longer exports `AppDeps`, `buildAppDeps` or `createApp`; the `activate(ctx)` plugin contract is replaced by `Plugin { modules }`
+
+[中文版](2026-08-29-module-tree.zh.md)
+
+The business surface of the server — every service, every repo, every route group, the session runtime, the terminal manager — is now a tree (`packages/server/src/platform.ts`) of the classes themselves — there is no `modules/` directory; each node is declared in the file of the thing it is. Most nodes are **components**: a service or repo class that exports itself. `@Component()` on the class — a node is named by its class, `AuthService` is the node `AuthService`, so nothing is named twice — one `@Use()` field per dependency, typed by the class or interface it needs — `@Use() private readonly users!: UsersRepo` — and injected before the optional `setup()`; the class's public surface is its interface. A **module** is the other kind of node: a class that exports *other* things, `@Module({ contributes?, context?, children? })` with `@Provide() sessions!: Sessions` fields assigned in `setup()`. Both may carry `@Bind("agents.memory") memoryRoutes!: Hono` for a contribution's code half and `park()` for state. `AuthService` and the module that only existed to construct it are the same class now; the `modules/<name>/` wrapper directories for repos and plain services are gone, and so are their `Pick<Impl, …>` interface classes — a consumer names the component class itself, or declares the narrow interface it needs where it consumes it (`abstract class ScheduleTaskRunner extends Interface<…>() {}`, declared beside the scheduler). `pnpm gen:ifaces` reads the decorators and field annotations statically — never executing the file — into the same table as the interfaces, projecting a component's public members as its contract; the booter checks each class against that table (a field it does not know is a stale-table error), so the tree is checked before any class code runs, then created in dependency order. A component wanted outside a tree — a script, a test — is built with `wire(Cls, { …fields })`.
+
+## Interfaces at signature level
+
+A component's interface is its class, projected; anything else is an abstract class `extends Interface<…>()`, wherever it is declared. `pnpm gen:ifaces` projects every such interface into `packages/server/src/ifaces.json` — parameters and return types included, not just method names; named data types are emitted once and referenced, so a recursive type is a reference to itself. The table is generated, not committed: `typecheck`, `build`, `test` and the deploy script regenerate it. A requirement is satisfied by Go's rule: every method the consumer names exists on the provider with an assignable signature (parameters contravariant, returns covariant). A module may declare the narrow interface it needs where it consumes it; the scheduler's `ScheduleTaskRunner` is one, satisfied by the session runtime's wider `SessionManager`.
+
+Host objects (`AbortSignal`, `Request`, a class of this package written as `Opaque<"Name">`) compare by name only, and the generator says so rather than guessing.
+
+## Contributions are manifest data
+
+A route group is a line in a manifest — `"HttpModule.routes": [{ id: "agents.memory", prefix: "/api/…", auth: "user", order: 190 }]` — and the module binds the handler by that id. The `http` module assembles the whole surface from those lines; adding an endpoint no longer touches a central route table. Sandbox backends and messaging connectors enter through the same kind of slot.
+
+## Plugins are modules
+
+A plugin package is a set of modules, written the way the platform's own are: `@Component` / `@Module` classes with `@Use` / `@Provide` / `@Bind` fields. Its manifests are generated — the package's build runs `gen-ifaces` and ships `ifaces.json` beside its `package.json` — the table is the package's module payload, a plugin is a plugin by being listed; the default export is `{ modules: [<class>, …] }`, each class checked against that table at load, and the modules boot as children of the platform's tree at every App creation. The `activate(ctx)` contract — `initialize` / `create` events, `PenguinInterface`, `PenguinContext` — is gone; what it registered (a sandbox backend, a workflow factory) is now a contribution or a provided interface, and what it reached (`terminals`, `sandbox`) is a requirement checked at signature level. The four sandbox backends are converted. A hand-written manifest (a workflow package's) may leave out an empty `requires`, `provides`, `contributes` or `children`.
+
+## The table as a page
+
+`pnpm ifaces:page` renders `ifaces.json` into one self-contained HTML page (`dist-ifaces/index.html`): the module tree, every node's requires / provides / contributes, every interface at signature level, with the table's sha256 in the title and the JSON beside it.
+
+## Compatibility
+
+The platform node's parked document keeps its version: the module tree's documents are an added `modules` field, and the pty handle ids and sandbox settings are still written where the first platforms parked them — so a data root a newer platform has parked on still boots any older platform pushed to it, terminals and confinement intact.
+
+`AppDeps`, `buildAppDeps` and `createApp` are gone from `@prismshadow/penguin-server`, and so is the `activate(ctx)` plugin form: an installed plugin written against it fails to load with "the default export is not a Plugin" until it is rewritten as modules. A test that needs a service reaches it through `flattenForTests(boot)` in the server's test helpers, or through `boot.tree.api(module, alias)` — a component's alias is its class name (`tree.api("AuthService", "AuthService")`); a slot is `<Class>.<slot>` (`HttpModule.routes`, `SandboxModule.providers`). Service and repo classes no longer take their dependencies in the constructor: `new UsersRepo(db)` becomes `wire(UsersRepo, { db })` from `@prismshadow/penguin-core/kernel`.
diff --git a/changelog/unreleased/2026-08-29-module-tree.zh.md b/changelog/unreleased/2026-08-29-module-tree.zh.md
new file mode 100644
index 00000000..c3d6d5f1
--- /dev/null
+++ b/changelog/unreleased/2026-08-29-module-tree.zh.md
@@ -0,0 +1,35 @@
+# 服务端成为模块树,启动前按签名校验
+
+- **Date:** 2026-08-29
+- **Type:** refactor
+- **Scope:** `core`, `server`, `web`, `tooling`
+- **PR:** [#543](https://github.com/Prism-Shadow/penguin-harness/pull/543)
+- **Breaking:** `@prismshadow/penguin-server` 不再导出 `AppDeps`、`buildAppDeps`、`createApp`;`activate(ctx)` 形态的插件契约被 `Plugin { modules }` 取代
+
+[English](2026-08-29-module-tree.md)
+
+服务端的业务面——每个服务、每个 repo、每组路由、session 运行时、终端管理器——现在是由这些 class 本身组成的一棵树(`packages/server/src/platform.ts`)——没有 `modules/` 目录,每个节点就声明在它所是的那个东西的文件里。大多数节点是**组件**:一个把自己导出的服务或 repo class。类上 `@Component()`——节点以它的 class 命名,`AuthService` 就是节点 `AuthService`,没有东西被命名两次——每个依赖一个 `@Use()` 字段,类型就是它需要的 class 或接口——`@Use() private readonly users!: UsersRepo`——在可选的 `setup()` 之前注入;class 的公开表面就是它的接口。**模块**是另一种节点:导出*别的东西*的 class,`@Module({ contributes?, context?, children? })`,在 `setup()` 里给 `@Provide() sessions!: Sessions` 字段赋值。两者都可以带 contribution 代码半身的 `@Bind("agents.memory") memoryRoutes!: Hono` 字段和寄存状态的 `park()`。`AuthService` 与那个只为构造它而存在的模块现在是同一个 class;repo 与普通服务的 `modules/<name>/` 包装目录没有了,它们的 `Pick<Impl, …>` 接口类也没有了——消费者直接写组件 class,或者在消费处声明自己需要的窄接口(`abstract class ScheduleTaskRunner extends Interface<…>() {}`,声明在 scheduler 旁边)。`pnpm gen:ifaces` 静态读取装饰器与字段注解——从不执行文件——进与接口同一张表,组件的公开成员被投影为它的契约;启动器再把每个 class 与这张表核对(表里不认识的字段即为表过期错误),因此整棵树在任何 class 代码运行之前就被校验,之后按依赖顺序创建。树之外要用一个组件——脚本、测试——用 `wire(Cls, { …fields })` 构造。
+
+## 签名级 interface
+
+组件的接口就是它的 class 的投影;其余接口是 `extends Interface<…>()` 的抽象类,声明在哪里都可以。`pnpm gen:ifaces` 把每个这样的 interface 投影进 `packages/server/src/ifaces.json`——包含参数和返回类型,而不只是方法名;具名数据类型只输出一次、按引用使用,因此递归类型就是对自身的引用。这张表是生成物,不进版本库:`typecheck`、`build`、`test` 和部署脚本都会重新生成它。一个 requires 按 Go 的规则判定满足:消费者列出的每个方法都存在于提供者上且签名可赋值(参数逆变,返回协变)。模块可以在消费处声明自己需要的窄接口;scheduler 的 `ScheduleTaskRunner` 就是一例,由 session 运行时更宽的 `SessionManager` 满足。
+
+宿主对象(`AbortSignal`、`Request`,以及本包里写成 `Opaque<"Name">` 的 class)只按名字比较,生成器会明说而不是猜。
+
+## contribution 是 manifest 数据
+
+一组路由就是 manifest 里的一行——`"HttpModule.routes": [{ "id": "agents.memory", "prefix": "/api/…", "auth": "user", "order": 190 }]`——模块按这个 id 绑定 handler。`http` 模块从这些行装配整个 HTTP 面;新增端点不再改任何集中的路由表。sandbox 后端和消息连接器走同一种槽位。
+
+## 插件即模块
+
+一个插件包就是一组模块,写法与 platform 自己的模块相同:`@Component` / `@Module` 类,字段上是 `@Use` / `@Provide` / `@Bind`。它的 manifest 是生成的——包的 build 跑 `gen-ifaces`,把 `ifaces.json` 随 `package.json` 一起发布——这张表就是包的模块载荷,包是不是插件由它被列出决定;默认导出是 `{ modules: [<class>, …] }`,加载时每个类对照该表核对,这些模块在每次 App 创建时作为 platform 树的子节点启动。`activate(ctx)` 契约——`initialize` / `create` 事件、`PenguinInterface`、`PenguinContext`——不再存在;它过去注册的东西(沙箱后端、workflow factory)现在是 contribution 或 provides,它过去触达的东西(`terminals`、`sandbox`)现在是按签名校验的 requires。四个沙箱后端已转换。手写的 manifest(workflow 包的)里为空的 `requires`、`provides`、`contributes`、`children` 可以省略。
+
+## 表就是一个页面
+
+`pnpm ifaces:page` 把 `ifaces.json` 渲染成一个自包含的 HTML 页面(`dist-ifaces/index.html`):模块树、每个节点的 requires / provides / contributes、每个接口的签名,标题里是表的 sha256,旁边就是那份 JSON。
+
+## 兼容性
+
+platform 节点的 parked 文档版本不变:模块树的文档是新增的 `modules` 字段,pty 句柄与沙箱设置仍写在最早的 platform 寄存它们的位置——所以被更新的 platform 寄存过的数据根,仍能启动之后推过来的任何更老的 platform,终端与沙箱配置都还在。
+
+`@prismshadow/penguin-server` 不再有 `AppDeps`、`buildAppDeps`、`createApp`,也不再有 `activate(ctx)` 形态:按旧契约写的已安装插件会以 "the default export is not a Plugin" 加载失败,直到改写为模块。测试需要某个服务时,通过服务端测试 helper 的 `flattenForTests(boot)`,或 `boot.tree.api(module, alias)` 取得。——组件的别名是它的 class 名(`tree.api("AuthService", "AuthService")`);槽位是 `<Class>.<slot>`(`HttpModule.routes`、`SandboxModule.providers`)。服务与 repo class 不再从构造函数接收依赖:`new UsersRepo(db)` 变成 `@prismshadow/penguin-core/kernel` 的 `wire(UsersRepo, { db })`。
diff --git a/packages/core/src/kernel/decorators.ts b/packages/core/src/kernel/decorators.ts
new file mode 100644
index 00000000..81d817dc
--- /dev/null
+++ b/packages/core/src/kernel/decorators.ts
@@ -0,0 +1,160 @@
+/**
+ * The class form's decorators: `@Module` / `@Component` on a class, `@Use` / `@Provide` /
+ * `@Bind` on its fields. What they record is read back by `moduleDefOf` (module.ts) when
+ * the class joins a tree.
+ *
+ * They record it ON THE CLASS, under `Symbol.for` keys, not in a map private to this
+ * module. A plugin bundles its own copy of this file (it compiles against the SDK and
+ * ships self-contained), so the copy that decorated a plugin's class is never the copy
+ * the host reads it with; a property on the class is the same property from either side.
+ * Nothing here imports anything, so a bundle that wants only the decorators gets only
+ * the decorators.
+ */
+import type { JsonObject } from "./json.js";
+import type { ContextDecl } from "./manifest.js";
+
+/** An interface handle: an abstract class whose instance type is the interface (see markers.ts Interface). */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export type IfaceClass<T = any> = abstract new (...args: never[]) => T;
+/** A module class: decorated with @Module; instantiated once per App; `create` is the module's create. */
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+export type ModuleClass = abstract new (...args: any[]) => object;
+
+/**
+ * The static half a module class declares in its decorator. Requirements and provisions
+ * are FIELDS (`@Use`, `@Provide`), where their types already are; what is left here is
+ * the name, the contributions (pure data), the parked context and the child classes.
+ */
+export interface ModuleMeta {
+ readonly contributes?: Readonly<
+ Record<string, ReadonlyArray<{ readonly id: string } & JsonObject>>
+ >;
+ readonly context?: ContextDecl;
+ readonly children?: ReadonlyArray<ModuleClass>;
+}
+
+/** What a @Component declares: a module's meta minus children — a component exports itself. */
+export type ComponentMeta = Omit<ModuleMeta, "children">;
+export type Meta = ModuleMeta & { readonly name: string; readonly kind: "module" | "component" };
+
+export interface ClassFields {
+ /** field → the module class wired to provide it (undefined = any visible provider). */
+ use: Map<string, ModuleClass | undefined>;
+ provide: Set<string>;
+ /** field → contribution id. */
+ bind: Map<string, string>;
+}
+
+const META = Symbol.for("@prismshadow/penguin-core/kernel:meta");
+const FIELDS = Symbol.for("@prismshadow/penguin-core/kernel:fields");
+
+/** The meta a class was decorated with, or undefined for an undecorated class. */
+export function metaOf(cls: ModuleClass): Meta | undefined {
+ // Own property only: a subclass of a module class is not that module.
+ return Object.hasOwn(cls, META) ? (cls as unknown as Record<symbol, Meta>)[META] : undefined;
+}
+
+export function fieldsOf(cls: ModuleClass): ClassFields {
+ const holder = cls as unknown as Record<symbol, ClassFields | undefined>;
+ if (!Object.hasOwn(cls, FIELDS)) {
+ const f: ClassFields = { use: new Map(), provide: new Set(), bind: new Map() };
+ Object.defineProperty(cls, FIELDS, { value: f, enumerable: false });
+ return f;
+ }
+ return holder[FIELDS]!;
+}
+
+function setMeta(cls: ModuleClass, meta: Meta): void {
+ Object.defineProperty(cls, META, { value: meta, enumerable: false, configurable: true });
+}
+
+/**
+ * A node's name is the class's DECLARED name — the one the generator read off the source
+ * into the table — and it arrives here as the decorator context's `name`, which both
+ * lowerings emit as a string literal. `target.name` would be the same word until a
+ * minifier renamed the binding; a string literal it cannot touch. So the name the table
+ * carries and the name the class boots under cannot disagree, whatever the bundle went
+ * through.
+ */
+function nodeName(context: ClassDecoratorContext): string {
+ const name = context.name;
+ if (typeof name !== "string" || name === "") {
+ throw new Error("a @Module / @Component class must be a named class declaration");
+ }
+ return name;
+}
+
+/**
+ * Registers a class as a module. `create(ctx, context)` runs once per App; the class's
+ * `@Use` fields are injected before it, its `@Provide` fields are read after it, its
+ * `@Bind` fields are the code halves of its contributions, and `park()` (optional)
+ * parks its state.
+ */
+export function Module(meta: ModuleMeta = {}) {
+ return (target: ModuleClass, context: ClassDecoratorContext): void => {
+ setMeta(target, { ...meta, name: nodeName(context), kind: "module" });
+ };
+}
+
+/**
+ * Registers a class as a COMPONENT: a module that exports itself. The instance is the
+ * provision, named in a consumer by its own class (`@Use() auth!: AuthService`), and its
+ * interface is its public surface as the generator projects it. `@Use` fields are injected
+ * before the optional `create(ctx, context)`; `@Bind` fields and `park()` work as on a
+ * module. A class whose inputs no interface provides (a computed closure, a path) is built
+ * by a @Module instead, which is what "exports others" means.
+ */
+export function Component(meta: ComponentMeta = {}) {
+ return (target: ModuleClass, context: ClassDecoratorContext): void => {
+ setMeta(target, { ...meta, name: nodeName(context), kind: "component" });
+ };
+}
+
+/**
+ * A requirement: `@Use(SessionsModule) readonly runner!: ScheduleTaskRunner;` — the field's
+ * type is the interface, the decorator's argument the module wired to provide it (absent =
+ * whichever visible module structurally satisfies it, if exactly one does). Injected before
+ * `create`. The interface key comes from the generated table, which reads the annotation.
+ */
+export function Use(from?: ModuleClass) {
+ return (_value: undefined, context: ClassFieldDecoratorContext): void => {
+ const name = String(context.name);
+ context.addInitializer(function (this: unknown) {
+ fieldsOf((this as object).constructor as ModuleClass).use.set(name, from);
+ });
+ };
+}
+
+/** A provision: `@Provide() settings!: Settings;` — assigned in `create`, read after it; unassigned = boot error. */
+export function Provide() {
+ return (_value: undefined, context: ClassFieldDecoratorContext): void => {
+ const name = String(context.name);
+ context.addInitializer(function (this: unknown) {
+ fieldsOf((this as object).constructor as ModuleClass).provide.add(name);
+ });
+ };
+}
+
+/** The code half of one contribution: `@Bind("agents.routes") routes!: Hono;` — assigned in `create`. */
+export function Bind(id: string) {
+ return (_value: undefined, context: ClassFieldDecoratorContext): void => {
+ const name = String(context.name);
+ context.addInitializer(function (this: unknown) {
+ fieldsOf((this as object).constructor as ModuleClass).bind.set(name, id);
+ });
+ };
+}
+
+/**
+ * Constructs a component OUTSIDE a tree — a script or a test that wants the class with
+ * its fields supplied by hand. The fields are assigned as the booter would inject them;
+ * nothing is checked, and `create()` is not called.
+ */
+export function wire<T extends object>(
+ cls: new () => T,
+ // `any`, so a callback supplied here is contextually typed rather than an implicit any.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ fields: Record<string, any>,
+): T {
+ return Object.assign(new cls(), fields);
+}
diff --git a/packages/core/src/kernel/manifest.ts b/packages/core/src/kernel/manifest.ts
index 20dd400c..660ac2b3 100644
--- a/packages/core/src/kernel/manifest.ts
+++ b/packages/core/src/kernel/manifest.ts
@@ -51,18 +51,28 @@ export interface Manifest {
const ManifestType = type({
name: "string > 0",
- requires: { "[string]": { iface: "string > 0", "from?": "string > 0" } },
- provides: { "[string]": "string > 0" },
- contributes: { "[string]": type({ id: "string > 0", "[string]": "unknown" }).array() },
+ "requires?": { "[string]": { iface: "string > 0", "from?": "string > 0" } },
+ "provides?": { "[string]": "string > 0" },
+ "contributes?": { "[string]": type({ id: "string > 0", "[string]": "unknown" }).array() },
"context?": { version: "number.integer >= 1", "schema?": "unknown" },
- children: type("string").or({ keyed: "string" }).array(),
+ "children?": type("string").or({ keyed: "string" }).array(),
});
-/** Strict parse of a manifest document; throws with the arktype summary on failure. */
+/**
+ * Strict parse of a manifest document; throws with the arktype summary on failure. An empty
+ * `requires`, `provides`, `contributes` or `children` may be left out of the document — a
+ * plugin that only contributes writes its name and its contributions — and reads as empty.
+ */
export function parseManifest(doc: unknown, where = "manifest"): Manifest {
const out = ManifestType(doc);
if (out instanceof type.errors) throw new Error(`${where}: ${out.summary}`);
- return out as unknown as Manifest;
+ return {
+ ...out,
+ requires: out.requires ?? {},
+ provides: out.provides ?? {},
+ contributes: out.contributes ?? {},
+ children: out.children ?? [],
+ } as unknown as Manifest;
}
/** The iface-table key a manifest reference resolves to. */
diff --git a/packages/core/src/kernel/module.ts b/packages/core/src/kernel/module.ts
index 7d983836..bc59e629 100644
--- a/packages/core/src/kernel/module.ts
+++ b/packages/core/src/kernel/module.ts
@@ -24,6 +24,8 @@ import type { ContextDecl, Manifest, Requirement } from "./manifest.js";
import { splitSlotKey } from "./manifest.js";
import type { ManifestNode, Problem, Published } from "./check.js";
import { checkTree, describeProblem } from "./check.js";
+import type { Meta, ModuleClass } from "./decorators.js";
+import { fieldsOf, metaOf } from "./decorators.js";
/** One contribution as the consuming module receives it. */
export interface Contributed<D = JsonObject, C = unknown> {
@@ -120,146 +122,17 @@ export const defineModule = moduleDefiner<IfaceRegistry>();
// ───────────────────────── class form: @Module / @Use / @Provide / @Bind ─────────────────────────
-/** An interface handle: an abstract class whose instance type is the interface (see markers.ts Interface). */
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export type IfaceClass<T = any> = abstract new (...args: never[]) => T;
-/** A module class: decorated with @Module; instantiated once per App; `create` is the module's create. */
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-export type ModuleClass = abstract new (...args: any[]) => object;
+// The decorators themselves live in decorators.ts (no imports, so a plugin bundles just them);
+// this file reads what they recorded.
+export type { ComponentMeta, IfaceClass, ModuleClass, ModuleMeta } from "./decorators.js";
+export { Bind, Component, Module, Provide, Use, wire } from "./decorators.js";
/** What a module class's `create` receives: everything in {@link ModuleCtx} except `use` — requirements are fields. */
export type ClassCtx = Omit<ModuleCtx, "use">;
-/**
- * The static half a module class declares in its decorator. Requirements and provisions
- * are FIELDS (`@Use`, `@Provide`), where their types already are; what is left here is
- * the name, the contributions (pure data), the parked context and the child classes.
- */
-export interface ModuleMeta {
- readonly contributes?: Readonly<
- Record<string, ReadonlyArray<{ readonly id: string } & JsonObject>>
- >;
- readonly context?: ContextDecl;
- readonly children?: ReadonlyArray<ModuleClass>;
-}
-
-/** What a @Component declares: a module's meta minus children — a component exports itself. */
-export type ComponentMeta = Omit<ModuleMeta, "children">;
-type Meta = ModuleMeta & { readonly name: string; readonly kind: "module" | "component" };
-
-interface ClassFields {
- /** field → the module class wired to provide it (undefined = any visible provider). */
- use: Map<string, ModuleClass | undefined>;
- provide: Set<string>;
- /** field → contribution id. */
- bind: Map<string, string>;
-}
-
-const metas = new WeakMap<ModuleClass, Meta>();
-const fields = new WeakMap<ModuleClass, ClassFields>();
-const fieldsOf = (cls: ModuleClass): ClassFields => {
- let f = fields.get(cls);
- if (f === undefined) {
- f = { use: new Map(), provide: new Set(), bind: new Map() };
- fields.set(cls, f);
- }
- return f;
-};
-
-/**
- * Registers a class as a module. `create(ctx, context)` runs once per App; the class's
- * `@Use` fields are injected before it, its `@Provide` fields are read after it, its
- * `@Bind` fields are the code halves of its contributions, and `park()` (optional)
- * parks its state.
- */
-export function Module(meta: ModuleMeta = {}) {
- return (target: ModuleClass, context: ClassDecoratorContext): void => {
- metas.set(target, { ...meta, name: nodeName(context), kind: "module" });
- };
-}
-
-/**
- * A node's name is the class's DECLARED name — the one the generator read off the source
- * into the table — and it arrives here as the decorator context's `name`, which both
- * lowerings emit as a string literal. `target.name` would be the same word until a
- * minifier renamed the binding; a string literal it cannot touch. So the name the table
- * carries and the name the class boots under cannot disagree, whatever the bundle went
- * through.
- */
-function nodeName(context: ClassDecoratorContext): string {
- const name = context.name;
- if (typeof name !== "string" || name === "") {
- throw new ModuleBootError("a @Module / @Component class must be a named class declaration");
- }
- return name;
-}
-
-/**
- * Registers a class as a COMPONENT: a module that exports itself. The instance is the
- * provision, named in a consumer by its own class (`@Use() auth!: AuthService`), and its
- * interface is its public surface as the generator projects it. `@Use` fields are injected
- * before the optional `create(ctx, context)`; `@Bind` fields and `park()` work as on a
- * module. A class whose inputs no interface provides (a computed closure, a path) is built
- * by a @Module instead, which is what "exports others" means.
- */
-export function Component(meta: ComponentMeta = {}) {
- return (target: ModuleClass, context: ClassDecoratorContext): void => {
- metas.set(target, { ...meta, name: nodeName(context), kind: "component" });
- };
-}
-
-/**
- * A requirement: `@Use(SessionsModule) readonly runner!: ScheduleTaskRunner;` — the field's
- * type is the interface, the decorator's argument the module wired to provide it (absent =
- * whichever visible module structurally satisfies it, if exactly one does). Injected before
- * `create`. The interface key comes from the generated table, which reads the annotation.
- */
-export function Use(from?: ModuleClass) {
- return (_value: undefined, context: ClassFieldDecoratorContext): void => {
- const name = String(context.name);
- context.addInitializer(function (this: unknown) {
- fieldsOf((this as object).constructor as ModuleClass).use.set(name, from);
- });
- };
-}
-
-/** A provision: `@Provide() settings!: Settings;` — assigned in `create`, read after it; unassigned = boot error. */
-export function Provide() {
- return (_value: undefined, context: ClassFieldDecoratorContext): void => {
- const name = String(context.name);
- context.addInitializer(function (this: unknown) {
- fieldsOf((this as object).constructor as ModuleClass).provide.add(name);
- });
- };
-}
-
-/** The code half of one contribution: `@Bind("agents.routes") routes!: Hono;` — assigned in `create`. */
-export function Bind(id: string) {
- return (_value: undefined, context: ClassFieldDecoratorContext): void => {
- const name = String(context.name);
- context.addInitializer(function (this: unknown) {
- fieldsOf((this as object).constructor as ModuleClass).bind.set(name, id);
- });
- };
-}
-
-/**
- * Constructs a component OUTSIDE a tree — a script or a test that wants the class with
- * its fields supplied by hand. The fields are assigned as the booter would inject them;
- * nothing is checked, and `create()` is not called.
- */
-export function wire<T extends object>(
- cls: new () => T,
- // `any`, so a callback supplied here is contextually typed rather than an implicit any.
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- fields: Record<string, any>,
-): T {
- return Object.assign(new cls(), fields);
-}
-
/** The meta a class was decorated with; throws for an undecorated class. */
export function moduleMetaOf(cls: ModuleClass): Meta {
- const m = metas.get(cls);
+ const m = metaOf(cls);
if (m === undefined)
throw new ModuleBootError(`class '${cls.name}' is not a @Module or @Component`);
return m;
diff --git a/packages/core/src/plugin/index.ts b/packages/core/src/plugin/index.ts
index f5b6f4c8..df114978 100644
--- a/packages/core/src/plugin/index.ts
+++ b/packages/core/src/plugin/index.ts
@@ -1,101 +1,53 @@
/**
* The plugin contract: what a plugin package compiles against.
*
- * Types only — the host that drives them lives in whatever embeds this SDK (for the
- * harness, `@prismshadow/penguin-server/plugin`). A plugin 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.
- *
- * A plugin is a module exporting one function:
- *
- * export function activate(ctx: PluginContext): void
- *
- * It runs once per process at load time, before any App exists. Everything after that
- * is events ({@link PluginEvents}), 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 CLOSED. They name every member
- * a plugin may rely on, and are not reopened by declaration merging: an embedder that
- * augmented this module would put members into the contract that only its own build has,
- * so a plugin type-checking against the contract would compile against a surface that
- * the next embedder does not provide — and nothing at this layer could tell.
- *
- * An embedder with more to offer declares its own interface EXTENDING these and hands that
- * in; reaching those extra members is then an explicit cast at the point of use, which is
- * the honest cost of depending on one embedder (see the harness's `HarnessContext`).
+ * Types, plus the five decorators — the same ones the harness's own modules are written
+ * with (core kernel/decorators.ts: no imports, so a plugin's bundle carries them and
+ * nothing else of the SDK). The host that drives a plugin lives in whatever embeds this
+ * SDK (for the harness, `@prismshadow/penguin-server/plugin`); a plugin reaches THAT with
+ * `import type` only and stays a self-contained library that happens to satisfy an
+ * interface.
+ *
+ * A plugin is an npm package; what it carries is what it ships. Its MODULES — the same
+ * unit the harness itself is built from — are written the same way: a `@Component` (or
+ * `@Module`) class whose `@Use` / `@Provide` / `@Bind` fields are its requirements,
+ * provisions and contribution code halves. Their manifests are GENERATED, not written:
+ * the package's build runs `scripts/gen-ifaces.mjs` over its own tsconfig and ships the
+ * resulting `ifaces.json` beside its `package.json` — the same table the harness
+ * generates for itself, holding the manifest of every decorated class and the signature
+ * of every interface they name. That table IS the module payload: the host reads it
+ * without executing the package, and the package's default export names the classes to
+ * boot. A package without one ships no modules.
+ *
+ * // package.json
+ * "files": ["dist", "ifaces.json"],
+ * "scripts": { "build": "node ../../scripts/gen-ifaces.mjs --project tsconfig.json --out ifaces.json && tsup" }
+ * // src/index.ts
+ * @Component({ contributes: { "SandboxModule.providers": [{ id: "sandbox-bwrap.provider", name: "penguin-bwrap", dimensions: ["fs-write", "network", "mask-paths"] }] } })
+ * export class SandboxBwrap {
+ * @Bind("sandbox-bwrap.provider") provider!: SandboxProviderSource;
+ * setup() { this.provider = createProvider(); }
+ * }
+ * export default { modules: [SandboxBwrap] } satisfies Plugin;
+ *
+ * The modules boot as children of the host's tree, once per App creation — the
+ * packaged boot and each hot-swap boot alike — so what a module registers never
+ * survives into a generation it did not register with. What it may require is what the
+ * host publishes as interfaces (for the harness: everything under
+ * `@prismshadow/penguin-server/plugin`); the requirement is checked structurally,
+ * at signature level, before the module is created.
*/
+import type { ModuleClass } from "../kernel/decorators.js";
-import type { SandboxControl, SandboxProviderRegistry } from "./sandbox.js";
-import type { WorkflowFactory, WorkflowInstances } from "./workflow.js";
+export type { ClassCtx } from "../kernel/module.js";
+export type { ComponentMeta, ModuleClass, ModuleMeta } from "../kernel/decorators.js";
+export { Bind, Component, Module, Provide, Use } from "../kernel/decorators.js";
+export type { Opaque, Slot } from "../kernel/markers.js";
+export { Interface } from "../kernel/markers.js";
-export type { WorkflowFactory, WorkflowInstance, WorkflowInstances } from "./workflow.js";
export type * from "./sandbox.js";
-/** A tool factory — RESERVED. The shape lands with the first plugin-provided tool. */
-export type ToolFactory = unknown;
-
-/** An INSTANCE of the harness. Closed — see the module doc. */
-export interface PenguinContext {
- /** Instances built from `iface.workflow`. */
- workflows: WorkflowInstances;
- /** Flips confinement for this instance (see {@link SandboxControl}). */
- sandbox: SandboxControl;
-}
-
-/** 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>;
- /** Sandbox backend registration (see {@link SandboxProviderRegistry}). */
- sandbox: SandboxProviderRegistry;
-}
-
-/**
- * Event name → payload, the one place the vocabulary lives: adding an entry types the
- * platform's emit and every plugin's handler at once.
- */
-export interface PluginEvents {
- 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 PluginContext {
- /**
- * 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 PluginEvents>(event: E, handler: (payload: PluginEvents[E]) => void): void;
- /** Cleanup, disposed concurrently — entries must be mutually independent. */
- disposables: Disposable[];
-}
-
+/** What a plugin package's default export is: the module classes to boot, each in the package's `ifaces.json`. */
export interface Plugin {
- /**
- * 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 PluginContext.on}.
- */
- activate(ctx: PluginContext): void | Promise<void>;
+ modules: readonly ModuleClass[];
}
diff --git a/packages/core/src/plugin/sandbox.ts b/packages/core/src/plugin/sandbox.ts
index 348b42ed..b9227030 100644
--- a/packages/core/src/plugin/sandbox.ts
+++ b/packages/core/src/plugin/sandbox.ts
@@ -13,6 +13,8 @@
* Nothing here emits runtime code. The helpers that read these shapes
* (`SANDBOX_DIMENSIONS`, `providerDimensions`, `requestedDimensions`) are the embedder's
* and live in the server package, so a plugin carries no runtime dependency on core.
+ * A backend reaches the harness by contributing to the `sandbox.providers` slot (see
+ * the sandbox module's iface.ts in the server package).
*/
/**
@@ -113,22 +115,3 @@ export type SandboxSettings = {
network?: "none";
maskPaths?: string[];
};
-
-/**
- * Sandbox backend registration — the floor where plugins are PROVIDERS. Nothing is
- * built in: every backend is a package a deployment installs and names in plugins.json,
- * so a third-party one enters by the same door. A backend declares which dimensions it
- * implements (declaring none means filesystem only) and the service routes each policy
- * to one that covers it, so an unimplemented dimension can never be silently ignored.
- * A provider may be a promise — loading is async, and the service fails closed while it
- * is pending or failed.
- */
-export interface SandboxProviderRegistry {
- registerProvider(name: string, provider: SandboxProviderSource): void;
-}
-
-/** Flips confinement. Settings park with the platform context, so they survive swaps. */
-export interface SandboxControl {
- configure(settings: SandboxSettings): void;
- settings(): SandboxSettings;
-}
diff --git a/packages/core/src/plugin/workflow.ts b/packages/core/src/plugin/workflow.ts
deleted file mode 100644
index ac1f05b8..00000000
--- a/packages/core/src/plugin/workflow.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-/**
- * Workflows: the named units a plugin 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/test/kernel-modules.test.ts b/packages/core/test/kernel-modules.test.ts
index 6cd6c6ee..c3ea039d 100644
--- a/packages/core/test/kernel-modules.test.ts
+++ b/packages/core/test/kernel-modules.test.ts
@@ -327,6 +327,34 @@ describe("checkTree", () => {
});
});
+describe("parseManifest", () => {
+ it("reads an empty requires, provides, contributes or children left out as empty", () => {
+ expect(
+ parseManifest({
+ name: "SandboxMxc",
+ contributes: { "SandboxModule.providers": [{ id: "p" }] },
+ }),
+ ).toEqual({
+ name: "SandboxMxc",
+ requires: {},
+ provides: {},
+ contributes: { "SandboxModule.providers": [{ id: "p" }] },
+ children: [],
+ });
+ expect(parseManifest({ name: "Bare" })).toEqual({
+ name: "Bare",
+ requires: {},
+ provides: {},
+ contributes: {},
+ children: [],
+ });
+ });
+
+ it("still rejects a field of the wrong shape", () => {
+ expect(() => parseManifest({ name: "X", children: {} }, "x")).toThrow(/^x: /);
+ });
+});
+
describe("bootModules", () => {
const sessionsApi = {
startTask: async () => ({ sessionId: "s", queued: false }),
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index f7746f6f..4ad3a89f 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -21,7 +21,7 @@ The PenguinHarness server exposes a same-origin HTTP API used by the bundled Web
```text
packages/server/src
-├── index.ts / config.ts / app.ts # startup entry · env config · Hono assembly (createApp binds no port — testable)
+├── index.ts / config.ts / app.ts # startup entry · env config · Hono assembly (the runtime app; the business routes are assembled by the http module under src/modules — no port bound — testable)
├── api/types.ts # the outward DTO contract (type-only import via the "./api" subpath)
├── auth/ # scrypt passwords, admin seeding, cookie sessions, auth middleware
├── db/ # node:sqlite connection, schema SQL, one repo per table
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 0f34c702..7b86a22d 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -21,7 +21,7 @@ PenguinHarness Server 提供一套同源 HTTP API,自带的 Web App 与其他
```text
packages/server/src
-├── index.ts / config.ts / app.ts # 启动入口 · 环境变量配置 · Hono 组装(createApp 不绑端口,便于测试)
+├── index.ts / config.ts / app.ts # 启动入口 · 环境变量配置 · Hono 组装(运行时 app;业务路由由 src/modules 下的 http 模块装配,不绑端口,便于测试)
├── api/types.ts # 对外 DTO 契约(经 "./api" 子路径供前端 type-only 引用)
├── auth/ # scrypt 密码、admin 种子、cookie 会话、认证中间件
├── db/ # node:sqlite 连接、建表 SQL、每表一个 repo
diff --git a/packages/docs/content/server-boot.en.md b/packages/docs/content/server-boot.en.md
index 30a10c4c..569dca32 100644
--- a/packages/docs/content/server-boot.en.md
+++ b/packages/docs/content/server-boot.en.md
@@ -51,7 +51,7 @@ Process-level (runtime mechanism, once) App-level (the business surface, re-ru
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)
-plugins.json load + activate (⑤ pub.) "initialize" / "create" event delivery · workflow instances
+plugins.json load (⑤ pub.) plugin modules created as children of the tree
```
**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.
@@ -69,46 +69,26 @@ The full App-creation order is `platformImpl.create` in `server/src/hmr/platform
```text
platformImpl.create
│
-├─ new TerminalManager(resources) # adopt the ptys the previous instance parked
+├─ caps = claimRuntimeCapabilities(resources) # db/auth-state/channels/config/proxy/hmr/desktop
├─ plugins = pluginHostFrom(resources) # claim the host the runtime loaded in ④ (empty host if none was published)
-├─ iface = { workflow, tool, sandbox } # a fresh definition view per App
-├─ plugins.emit("initialize", iface) # the definition view, to every handler, in activation order
-├─ sandbox = new SandboxService(registered backends) # rehydrated from the parked settings
-├─ plugins.emit("create", { # the instance view, assembled after registration closes
-│ workflows: instantiateWorkflows(iface.workflow), # every factory is called eagerly here
-│ terminals,
-│ sandbox: { configure, settings },
-│ })
-├─ caps = claimRuntimeCapabilities(resources) # db/auth/channels/config/proxy/desktop
-└─ business assembly (when caps are all present): buildAppDeps — the sandbox confiner
- rides in as an argument, into the session loader's spawn path → scheduler.start()
- → 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
+├─ tree = bootModules(platformTree(caps, …, plugin modules), { ifaces, parked: context.modules })
+│ # THE TREE (server/src/platform.ts): every service and repo is a @Component
+│ # (a class that exports itself), the session runtime, the terminal manager and the
+│ # http assembly are @Modules (classes that export others). Their manifests (read off
+│ # the decorators by gen-ifaces) are checked first — requires resolved by signature,
+│ # contributions validated against their slots — then setup() runs in dependency
+│ # order. Plugin modules (a package's ifaces.json) are children of the same tree.
+└─ ctx.effect: tree.dispose() (every module's effects, reverse order) + manager.shutdown drain
```
+A plugin is a set of modules — the unit the harness itself is built from, written the same way: `@Component` / `@Module` classes with `@Use` / `@Provide` / `@Bind` fields. Its manifests are generated, not written — the package's build runs `gen-ifaces` over its own tsconfig and ships the `ifaces.json` beside its `package.json` — the table is the package's module payload, and a plugin is a plugin by being listed; the default export is `{ modules: [<class>, …] }`, each class checked against its manifest in that table at load. Split by frequency:
-Split by frequency, the plugin lifecycle has three tiers:
+| Moment | Frequency | What happens |
+| --------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| Load | Once per process | Boot step ④ `loadPlugins`: resolve and import each specifier in `plugins.json`, read the `ifaces.json` beside its `package.json` (absent = no modules), check each class the default export names against its manifest there. A package that names classes without a table (never built), or one whose class and table disagree (a stale build), is skipped with its reason; an unreadable or malformed `plugins.json` fails the boot |
+| Check + create | Once per App | The platform adds the plugin modules to its tree; the whole tree is checked as data first (requirements resolved by signature, contributions validated against their slots), then created in dependency order — so a module is created fresh per boot and per hot swap |
+| Dispose | Once per App | A module's `effect()` registrations run in reverse creation order when the App is disposed; nothing of a plugin survives into the next generation |
-| Moment | Frequency | What happens |
-| ----------------------- | ---------------- | -------------------------------------------------------------------------------------------------------------- |
-| Load + `activate(ctx)` | Once per process | Boot step ④ `loadPlugins`: resolve and import each specifier in `plugins.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 `plugins.json` fails the boot |
-| `"initialize"` event | Once per App | Handlers register workflow factories and sandbox backends 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` + `sandbox`) |
-| `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**: plugin *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 `plugins.json` ordering.
-- **The event vocabulary is typed and lives in one place**: `PluginEvents` maps each name to its payload — adding an event types the platform's emit and every handler at once.
-- **Confinement is same-generation wiring**: the confiner reaches core as a plain argument to `buildAppDeps`, and the sessions spawning through it are hard-stopped with their App — what crosses the swap is the active settings on the parked context, so a push cannot silently un-confine a deployment.
-
-The plugin contract (`Plugin` / `PluginContext` / `PluginEvents` / `PenguinInterface` / `PenguinContext`, and the sandbox vocabulary a backend is written against) is declared in the SDK, at `@prismshadow/penguin-core/plugin`. `PenguinContext` and `PenguinInterface` are closed: they name every member a plugin may rely on, and are not reopened by declaration merging. `terminals` cannot be among them — it is a harness class — so it is named on `HarnessContext`, which extends the contract and is the whole of `@prismshadow/penguin-server/plugin`; a plugin reading it writes `ctx as HarnessContext` and thereby states where it is used that it depends on this embedder. A plugin that needs no harness-only member names core alone: each sandbox backend in this repo does, and none depends on the server package. Both subpaths emit types only. Which plugins exist is the deployment's `<root>/plugins.json`; the harness itself imports no plugin.
+The plugin contract (`Plugin`, the decorators, plus the sandbox vocabulary) is declared in the SDK, at `@prismshadow/penguin-core/plugin`; `@prismshadow/penguin-server/plugin` re-exports the interfaces a plugin module may require (`Sandbox`, `Terminals`, `SessionManager`, `Agents`, …), types only. The decorators are the SDK's only runtime a plugin carries — they record on the class itself, so the copy in a plugin's bundle and the host's read the same thing. Which plugins exist is the deployment's `<root>/plugins.json`; the harness itself imports no plugin. A component's interface is its class's public surface; a module's provisions and a consumer's narrow requirements are abstract classes (`extends Interface<…>()`) declared beside the code that owns them. `pnpm gen:ifaces` projects both into `src/ifaces.json` (generated, not committed — `typecheck`, `build` and `test` regenerate it), the table the tree is checked against.
## Subsystem inventory
@@ -126,8 +106,9 @@ Each subsystem's construction site and external surface (step numbers refer to t
| 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 |
-| Plugin host | built by ④ `loadPlugins`, published to the registry in ⑤ | `activate(ctx: PluginContext)` + the `PluginEvents` registry; the configuration surface is `<root>/plugins.json` |
-| Sandbox | `sandbox/service.ts` — **App-level** (built in create, over the backends plugins registered) | `iface.sandbox.registerProvider` / `ctx.sandbox.{configure,settings}`; enforcement reaches commands through core's spawn seam, and backends are plugin packages named in `plugins.json` |
+| Plugin host | built by ④ `loadPlugins`, published to the registry in ⑤ | an npm package: its generated `ifaces.json` (the module payload), a default export `{ modules: [<class>, …] }`; the configuration surface is `<root>/plugins.json` |
+| Sandbox | `sandbox/service.ts` — **App-level** (a module; backends contribute to its `providers` slot) | a `SandboxModule.providers` contribution from a plugin module; enforcement reaches commands through core's spawn seam |
+| Module tree | `src/platform.ts` — **App-level** (booted by create over the claimed capabilities) | `@Component()` on each service / repo class (a node is named by its class) with `@Use()` fields for its dependencies; `@Module({ … })` classes with `@Provide()` fields where one class builds several things; narrow consumer interfaces as abstract classes beside their consumer (`extends Interface<…>()`); no `modules/` directory — each node lives in the file of the thing it is; `src/ifaces.json` generated; `GET /api/contributions` lists what reached the web slots |
| 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.
diff --git a/packages/docs/content/server-boot.zh.md b/packages/docs/content/server-boot.zh.md
index d6d3723c..2ee1563f 100644
--- a/packages/docs/content/server-boot.zh.md
+++ b/packages/docs/content/server-boot.zh.md
@@ -50,7 +50,7 @@ main() —— 每行一个 PenguinServer 方法
SQLite · 认证(AuthService) 全部业务服务与路由(services + http/routes)
ChannelHub(SSE 跨 swap 存活) SessionManager · Scheduler
HmrHost · 资源注册表 TerminalManager(接管寄存的 pty)
-plugins.json 加载 + activate(⑤ 发布) "initialize" / "create" 事件投递 · workflow 实例
+plugins.json 加载(⑤ 发布) 插件模块作为树的子节点创建
```
**swap 语义:未实现 park 的状态一律硬中止**——待审批全部拒绝、运行中任务中止、scheduler 随旧 App 死掉,新 App 从认领的能力重建一切。只有实现了 park/adopt 的资源(终端 pty)跨 swap 存活。
@@ -68,45 +68,25 @@ App 创建的完整顺序在 `server/src/hmr/platform.ts` 的 `platformImpl.crea
```text
platformImpl.create
│
-├─ new TerminalManager(resources) # 接管上一实例寄存的 pty
+├─ caps = claimRuntimeCapabilities(resources) # db/auth-state/channels/config/proxy/hmr/desktop
├─ plugins = pluginHostFrom(resources) # 认领运行时在 ④ 加载好的那个 host(未发布则为空 host)
-├─ iface = { workflow, tool, sandbox } # 每个 App 全新的定义视图
-├─ plugins.emit("initialize", iface) # 定义视图,按激活顺序投递给每个 handler
-├─ sandbox = new SandboxService(已注册的后端) # 由寄存的设置重新水合
-├─ plugins.emit("create", { # 实例视图,注册关闭后组装
-│ workflows: instantiateWorkflows(iface.workflow), # 全部 factory 在此被急切调用
-│ terminals,
-│ sandbox: { configure, settings },
-│ })
-├─ caps = claimRuntimeCapabilities(resources) # db/auth/channels/config/proxy/desktop
-└─ 业务面组装(caps 齐全时):buildAppDeps——sandbox confiner 作为普通参数传入,
- 进入 session loader 的 spawn 路径 → scheduler.start()
- → createApp(终端组 + 业务组注册进同一个 Hono app)
- → 一次注册表写入发布 {deps, app, shutdown} 指针 → ctx.effect 注册 swap 硬中止
+├─ tree = bootModules(platformTree(caps, …, 插件模块), { ifaces, parked: context.modules })
+│ # 模块树(server/src/platform.ts):
+│ # 每个服务和 repo 是一个 @Component(导出自己的 class),session 运行时、终端管理器和
+│ # http 装配是 @Module(导出别人的 class)。先校验它们的 manifest(gen-ifaces 从装饰器
+│ # 读出)——requires 按签名解析、contribution 按槽位校验——再按依赖顺序执行 setup()。
+│ # 插件模块(包里生成的 ifaces.json)是同一棵树的子节点。
+└─ ctx.effect:tree.dispose()(每个模块的 effect,逆序)+ manager.shutdown 排空
```
+插件是一组模块——与 harness 自身的构成单位相同,写法也相同:`@Component` / `@Module` 类,字段上是 `@Use` / `@Provide` / `@Bind`。它的 manifest 是生成的,不是手写的——包的 build 对自己的 tsconfig 跑 `gen-ifaces`,把 `ifaces.json` 随 `package.json` 一起发布——这张表就是包的模块载荷,包是不是插件由它被列出决定;默认导出是 `{ modules: [<class>, …] }`,加载时每个类对照表中自己的 manifest 核对。按频率拆开:
-按频率拆开,插件生命周期是三层:
+| 时机 | 频率 | 发生什么 |
+| ------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
+| 加载 | 每进程一次 | 启动步骤 ④ `loadPlugins`:解析 `plugins.json` 里的 specifier、import、读它 `package.json` 旁的 `ifaces.json`(没有即没有模块),把默认导出点名的每个类对照表中自己的 manifest 核对。点名了类却没有表的包(没构建过)、类与表不一致的包(构建陈旧)会带原因被跳过;`plugins.json` 不可读或格式错误则启动失败 |
+| 校验 + 创建 | 每 App 一次 | platform 把插件模块加入它的树;整棵树先作为数据校验(requires 按签名解析、contribution 按槽位校验),再按依赖顺序创建——所以模块在每次启动、每次热替换时都是全新创建的 |
+| 释放 | 每 App 一次 | 模块通过 `effect()` 登记的清理在 App 释放时按创建逆序执行;插件的任何东西都不会进入下一代 |
-| 时机 | 频率 | 发生什么 |
-| -------------- | ----------- | ---------------------------------------------------------------------------------------------------- |
-| 加载 + `activate(ctx)` | 每进程一次 | 启动步骤 ④ `loadPlugins`:解析 `plugins.json` 里的 specifier、import、执行其导出的 `activate`(async 会被等待)——`ctx.on(...)` 订阅与 `ctx.disposables` 登记只在这个窗口内有效。单条失败会回滚(跑掉它已登记的 disposable)并跳过;`plugins.json` 不可读或格式错误则启动失败 |
-| `"initialize"` 事件 | 每 App 一次 | handler 向全新的 `iface` 注册 workflow factory 与 sandbox 后端(`tool` 槽位保留未用) |
-| workflow 实例化 | 每 App 一次 | `instantiateWorkflows` 在 emit 之前同步调用**全部** factory——实例随 App 创建整批诞生,不是首次调用时 |
-| `"create"` | 每 App 一次 | 插件拿到实例视图 `ctx`(`workflows` + `terminals` + `sandbox`) |
-| `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` 会抛错的注册表,名字的归属不会随 `plugins.json` 顺序改变。
-- **事件词汇表有类型且只有一处**:`PluginEvents` 把每个事件名映射到它的载荷——加一个事件,平台的 emit 端和所有 handler 同时获得类型。
-- **约束是同代接线**:confiner 作为 `buildAppDeps` 的普通参数进入 core,经它 spawn 的 session 随所属 App 硬停——跨过 swap 的是寄存上下文上的生效设置,因此一次推送无法悄悄解除一个部署的约束。
-
-插件契约(`Plugin` / `PluginContext` / `PluginEvents` / `PenguinInterface` / `PenguinContext`,以及后端所针对编写的沙箱词汇)声明在 SDK 里,即 `@prismshadow/penguin-core/plugin`。`PenguinContext` 与 `PenguinInterface` 是封闭的:它们写明插件可以依赖的每一个成员,不再被声明合并重新打开。`terminals` 不可能位列其中——它是 harness 的类——因此它被命名在继承契约的 `HarnessContext` 上,而 `HarnessContext` 就是 `@prismshadow/penguin-server/plugin` 的全部;读取它的插件需写 `ctx as HarnessContext`,从而在使用处表明自己依赖这个宿主。不需要宿主专属成员的插件只引用 core:本仓库的每个沙箱后端都是如此,都不依赖 server 包。两个子路径都只产出类型。哪些插件存在由部署的 `<root>/plugins.json` 决定,harness 自身不 import 任何插件。
+插件契约(`Plugin`、装饰器,加上沙箱词汇表)声明在 SDK 里,即 `@prismshadow/penguin-core/plugin`;`@prismshadow/penguin-server/plugin` 再导出插件模块可以 require 的接口(`Sandbox`、`Terminals`、`SessionManager`、`Agents`……),只有类型。装饰器是插件带走的唯一一段 SDK 运行时——它们把记录写在类自身上,所以插件 bundle 里的那份和宿主读的是同一样东西。哪些插件存在由部署的 `<root>/plugins.json` 决定,harness 自身不 import 任何插件。组件的接口是它 class 的公开表面;模块的 provides 与消费者的窄 requires 是声明在归属代码旁边的抽象类(`extends Interface<…>()`)。`pnpm gen:ifaces` 把两者投影进 `src/ifaces.json`(生成物,不进版本库——`typecheck`、`build`、`test` 都会重新生成),即模块树据以校验的表。
## 子系统一览
@@ -124,8 +104,9 @@ platformImpl.create
| 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 寄存跨热更新存活 |
-| 插件宿主 | ④ `loadPlugins` 构建,⑤ 发布进资源注册表 | `activate(ctx: PluginContext)` + `PluginEvents` 事件表;配置面是 `<root>/plugins.json` |
-| 沙盒 | `sandbox/service.ts`——**App 级**(create 内基于插件注册的后端构建) | `iface.sandbox.registerProvider` / `ctx.sandbox.{configure,settings}`;约束经 core 的 spawn seam 落到命令上,后端是 `plugins.json` 里点名的插件包 |
+| 插件宿主 | ④ `loadPlugins` 构建,⑤ 发布进资源注册表 | 一个 npm 包:生成的 `ifaces.json`(模块载荷)、默认导出 `{ modules: [<class>, …] }`;配置面是 `<root>/plugins.json` |
+| 模块树 | `src/platform.ts`——**App 级**(create 在认领的能力之上启动) | 每个服务 / repo class 上 `@Component()`(节点以 class 命名),依赖是 `@Use()` 字段;一个 class 造出多个东西时用带 `@Provide()` 字段的 `@Module({ … })`;消费者的窄接口是紧挨消费者声明的抽象类(`extends Interface<…>()`);没有 `modules/` 目录——每个节点就住在它所是的那个东西的文件里;生成的 `src/ifaces.json`;`GET /api/contributions` 列出到达 web 槽位的内容 |
+| 沙盒 | `sandbox/service.ts`——**App 级**(一个模块;后端向它的 `providers` 槽位投递) | 插件模块向 `SandboxModule.providers` 投递的一条 contribution;约束经 core 的 spawn seam 落到命令上 |
| 模型目录 | 无启动期构建——core 静态数据 | `/api/projects/:projectId/models`;目录本体在 `core/src/state/model-catalog.ts` |
请求期还有一条固定路径值得知道:平台的 HTTP seam 把每个请求先交给当前 App 的 `http(request)`,返回 `null` 才落到运行时自己的路由;热更新进行中时请求在 seam 上排队等新 App 就绪,而不是打到半旧的实例上。
diff --git a/packages/server/README.md b/packages/server/README.md
index 434640ba..93fef628 100644
--- a/packages/server/README.md
+++ b/packages/server/README.md
@@ -4,7 +4,7 @@ The PenguinHarness Web backend — the Web implementation of the SDK's Human bou
## Architecture
-- **HTTP**: Hono + `@hono/node-server`; `createApp(deps)` is pure assembly (no port bind — tests drive it via `app.request()`); `index.ts` is the startup entry (dotenv, graceful shutdown).
+- **HTTP**: Hono + `@hono/node-server`; the `http` module (src/http/app.ts) assembles the business surface from every module's `HttpModule.routes` contributions and binds no port (tests drive it via `app.request()`); `index.ts` is the startup entry (dotenv, graceful shutdown).
- **Storage**: SQLite via Node's built-in `node:sqlite` (WAL) holds only indexes and aggregates (users, auth sessions, Project authorization, Agent/Session indexes, usage, UI prefs, error records). Agent State, Traces and Workspaces stay as files under `~/.penguin/data/<project>/agents/<agent>/`, fully shared with the SDK and CLI.
- **Runtime**: a session manager keeps active Sessions (get-or-resume-or-heal, per-Session mutex, run/compact driving); approvals surface over SSE as `approval_request` and decisions re-read the stored approval mode each time; interrupts converge pending approvals to deny before aborting; a scheduler fires `agent_state/schedule/*.toml` tasks while the service runs.
- **SSE**: per-channel monotonic event ids with a bounded replay buffer (1000 events / 2MB); reconnects replay from `Last-Event-ID` or receive `resync_required`; heartbeat comment every 20s.
diff --git a/packages/server/package.json b/packages/server/package.json
index 30a9d945..960277fb 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -63,9 +63,10 @@
"scripts": {
"dev": "node ../../scripts/dev-prebuild.mjs && node ../../scripts/run-with-env.mjs PENGUIN_HOME=~/.penguin/dev-data PORT=7368 -- tsx watch src/index.ts",
"start": "node --disable-warning=ExperimentalWarning dist/index.js",
- "typecheck": "tsc --noEmit -p tsconfig.json",
- "test": "vitest run --passWithNoTests",
- "build": "tsup"
+ "typecheck": "pnpm gen:ifaces && tsc --noEmit -p tsconfig.json",
+ "gen:ifaces": "node ../../scripts/gen-ifaces.mjs --project tsconfig.json --out src/ifaces.json",
+ "test": "pnpm gen:ifaces && vitest run --passWithNoTests",
+ "build": "pnpm gen:ifaces && tsup"
},
"dependencies": {
"@hono/node-server": "^2.0.5",
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 8929a05e..eb188b8d 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -3856,3 +3856,23 @@ export interface MachinesResponse {
imageVersion: string | null;
job: MachineJob | null;
}
+
+// ---------------------------------------------------------------------------
+// Web contributions (GET /api/contributions)
+// ---------------------------------------------------------------------------
+
+/** How the web app renders a contributed surface: a name from its own registry, or an iframe. */
+export type RendererRef = { builtin: string } | { iframe: { src: string; namespace: string } };
+
+/** One contribution to a web slot: its id, the contributing module, and the slot's data. */
+export interface WebContribution {
+ id: string;
+ from: string;
+ [key: string]: unknown;
+}
+
+export interface ContributionsResponse {
+ pages: WebContribution[];
+ agentTabs: WebContribution[];
+ sessionTabs: WebContribution[];
+}
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index e4382e4d..353116b1 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -26,6 +26,8 @@ import type { Context, MiddlewareHandler } from "hono";
import { bodyLimit } from "hono/body-limit";
import { bodyLimitBytes, toAttachmentLimits } from "./services/attachment-limits.js";
import type { DatabaseSync } from "node:sqlite";
+import type { ModuleTree } from "@prismshadow/penguin-core/kernel";
+import type { ProjectAccess } from "./services/project-access.js";
import type { ServerConfig } from "./config.js";
import { applyProxySettings, mergedNoProxy } from "./net/proxy.js";
import {
@@ -43,7 +45,7 @@ import {
RuntimeCapabilities,
} from "./hmr/capabilities.js";
import type { ProxyControl } from "./hmr/capabilities.js";
-import { cliShimDir, ensureCliShim } from "./services/cli-shim.js";
+import { ensureCliShim } from "./services/cli-shim.js";
import { openDatabase } from "./db/database.js";
import { MachinesRepo } from "./db/repos/machines.js";
import { migrate } from "./db/migrations.js";
@@ -166,78 +168,22 @@ import { machinesRoutes } from "./http/routes/machines.js";
import { UsageRecorder } from "./runtime/usage-recorder.js";
import { previewRoutes } from "./http/routes/preview.js";
import { MachinesService } from "./machines/service.js";
-import { SERVER_PROXY_PREFIX, machinesProxy } from "./machines/proxy.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
-export interface AppDeps {
+/**
+ * What the runtime process holds after boot: the capabilities it owns for the process
+ * lifetime, and the module tree the platform built over them (src/modules). There is no
+ * flat bag of services here any more — a module names what it needs in its manifest.
+ */
+export interface ServerBoot {
config: ServerConfig;
db: DatabaseSync;
- sessionsRepo: SessionsRepo;
- /** The `users` table itself, for the one route that writes a column no service owns (PUT /api/me/profile). */
- usersRepo: UsersRepo;
- prefsRepo: UiPrefsRepo;
- /** Admin-level server-global settings (currently the proxy switches and address). */
- serverSettingsRepo: ServerSettingsRepo;
- authService: AuthService;
- adminService: AdminService;
- projectService: ProjectService;
- projectConfigService: ProjectConfigService;
- /** In-flight provider key-minting flows (PKCE verifiers live here and nowhere else). */
- modelOAuth: ModelOAuthService;
- agentService: AgentService;
- agentConfigService: AgentConfigService;
- memoryService: MemoryService;
- sessionService: SessionService;
- traceService: TraceService;
- /** Trace-file index (derived cache + reconciler); routes use it for delete-time coherence. */
- traceIndex: TraceIndexService;
- usageService: UsageService;
- /** GitHub latest-release lookup for the web UI's update reminder (cached, fail-soft). */
- updateCheck: UpdateCheckService;
- /** The admin self-update run in the background (`penguin update --yes`), with its progress for the update modal. */
- updateJob: UpdateJobService;
- workspaceFiles: WorkspaceFilesService;
- /** Signs/verifies short-lived Workspace preview tokens (separate preview origin). */
- previewTokens: PreviewTokenSigner;
- benchmarks: BenchmarkService;
- snapshots: SnapshotService;
- schedulesRepo: SchedulesRepo;
- errorsRepo: ErrorsRepo;
- /** Session ↔ messaging-channel bot bindings (stored; runtime connections live on `messaging`). */
- messagingRepo: MessagingBindingsRepo;
- /** Messaging bridge — channel connectors + event connections (started by the platform next to the scheduler). */
- messaging: MessagingBridge;
- /** QQ scan-to-connect: the in-flight bind tasks and the AES keys that never leave the server. */
- qqScan: QQScanService;
- /** WeChat scan-to-connect: the in-flight codes and the poll handles that never leave the server. */
- wechatScan: WeChatScanService;
- scheduler: Scheduler;
channels: ChannelHub;
- manager: SessionManager;
- /** Session-origin registry derived from session_meta (single source of truth; no DB column). */
- sessionSources: SessionSources;
- /** Error persistence (shared by app.onError and various background capture points; the process-level fallback is in index.ts). */
- errors: ErrorRecorder;
- /** Desktop mode (PENGUIN_DESKTOP_TOKEN): one-shot login + shutdown token holder; null outside desktop mode. */
+ hmr: HmrHost;
desktop: DesktopService | null;
/** Process lifecycle: whether a supervisor relaunches this process, and the restart trigger (the "restart to update" step). */
lifecycle: LifecycleService;
- /**
- * Installing this build on a machine from the server's own `~/.ssh/config` (the Machines
- * page). Business, not runtime: spawning ssh and packing an image are in-process effects,
- * so the whole capability ships by push — see machines/service.ts.
- */
- machines: MachinesService;
- /** 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;
+ tree: ModuleTree;
}
export interface BuildDepsOverrides {
@@ -296,10 +242,10 @@ export async function bootAppDeps(
config: ServerConfig,
overrides: BuildDepsOverrides = {},
plugins?: PluginHost,
-): Promise<AppDeps> {
+): Promise<ServerBoot> {
const db = openDatabase(config.dbPath);
- const usersRepo = new UsersRepo(db);
+ const usersRepo = wire(UsersRepo, { db: db });
// Hoisted above the services so its registry can be populated before anything boots
// against it.
@@ -362,7 +308,8 @@ 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);
- hmr.resources.register(RUNTIME_LIFECYCLE_RESOURCE_ID, new LifecycleService(config.supervised));
+ const lifecycle = new LifecycleService(config.supervised);
+ hmr.resources.register(RUNTIME_LIFECYCLE_RESOURCE_ID, lifecycle);
// The registry sweep only STARTS plugin 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.
@@ -374,21 +321,31 @@ export async function bootAppDeps(
// services, routes, the scheduler — is assembled inside its create(). The check reads
// the in-process api member, not a registry entry: the instance IS the current App.
const instance = await hmr.ensure();
- const business = instance.api.business();
- if (business === null) {
+ const tree = instance.api.business();
+ if (tree === null) {
throw new Error("the packaged platform built no business surface");
}
- // The App's own deps, read off the booted instance — the same bag every caller of this
- // function always received. Callers that outlive swaps (index.ts, the runtime app) may
- // only touch its swap-stable members: the runtime singletons published above, and the
- // stateless repos over this process's own db handle. The business machinery on it
- // (manager, services, scheduler) belongs to THIS generation and goes stale at the next
- // push — per-request business dispatch rides the seam, never this reference.
- return business;
+ // Callers that outlive swaps (index.ts, the runtime app) may only touch the swap-stable
+ // members: the runtime singletons published above. The tree is THIS generation's and
+ // goes stale at the next push — per-request business dispatch rides the seam.
+ return { config, db, channels, hmr, desktop, lifecycle, tree };
}
/** Assembles the Hono app (does not listen on a port). */
-export function createRuntimeApp(deps: AppDeps): Hono<AppEnv> {
+export function createRuntimeApp(boot: ServerBoot): Hono<AppEnv> {
+ const { tree } = boot;
+ const errors = tree.api<ErrorRecorder>("ErrorRecorder", "ErrorRecorder");
+ const log = tree.api<{ line(text: string): void }>("RuntimeModule", "log");
+ const settings = tree.api<ServerSettingsRepo>("ServerSettingsRepo", "ServerSettingsRepo");
+ const access = tree.api<ProjectAccess>("ProjectAccess", "ProjectAccess");
+ const authService = tree.api<AuthService>("AuthService", "AuthService");
+ const deps = {
+ config: boot.config,
+ desktop: boot.desktop,
+ authService,
+ hmr: boot.hmr,
+ channels: boot.channels,
+ };
const app = new Hono<AppEnv>();
// Error recording is layered in a lambda wrapping onError: handleError stays a
@@ -396,8 +353,8 @@ export function createRuntimeApp(deps: AppDeps): Hono<AppEnv> {
// 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({
+ const projectId = attributedProjectId(c, { access });
+ errors.record({
source: "http",
err,
...(projectId !== undefined ? { ctx: { projectId } } : {}),
@@ -411,7 +368,7 @@ export function createRuntimeApp(deps: AppDeps): Hono<AppEnv> {
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`);
+ log.line(`${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
@@ -457,7 +414,7 @@ export function createRuntimeApp(deps: AppDeps): Hono<AppEnv> {
// 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());
+ const size = bodyLimitBytes(settings.getAttachmentLimitsMb());
if (capped === null || capped.size !== size) {
capped = {
size,
@@ -791,520 +748,3 @@ function registerStaticRoutes(app: Hono<AppEnv>, resolveSource: () => Promise<We
* 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 = {},
- // Spawn confinement (mechanism only here): platform.ts's create() hands in a getter
- // over its own SandboxService, and it is threaded untouched through BOTH core entry
- // paths — the loader (resume/self-heal) and SessionService (creation) — then re-read
- // at every command spawn, like proxyEnv. Same-generation wiring on purpose: the
- // sessions spawning through it are hard-stopped with their App, so no channel with a
- // longer lifetime is needed. Policy itself lives in ../sandbox/.
- confineSpawn: () => SpawnConfiner | null = () => null,
-): AppDeps {
- const { config, db, authState, channels, hmr } = caps;
- const log = overrides.log ?? ((line: string) => console.log(line));
-
- // A pushed platform carries its own migrations, which is the only way the tables its
- // business needs can reach a runtime older than they are — that runtime will never grow
- // them by restarting, because it does not have them. swapPath: this boot can be rolled
- // back, so a restart-only migration is refused here instead of being left behind.
- migrate(db, { swapPath: true });
-
- /**
- * This machine's own id is minted on the first boot of this data root and stable ever
- * after — every stored reference to this machine, here and on the machines it reaches,
- * points at it. Behind a function so a test that passes its own service never mints one.
- */
- const buildMachines = (): MachinesService => {
- const repo = new MachinesRepo(db);
- return new MachinesService(config.root, repo.ownId(), repo, {}, () => hmr.assetsDir());
- };
-
- const usersRepo = new UsersRepo(db);
- const projectsRepo = new ProjectsRepo(db);
- const membersRepo = new MembersRepo(db);
- // Auth is built HERE, with the App, so every rule it carries ships by push. The runtime
- // publishes only `authState` — the values a push must not forget (auth/runtime-state.ts).
- // `provisionInitialProject` closes over the projectService created below: seeding runs long
- // after this returns, so the cycle costs a closure rather than an install-it-later hook.
- const authService = new AuthService({
- users: usersRepo,
- authSessions: new AuthSessionsRepo(db),
- state: authState,
- provisionInitialProject: (user, isAdmin) =>
- projectService.provisionInitialProject(user, isAdmin),
- seedAdminPassword: config.seedAdminPassword,
- sessionTtlMs: config.authSessionTtlMs,
- sessionRenewMs: config.authSessionRenewMs,
- ...(overrides.passwordHashCost !== undefined
- ? { passwordHashCost: overrides.passwordHashCost }
- : {}),
- ...(overrides.now ? { now: overrides.now } : {}),
- });
- const agentsRepo = new AgentsRepo(db);
- const sessionsRepo = new SessionsRepo(db);
- const usageRepo = new UsageRepo(db);
- const errorsRepo = new ErrorsRepo(db);
- const prefsRepo = new UiPrefsRepo(db);
- const serverSettingsRepo = new ServerSettingsRepo(db);
- // Command-subprocess proxy policy for core, keyed on the
- // "agent environment uses the proxy" switch (the app switch only drives the server's
- // own dispatcher, see net/proxy.ts): switch off → strip HTTP(S)_PROXY/ALL_PROXY; on
- // with an explicit address → inject that address (with the merged loopback NO_PROXY)
- // over whatever the environment carries; on without an address → pass the environment
- // through. A getter, not a snapshot: it is re-read at every command spawn, so a
- // settings change reaches already-loaded Sessions. Threaded through BOTH core entry
- // paths — the loader (resume/self-heal) and SessionService (creation, whose runtime
- // the manager adopts for the first Task).
- const proxyEnv = (): ProxyEnvPolicy | null => {
- if (!serverSettingsRepo.getProxyForAgent()) return { mode: "strip" };
- const url = serverSettingsRepo.getProxyUrl();
- return url === null ? null : { mode: "inject", url, noProxy: mergedNoProxy() };
- };
- // Harness-control env for command subprocesses of server-driven Sessions: the server's
- // own canonical URL, its boot API token, and the Session's coordinates — what lets
- // commands the Agent runs drive this harness back through the CLI/API. Threaded like
- // proxyEnv through BOTH core entry paths (loader + SessionService), and evaluated per
- // spawn: config.port is written back by index.ts once the real port is bound (PORT=0),
- // so the URL must not be captured at assembly time. On a loopback bind the URL uses the
- // canonical App host (`localhost`) — the counterpart name serves only /preview/*; a
- // wildcard bind falls back to 127.0.0.1.
- const canonicalApiUrl = (): string => {
- const host =
- config.host === "0.0.0.0" || config.host === "::"
- ? "127.0.0.1"
- : (loopbackHostRoles(config.host)?.app ?? config.host);
- return `http://${host}:${config.port}`;
- };
- // The directory core puts at the FRONT of PATH for every command an Agent runs (and for
- // its hook scripts): the shim directory bootAppDeps wrote this harness's own `penguin`
- // into. Derived from the config rather than passed along, so the platform half needs no
- // new capability — and read for truth rather than for null, because a runtime older than
- // this field publishes a config without it and wrote no shim either: no field, no
- // directory, feature off, rather than a push declined over a PATH entry.
- const shimDir = config.cliEntry ? cliShimDir(config.root) : null;
- const pathPrepend = (): string[] => (shimDir === null ? [] : [shimDir]);
- const controlEnv = (ctx: ControlEnvContext): Record<string, string> => {
- const token = authService.localApiToken();
- return {
- PENGUIN_API_URL: canonicalApiUrl(),
- ...(token !== null ? { PENGUIN_API_TOKEN: token } : {}),
- PENGUIN_PROJECT_ID: ctx.projectId,
- PENGUIN_AGENT_ID: ctx.agentId,
- PENGUIN_SESSION_ID: ctx.sessionId,
- };
- };
- const schedulesRepo = new SchedulesRepo(db);
-
- const projectConfigService = new ProjectConfigService(config.root);
- // Per-App like the preview signer above: a flow holds a PKCE verifier and nothing durable,
- // so a push or a restart costs the user one re-authorization and leaks nothing.
- const modelOAuth = new ModelOAuthService({
- applyGroupKey: (projectId, provider, apiKey) =>
- projectConfigService.setGroupApiKey(projectId, provider, apiKey),
- });
- const agentConfigService = new AgentConfigService(config.root);
- const snapshots = new SnapshotService(config.root);
- const agentService = new AgentService(config.root, agentsRepo, agentConfigService, snapshots);
- const memoryService = new MemoryService(config.root, agentConfigService);
- // Session-origin registry: session_meta is the single source of truth (no DB column);
- // shared by the manager (subagent registration), the loader (self-heal rebuild),
- // SessionService (creation / adoption / lazy list resolution), and the Trace index /
- // listing classification.
- const sessionSources = new SessionSources();
- // Trace-file index: the derived cache every trace listing/locating path serves from
- // (mtime-gated reconciler keeps it in step with the on-disk tree; see trace-index.ts).
- const traceIndexRepo = new TraceIndexRepo(db);
- const traceIndex = new TraceIndexService(config.root, traceIndexRepo, sessionSources);
- const traceService = new TraceService(config.root, {
- index: traceIndex,
- sessions: sessionsRepo,
- sources: sessionSources,
- // The one price table: the analysis costs a file's Requests with the lookup the cost
- // center prices usage rows with, so the Trace panel and the toolbar never disagree.
- lookupPricing: (projectId, provider, modelId) =>
- projectConfigService.getPricing(projectId, provider, modelId),
- });
- 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. (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 usageService = new UsageService(
- usageRepo,
- errorsRepo,
- // No clock here: a scheduled row's two rates come back together and each aggregation half
- // is priced at the tier its own records ran in, which the query decides from their `ts`.
- (projectId, provider, modelId) => projectConfigService.getPricing(projectId, provider, modelId),
- overrides.now ?? (() => new Date()),
- );
- const updateCheck =
- overrides.updateCheck ?? new UpdateCheckService(overrides.now ? { now: overrides.now } : {});
- const updateJob = overrides.updateJob ?? new UpdateJobService();
-
- 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
- // list-row facts that must reach tabs not subscribed to the Session's own channel.
- //
- // Audience = the Project's owner plus its members, i.e. exactly who
- // ProjectsRepo.listAccessible would grant the Project to — nobody learns that a Session they
- // cannot open changed state or gained a title.
- //
- // `peek`, deliberately not `get`: a user who has never opened an event stream has no
- // channel, and conjuring one to buffer badge updates nobody is listening to is pure waste
- // (their next connection fetches the list, which carries the same statuses anyway).
- const notifyProjectUsers = (projectId: string, event: ServerEvent): void => {
- const ownerUserId = projectsRepo.findById(projectId)?.ownerUserId;
- if (ownerUserId === undefined) return;
- const audience = new Set([ownerUserId, ...membersRepo.list(projectId).map((m) => m.userId)]);
- for (const userId of audience) {
- channels.peek(userChannelKey(userId))?.publish(event, "server_event");
- }
- };
- const titles =
- overrides.titles ??
- new TitleGenerator({
- sessions: sessionsRepo,
- channels,
- recorder,
- errors,
- log,
- notifyProjectUsers,
- });
- const manager = new SessionManager({
- sessions: sessionsRepo,
- channels,
- loader:
- overrides.loader ??
- createCoreSessionLoader(config.root, sessionSources, {
- proxyEnv,
- controlEnv,
- pathPrepend,
- confineSpawn,
- }),
- sources: sessionSources,
- recorder,
- errors,
- titles,
- log,
- // Run-state flips reach the whole login session, not just the tab watching that one
- // conversation (see the shared publisher above for the audience).
- notifyProjectUsers,
- ...(overrides.now ? { now: overrides.now } : {}),
- });
-
- const projectService = new ProjectService({
- root: config.root,
- users: usersRepo,
- projects: projectsRepo,
- members: membersRepo,
- agents: agentsRepo,
- sessions: sessionsRepo,
- usage: usageRepo,
- errors: errorsRepo,
- schedules: schedulesRepo,
- projectConfig: projectConfigService,
- manager,
- traceIndex,
- });
- const adminService = new AdminService({
- users: usersRepo,
- authSessions: new AuthSessionsRepo(db),
- projects: projectsRepo,
- projectService,
- ...(overrides.passwordHashCost !== undefined
- ? { passwordHashCost: overrides.passwordHashCost }
- : {}),
- ...(overrides.now ? { now: overrides.now } : {}),
- });
- const messagingRepo = new MessagingBindingsRepo(db);
- // Messaging bridge: assembled here, started by platform.ts's create() (tests drive it
- // via sync()/fake transports, no real network), stopped by the same create()'s dispose
- // effect. One connector per channel; further channels register here.
- const messaging = new MessagingBridge({
- repo: messagingRepo,
- sessions: sessionsRepo,
- // The same service the Files panel reads through: mirroring a file the reply mentions
- // must obey exactly the containment rules browsing it does, not a second copy of them.
- files: workspaceFiles,
- root: config.root,
- // Read through per message, not snapshotted: these are admin-settable, and every other
- // caller resolves them per request so a change applies without a restart.
- attachmentLimits: () => toAttachmentLimits(serverSettingsRepo.getAttachmentLimitsMb()),
- channels,
- runner: manager,
- connectors: [
- new FeishuConnector(overrides.feishuSdk ?? createLarkSdk()),
- new TelegramConnector(
- overrides.telegramTransport ?? createTelegramTransport(),
- overrides.telegramRetryDelayMs ? { retryDelayMs: overrides.telegramRetryDelayMs } : {},
- ),
- new QQConnector(overrides.qqTransport ?? createQQTransport(), {
- ...(overrides.qqTailFlushMs !== undefined ? { tailFlushMs: overrides.qqTailFlushMs } : {}),
- ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),
- }),
- new WeChatConnector(
- overrides.wechatTransport ?? createWeChatTransport(),
- overrides.wechatRetryDelayMs ? { retryDelayMs: overrides.wechatRetryDelayMs } : {},
- ),
- ],
- errors,
- log,
- ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),
- ...(overrides.messagingLineDelayMs !== undefined
- ? { lineDelayMs: overrides.messagingLineDelayMs }
- : {}),
- ...(overrides.messagingInboundImageBudgetBytes !== undefined
- ? { inboundImageBudgetBytes: overrides.messagingInboundImageBudgetBytes }
- : {}),
- });
- // Scan-to-connect holds one AES key per in-flight bind task, in memory only: it decrypts
- // an App Secret, and a task lives for the couple of minutes a person spends scanning.
- const qqScan = new QQScanService(overrides.qqScanTransport ?? createQQScanTransport(), {
- ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),
- });
- // Same reasoning as above: what this one holds is the handle that collects a bot token
- // rather than a key that decrypts a secret, and it is equally not worth persisting.
- const wechatScan = new WeChatScanService(
- overrides.wechatScanTransport ?? createWeChatScanTransport(),
- { ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}) },
- );
- const sessionService = new SessionService({
- root: config.root,
- sessions: sessionsRepo,
- manager,
- projectConfig: projectConfigService,
- sources: sessionSources,
- traceIndex,
- proxyEnv,
- controlEnv,
- pathPrepend,
- // List rows carry the ENABLED channel's indicator (saved-but-dark configs stay off
- // the row); a point query per row keeps the repo out of the service. An unknown
- // stored channel reads as none (same defensive skip as the bridge and the routes).
- messagingChannel: (sessionId) => {
- const enabled = messagingRepo.findEnabled(sessionId);
- return enabled !== null &&
- (enabled.channel === "feishu" ||
- enabled.channel === "telegram" ||
- enabled.channel === "qq" ||
- enabled.channel === "wechat")
- ? enabled.channel
- : null;
- },
- confineSpawn,
- });
- // 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,
- projects: projectsRepo,
- sessions: sessionsRepo,
- runner: manager,
- sessionCreator: sessionService,
- projectConfig: projectConfigService,
- errors,
- notify: (userId, event) => {
- channels.get(userChannelKey(userId)).publish(event, "server_event");
- },
- ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),
- });
-
- return {
- config,
- db,
- sessionsRepo,
- usersRepo,
- prefsRepo,
- serverSettingsRepo,
- authService,
- adminService,
- projectService,
- projectConfigService,
- modelOAuth,
- agentService,
- agentConfigService,
- memoryService,
- sessionService,
- traceService,
- traceIndex,
- usageService,
- updateCheck,
- updateJob,
- workspaceFiles,
- previewTokens,
- benchmarks,
- snapshots,
- schedulesRepo,
- errorsRepo,
- messagingRepo,
- qqScan,
- wechatScan,
- messaging,
- scheduler,
- channels,
- manager,
- sessionSources,
- errors,
- desktop: caps.desktop,
- lifecycle: caps.lifecycle,
- // Anchored at the data root: that is where the hmr store the pushable image comes from
- // lives, and where verified Node runtime downloads are cached between installs.
- machines: overrides.machines ?? buildMachines(),
- hmr,
- proxyControl: caps.proxyControl,
- log,
- };
-}
-
-/** 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 host published no business capabilities — a declared bare kernel:
- * the terminal group still serves, everything else declines. A runtime merely too OLD to
- * publish them never reaches here; the platform refuses to boot on one (hmr/platform.ts's
- * create), because that runtime still answers the business API out of its own routes.
- */
-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 — skipped when no business (and so
- // no errors table access) is running.
- app.onError((err, c) => {
- if (deps !== null) {
- const projectId = attributedProjectId(c, deps);
- deps.errors.record({
- source: "http",
- err,
- ...(projectId !== undefined ? { ctx: { projectId } } : {}),
- });
- }
- return handleError(err, c);
- });
- app.notFound(() => declined());
-
- // 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));
-
- if (deps === null) return app;
-
- // 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();
- }
- await next();
- });
-
- // The provider key-minting redirect receiver, and the only business route mounted outside
- // the auth gate below — the same shape /api/desktop/update uses in reverse, and for the
- // mirror-image reason. A loopback OAuth callback is reached by whichever browser the
- // provider redirected: on the desktop the shell hands the authorization page to the system
- // browser, which holds no session cookie for this origin, so requiring one 401'd every
- // desktop authorization. It authorizes on the flow id instead, and all it may do with one
- // is deposit the code it carried: the exchange that writes a key runs on the owner's poll
- // of the status route, behind this gate (see the route module).
- //
- // Exactly this literal path, registered here so the exemption cannot widen: the group
- // mount below still carries /start, /:flowId/code and the status route behind the gate,
- // and because this registration comes first, `:flowId` can never swallow "callback". Only
- // GET is served, and the handler refuses the HEAD that Hono re-dispatches into it.
- app.route("/api/projects/:projectId/model-oauth/callback", modelOAuthCallbackRoutes(deps));
-
- // The data root's install identity, public: the web app compares it against what it holds
- // in `localStorage` before React mounts, which is before it knows whether anyone is signed
- // in — and a just-wiped root, the case the whole mechanism exists for, has nobody signed in
- // at all. See http/routes/install.ts.
- //
- // Mounted in the PLATFORM rather than the runtime because a hot push carries platform + cli
- // + web dist as ONE version and never the runtime (hmr/host.ts): the bundle that calls this
- // route and the route itself then always move together, whereas a runtime mount would let a
- // pushed web dist arrive on an installation whose runtime does not serve what it asks for.
- // For that reason /api/install is deliberately absent from RUNTIME_PREFIXES above — the
- // platform must serve it, not decline it.
- app.route("/api/install", installRoutes(deps));
- // `/server/<machineId>/api/…` — a connected machine's API, forwarded over the forward held
- // to it and addressed by the machine's OWN id. Admins only: the request is made over there
- // as that machine's admin, with a session this server minted over the ssh access that
- // installed it, so this server's admin session is the one credential involved.
- const serverProxy = machinesProxy(
- (machineId) => deps.machines.proxyTarget(machineId),
- (machineId, outcome) => deps.machines.noteApiSeen(machineId, outcome),
- );
- app.all(
- `${SERVER_PROXY_PREFIX}*`,
- authMiddleware(deps.authService, deps.config.trustProxy),
- async (c) => {
- if (!c.var.user.isAdmin) {
- throw new HttpError(403, "admin_required", "Only an admin can reach a machine's API.");
- }
- const answer = await serverProxy(c.req.raw);
- return answer ?? c.notFound();
- },
- );
-
- // Protected routes: cookie -> auth_session -> user, over the runtime's auth service.
- app.use("/api/*", authMiddleware(deps.authService, deps.config.trustProxy));
- app.route("/api/me", meRoutes(deps));
- app.route("/api/version", versionRoutes(deps));
- app.route("/api/admin/users", adminUsersRoutes(deps));
- app.route("/api/admin/settings", adminSettingsRoutes(deps));
- app.route("/api/events", eventsRoutes(deps));
- // Plugin library listing: readable once logged in, not nested under a Project prefix.
- app.route("/api/plugins", pluginLibraryRoutes());
- app.route("/api/projects/:projectId/machines", machinesRoutes(deps));
- app.route("/api/projects", projectsRoutes(deps));
- app.route("/api/projects/:projectId/members", membersRoutes(deps));
- app.route("/api/projects/:projectId/models", modelsRoutes(deps));
- app.route("/api/projects/:projectId/model-oauth", modelOAuthRoutes(deps));
- app.route("/api/projects/:projectId/chat-defaults", chatDefaultsRoutes(deps));
- app.route("/api/projects/:projectId/command-policy", commandPolicyRoutes(deps));
- app.route("/api/projects/:projectId/agents", agentsRoutes(deps));
- app.route("/api/projects/:projectId/dirs", dirsRoutes(deps));
- app.route("/api/projects/:projectId/dir-skills", directorySkillsRoutes(deps));
- app.route("/api/projects/:projectId/benchmarks", benchmarksRoutes(deps));
- app.route("/api/projects/:projectId/agents/:agentId/config", agentConfigRoutes(deps));
- app.route("/api/projects/:projectId/agents/:agentId/vault", vaultRoutes(deps));
- app.route("/api/projects/:projectId/agents/:agentId/memory", memoryRoutes(deps));
- app.route("/api/projects/:projectId/agents/:agentId/schedules", scheduleRoutes(deps));
- app.route("/api/projects/:projectId/agents/:agentId/skills", agentSkillsRoutes(deps));
- app.route("/api/projects/:projectId/agents/:agentId/plugins", agentPluginsRoutes(deps));
- app.route("/api/projects/:projectId/agents/:agentId/hooks", agentHooksRoutes(deps));
- app.route("/api/projects/:projectId/agents/:agentId", agentTransferRoutes(deps));
- app.route("/api/projects/:projectId/agents/:agentId/traces", agentTracesRoutes(deps));
- app.route("/api/projects/:projectId/agents/:agentId/sessions", agentSessionsRoutes(deps));
- app.route("/api/projects/:projectId/usage", usageRoutes(deps));
- app.route("/api/sessions", sessionsRoutes(deps));
- app.route("/api/sessions", sessionMessagingRoutes(deps));
-
- // 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.
- app.route("/preview", previewRoutes(deps));
-
- // 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;
-}
diff --git a/packages/server/src/auth-token.ts b/packages/server/src/auth-token.ts
index b461fe60..8a162b67 100644
--- a/packages/server/src/auth-token.ts
+++ b/packages/server/src/auth-token.ts
@@ -9,6 +9,7 @@ import fs from "node:fs";
import { openExistingDatabase } from "./db/database.js";
import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";
import { UsersRepo } from "./db/repos/users.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
/** An hour: long enough for a controller to finish, short enough to forget. */
export const CLI_TOKEN_TTL_MS = 60 * 60_000;
@@ -58,12 +59,12 @@ export function mintApiToken(
let db: ReturnType<typeof openExistingDatabase> | null = null;
try {
db = openExistingDatabase(dbPath);
- if (new UsersRepo(db).findById(userId) === null) {
+ if (wire(UsersRepo, { db: db }).findById(userId) === null) {
return { outcome: "failed", detail: `no such account: ${userId}` };
}
// The repo is the single minting point (token shape, hash, TTL ceiling), so a CLI-minted
// row cannot drift from one the server issues itself.
- const { token, expiresAt } = new AuthSessionsRepo(db).issue({
+ const { token, expiresAt } = wire(AuthSessionsRepo, { db: db }).issue({
userId,
via: "cli",
now: opts.now ?? new Date(),
diff --git a/packages/server/src/auth/service.ts b/packages/server/src/auth/service.ts
index 3b30c22f..f20e8286 100644
--- a/packages/server/src/auth/service.ts
+++ b/packages/server/src/auth/service.ts
@@ -15,6 +15,8 @@ import { sessionTokenHash } from "../db/repos/auth-sessions.js";
import type { SessionViaValue, AuthSessionsRepo } from "../db/repos/auth-sessions.js";
import type { AuthRuntimeState } from "./runtime-state.js";
import { SCRYPT_COST, hashPassword, verifyPassword } from "./password.js";
+import { Component, Use, Interface } from "@prismshadow/penguin-core/kernel";
+import type { AuthState, Config, Overrides } from "../hmr/capabilities.js";
export const MIN_PASSWORD_LENGTH = 8;
@@ -64,37 +66,39 @@ export function toUserInfo(row: UserRow): UserInfo {
};
}
-export interface AuthServiceDeps {
- users: UsersRepo;
- authSessions: AuthSessionsRepo;
+@Component()
+export class AuthService {
+ @Use() private readonly users!: UsersRepo;
+ @Use() private readonly authSessions!: AuthSessionsRepo;
/**
* Process-scoped auth values (runtime-state.ts). Held by the RUNTIME so the link a boot
* printed survives a platform push; everything else about auth is rebuilt with the App.
*/
- state: AuthRuntimeState;
- /** Provisions the initial Project at signup (injected by project-service, to avoid a circular dependency). */
- provisionInitialProject: (user: UserRow, isAdmin: boolean) => Promise<void>;
- /** Fixed initial password for the seeded admin (config.seedAdminPassword); null generates a random one at seed time. */
- seedAdminPassword: string | null;
- sessionTtlMs: number;
- sessionRenewMs: number;
- /** Test double: scrypt work factor for hashes this service writes (SCRYPT_COST in production). */
- passwordHashCost?: number;
- now?: () => Date;
-}
-
-export class AuthService {
- private readonly now: () => Date;
- private readonly hashCost: number;
+ @Use() private readonly state!: AuthState;
+ /** Provisions the initial Project at signup — declared at the consumer, below. */
+ @Use() private readonly provisioner!: InitialProjectProvisioner;
+ @Use() private readonly config!: Config;
+ @Use() private readonly overrides!: Overrides;
+ private now: () => Date = () => new Date();
+ /** scrypt work factor for hashes this service writes; a test double lowers it. */
+ private hashCost: number = SCRYPT_COST;
/** Session lifetime, for the cookie that must expire WITH the session, not before it. */
get sessionTtlMs(): number {
- return this.deps.sessionTtlMs;
+ return this.config.authSessionTtlMs;
+ }
+ private get sessionRenewMs(): number {
+ return this.config.authSessionRenewMs;
+ }
+ /** Fixed initial password for the seeded admin; null generates a random one at seed time. */
+ private get seedAdminPassword(): string | null {
+ return this.config.seedAdminPassword;
}
- constructor(private readonly deps: AuthServiceDeps) {
- this.now = deps.now ?? (() => new Date());
- this.hashCost = deps.passwordHashCost ?? SCRYPT_COST;
- this.deps.authSessions.deleteExpired(this.now().toISOString());
+ setup(): void {
+ const overrides = this.overrides.value();
+ this.now = overrides.now ?? this.now;
+ this.hashCost = overrides.passwordHashCost ?? SCRYPT_COST;
+ this.authSessions.deleteExpired(this.now().toISOString());
}
/**
@@ -105,13 +109,13 @@ export class AuthService {
mintFirstLogin(): string | null {
if (!this.adminPasswordIsInitial()) return null;
if (
- this.deps.state.firstLoginToken !== null &&
- this.authenticateWithMeta(this.deps.state.firstLoginToken) === null
+ this.state.firstLoginToken !== null &&
+ this.authenticateWithMeta(this.state.firstLoginToken) === null
) {
- this.deps.state.firstLoginToken = null;
+ this.state.firstLoginToken = null;
}
- this.deps.state.firstLoginToken ??= this.issueSession(ADMIN_USER_ID, "setup");
- return this.deps.state.firstLoginToken;
+ this.state.firstLoginToken ??= this.issueSession(ADMIN_USER_ID, "setup");
+ return this.state.firstLoginToken;
}
/**
@@ -120,7 +124,7 @@ export class AuthService {
* that or the rescue link stays suppressed.
*/
async adminPasswordIs(password: string): Promise<boolean> {
- const row = this.deps.users.findById(ADMIN_USER_ID);
+ const row = this.users.findById(ADMIN_USER_ID);
return row !== null && (await verifyPassword(password, row.passwordHash));
}
@@ -130,8 +134,8 @@ export class AuthService {
* the server retries on next startup.
*/
async seedAdmin(): Promise<void> {
- if (this.deps.users.count() > 0) return;
- const password = this.deps.seedAdminPassword ?? generateInitialAdminPassword();
+ if (this.users.count() > 0) return;
+ const password = this.seedAdminPassword ?? generateInitialAdminPassword();
// A pinned override must meet the same policy as every other password — rejected before
// any insert, so a configuration typo cannot create a trivially weak privileged account.
if (password.length < MIN_PASSWORD_LENGTH) {
@@ -148,11 +152,11 @@ export class AuthService {
avatar: null,
createdAt: this.now().toISOString(),
};
- this.deps.users.insert(user);
+ this.users.insert(user);
try {
- await this.deps.provisionInitialProject(user, true);
+ await this.provisioner.provisionInitialProject(user, true);
} catch (err) {
- this.deps.users.delete(user.userId);
+ this.users.delete(user.userId);
throw err;
}
}
@@ -163,14 +167,14 @@ export class AuthService {
* because a prefetching browser would burn it before its reader clicked.
*/
redeemFirstLogin(given: string): string | null {
- const expected = this.deps.state.firstLoginToken;
+ const expected = this.state.firstLoginToken;
if (expected === null || given === "" || !tokensEqual(given, expected)) return null;
return this.authenticateWithMeta(expected) === null ? null : expected;
}
/** Whether the built-in admin still runs on its initial password (gates the first-login link). */
adminPasswordIsInitial(): boolean {
- return this.deps.users.findById(ADMIN_USER_ID)?.passwordIsInitial === true;
+ return this.users.findById(ADMIN_USER_ID)?.passwordIsInitial === true;
}
/** Consecutive login failures per userId (see the throttling comment on the constants). */
@@ -199,7 +203,7 @@ export class AuthService {
);
}
}
- const row = this.deps.users.findById(userId);
+ const row = this.users.findById(userId);
const ok = row !== null && (await verifyPassword(password, row.passwordHash));
if (!row || !ok) {
this.loginFailures.set(userId, {
@@ -209,7 +213,7 @@ export class AuthService {
throw new HttpError(401, "invalid_credentials", "Incorrect username or password.");
}
this.loginFailures.delete(userId);
- this.deps.authSessions.deleteExpired(this.now().toISOString());
+ this.authSessions.deleteExpired(this.now().toISOString());
return { user: toUserInfo(row), token: this.issueSession(row.userId, "password") };
}
@@ -219,7 +223,7 @@ export class AuthService {
* broken deployment (seeding runs before the route exists).
*/
loginDesktop(): { user: UserInfo; token: string } {
- const row = this.deps.users.findById(ADMIN_USER_ID);
+ const row = this.users.findById(ADMIN_USER_ID);
if (!row) {
throw new HttpError(500, "internal", "Built-in admin has not been seeded.");
}
@@ -228,7 +232,7 @@ export class AuthService {
/** Self password change (user settings): validates the old password first; the current session stays valid. */
async changePassword(userId: string, oldPassword: string, newPassword: string): Promise<void> {
- const row = this.deps.users.findById(userId);
+ const row = this.users.findById(userId);
if (!row || !(await verifyPassword(oldPassword, row.passwordHash))) {
throw new HttpError(400, "password_mismatch", "Current password is incorrect.");
}
@@ -248,7 +252,7 @@ export class AuthService {
if (newPassword.length < MIN_PASSWORD_LENGTH) {
throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
}
- this.deps.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);
+ this.users.updatePassword(userId, await hashPassword(newPassword, this.hashCost), false);
// A successful set proves at least what the successful login that resets the counter
// proves (the old password, or a desktop/setup session), so it resets it too. Without
// this, anyone spamming the login endpoint holds the backoff window open, and the sign-in
@@ -260,14 +264,14 @@ export class AuthService {
// allowed to change the password without knowing the old one — so one left behind is an
// account takeover waiting to happen.
if (userId === ADMIN_USER_ID) {
- this.deps.authSessions.deleteByUserAndVia(userId, "setup");
- this.deps.state.firstLoginToken = null;
+ this.authSessions.deleteByUserAndVia(userId, "setup");
+ this.state.firstLoginToken = null;
}
}
/** Ends a session: the row is the session, so logout deletes it. Unknown token is a no-op. */
logout(token: string): void {
- this.deps.authSessions.delete(sessionTokenHash(token));
+ this.authSessions.delete(sessionTokenHash(token));
}
/**
@@ -277,7 +281,7 @@ export class AuthService {
* outlive the App a push replaces (auth/runtime-state.ts).
*/
localApiToken(): string | null {
- return this.deps.state.apiToken;
+ return this.state.apiToken;
}
/**
@@ -287,10 +291,10 @@ export class AuthService {
* null on mismatch, when no token was minted, or when the admin row is missing.
*/
authenticateApiToken(token: string): { user: UserRow; via: SessionVia } | null {
- const apiToken = this.deps.state.apiToken;
+ const apiToken = this.state.apiToken;
if (apiToken === null || token.length === 0) return null;
if (!tokensEqual(token, apiToken)) return null;
- const user = this.deps.users.findById(ADMIN_USER_ID);
+ const user = this.users.findById(ADMIN_USER_ID);
return user === null ? null : { user, via: "token" };
}
@@ -302,23 +306,20 @@ export class AuthService {
*/
authenticateWithMeta(token: string): { user: UserRow; via: SessionVia; renewed: boolean } | null {
const tokenHash = sessionTokenHash(token);
- const session = this.deps.authSessions.findByTokenHash(tokenHash);
+ const session = this.authSessions.findByTokenHash(tokenHash);
if (!session) return null;
const now = this.now();
const expiresAt = Date.parse(session.expiresAt);
if (expiresAt <= now.getTime()) {
- this.deps.authSessions.delete(tokenHash);
+ this.authSessions.delete(tokenHash);
return null;
}
- const user = this.deps.users.findById(session.userId);
+ const user = this.users.findById(session.userId);
if (!user) return null;
- const renewable = expiresAt - Date.parse(session.createdAt) >= this.deps.sessionRenewMs;
+ const renewable = expiresAt - Date.parse(session.createdAt) >= this.sessionRenewMs;
let renewed = false;
- if (renewable && expiresAt - now.getTime() < this.deps.sessionRenewMs) {
- this.deps.authSessions.touch(
- tokenHash,
- new Date(now.getTime() + this.deps.sessionTtlMs).toISOString(),
- );
+ if (renewable && expiresAt - now.getTime() < this.sessionRenewMs) {
+ this.authSessions.touch(tokenHash, new Date(now.getTime() + this.sessionTtlMs).toISOString());
renewed = true;
}
const via: SessionVia =
@@ -327,11 +328,16 @@ export class AuthService {
}
private issueSession(userId: string, via: SessionViaValue): string {
- return this.deps.authSessions.issue({
+ return this.authSessions.issue({
userId,
via,
now: this.now(),
- ttlMs: this.deps.sessionTtlMs,
+ ttlMs: this.sessionTtlMs,
}).token;
}
}
+
+/** What signing a new user in needs of project administration — declared at the consumer. */
+export abstract class InitialProjectProvisioner extends Interface<{
+ provisionInitialProject(user: UserRow, isAdmin: boolean): Promise<void>;
+}>() {}
diff --git a/packages/server/src/db/repos/agents.ts b/packages/server/src/db/repos/agents.ts
index 197f1b45..5b978506 100644
--- a/packages/server/src/db/repos/agents.ts
+++ b/packages/server/src/db/repos/agents.ts
@@ -1,7 +1,8 @@
/**
* agents table repo: Agent index; name/description live in system_config.yaml.
*/
-import type { DatabaseSync } from "node:sqlite";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
export interface AgentRow {
projectId: string;
@@ -9,8 +10,9 @@ export interface AgentRow {
createdAt: string;
}
+@Component()
export class AgentsRepo {
- constructor(private readonly db: DatabaseSync) {}
+ @Use() private readonly db!: Db;
/** Idempotent insert: backfills an untracked Agent discovered via directory scan; shared with explicit creation. */
insertOrIgnore(row: AgentRow): void {
diff --git a/packages/server/src/db/repos/auth-sessions.ts b/packages/server/src/db/repos/auth-sessions.ts
index 743e5f38..9409f9f3 100644
--- a/packages/server/src/db/repos/auth-sessions.ts
+++ b/packages/server/src/db/repos/auth-sessions.ts
@@ -4,7 +4,8 @@
* so a CLI-minted row cannot drift from one the server issues itself.
*/
import { createHash, randomBytes } from "node:crypto";
-import type { DatabaseSync } from "node:sqlite";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
/** How a session was established, as stored. NULL on rows formed before the column existed. */
export type SessionViaValue = "password" | "desktop" | "setup" | "cli";
@@ -22,8 +23,9 @@ export function sessionTokenHash(token: string): string {
return createHash("sha256").update(token).digest("hex");
}
+@Component()
export class AuthSessionsRepo {
- constructor(private readonly db: DatabaseSync) {}
+ @Use() private readonly db!: Db;
/**
* Mints a session and returns the raw token for a cookie or the terminal. `maxTtlMs` caps a
diff --git a/packages/server/src/db/repos/errors.ts b/packages/server/src/db/repos/errors.ts
index 2daa2ad5..00d7e9a8 100644
--- a/packages/server/src/db/repos/errors.ts
+++ b/packages/server/src/db/repos/errors.ts
@@ -20,7 +20,8 @@
* wrongly delete still-valid data within the cap. The first line of defense is
* ErrorRecorder's short-window deduplication.
*/
-import type { DatabaseSync } from "node:sqlite";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
/** Row cap: once exceeded, oldest rows are evicted in ascending id order (see file header). */
export const MAX_ROWS = 20000;
@@ -88,19 +89,14 @@ export interface ErrorItem {
message: string;
}
+@Component()
export class ErrorsRepo {
- private readonly maxRows: number;
- private readonly pruneEvery: number;
+ private readonly maxRows: number = MAX_ROWS;
+ private readonly pruneEvery: number = PRUNE_EVERY;
/** Insert count since the last capacity check (see file header: avoids COUNT on every call). */
private sinceCheck = 0;
- constructor(
- private readonly db: DatabaseSync,
- limits: ErrorsRepoLimits = {},
- ) {
- this.maxRows = limits.maxRows ?? MAX_ROWS;
- this.pruneEvery = limits.pruneEvery ?? PRUNE_EVERY;
- }
+ @Use() private readonly db!: Db;
insert(r: ErrorRecordInsert): void {
this.db
diff --git a/packages/server/src/db/repos/members.ts b/packages/server/src/db/repos/members.ts
index 36f64103..7c207736 100644
--- a/packages/server/src/db/repos/members.ts
+++ b/packages/server/src/db/repos/members.ts
@@ -2,7 +2,8 @@
* Repo for the project_members table: only member
* authorization relationships — the owner is never in this table.
*/
-import type { DatabaseSync } from "node:sqlite";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
export interface MemberRow {
projectId: string;
@@ -10,8 +11,9 @@ export interface MemberRow {
createdAt: string;
}
+@Component()
export class MembersRepo {
- constructor(private readonly db: DatabaseSync) {}
+ @Use() private readonly db!: Db;
insert(row: MemberRow): void {
this.db
diff --git a/packages/server/src/db/repos/messaging-bindings.ts b/packages/server/src/db/repos/messaging-bindings.ts
index 45c010ef..d4c97b5e 100644
--- a/packages/server/src/db/repos/messaging-bindings.ts
+++ b/packages/server/src/db/repos/messaging-bindings.ts
@@ -27,7 +27,8 @@
* fields and its account identity stay. The repo does not interpret the document; each
* channel's connector and route own its shape.
*/
-import type { DatabaseSync } from "node:sqlite";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
export interface MessagingBindingRow {
sessionId: string;
@@ -116,8 +117,9 @@ function mapRow(r: Record<string, unknown>): MessagingBindingRow {
};
}
+@Component()
export class MessagingBindingsRepo {
- constructor(private readonly db: DatabaseSync) {}
+ @Use() private readonly db!: Db;
/** The Session's saved config of ONE channel (null when that channel is not configured). */
find(sessionId: string, channel: string): MessagingBindingRow | null {
diff --git a/packages/server/src/db/repos/projects.ts b/packages/server/src/db/repos/projects.ts
index 5053d744..f715c345 100644
--- a/packages/server/src/db/repos/projects.ts
+++ b/packages/server/src/db/repos/projects.ts
@@ -2,8 +2,9 @@
* Repo for the projects table: an index of ownership
* relationships; the display name lives in project_config.toml.
*/
-import type { DatabaseSync } from "node:sqlite";
import type { ProjectRole } from "../../api/types.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
export interface ProjectRow {
projectId: string;
@@ -23,8 +24,9 @@ function mapRow(r: Record<string, unknown>): ProjectRow {
};
}
+@Component()
export class ProjectsRepo {
- constructor(private readonly db: DatabaseSync) {}
+ @Use() private readonly db!: Db;
insert(row: ProjectRow): void {
this.db
diff --git a/packages/server/src/db/repos/schedules.ts b/packages/server/src/db/repos/schedules.ts
index e6129b1f..04b56185 100644
--- a/packages/server/src/db/repos/schedules.ts
+++ b/packages/server/src/db/repos/schedules.ts
@@ -7,7 +7,8 @@
* (registerOrSync resets the trigger state); a change to the file content fingerprint
* only clears the disabled flag (the file becomes effective again after reconciliation).
*/
-import type { DatabaseSync } from "node:sqlite";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
export interface ScheduleStateRow {
projectId: string;
@@ -39,8 +40,9 @@ function mapRow(r: Record<string, unknown>): ScheduleStateRow {
};
}
+@Component()
export class SchedulesRepo {
- constructor(private readonly db: DatabaseSync) {}
+ @Use() private readonly db!: Db;
find(projectId: string, agentId: string, name: string): ScheduleStateRow | null {
const r = this.db
diff --git a/packages/server/src/db/repos/server-settings.ts b/packages/server/src/db/repos/server-settings.ts
index 497d85f0..f0178f97 100644
--- a/packages/server/src/db/repos/server-settings.ts
+++ b/packages/server/src/db/repos/server-settings.ts
@@ -3,12 +3,13 @@
* with JSON-encoded values. An absent row means the setting's built-in default, so
* settings added after a web.db was formed need no migration.
*/
-import type { DatabaseSync } from "node:sqlite";
import {
clampAttachmentMb,
DEFAULT_ATTACHMENT_MAX_MB,
DEFAULT_ATTACHMENT_TOTAL_MB,
} from "../../services/attachment-limits.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
/** Key of the "application uses the proxy" switch (the server's own outbound dispatcher); default on. */
const PROXY_FOR_APP_KEY = "proxy_for_app";
@@ -33,8 +34,9 @@ const ATTACHMENT_MAX_MB_KEY = "attachment_max_mb";
/** Key of the per-message total attachment limit, in whole MB; default DEFAULT_ATTACHMENT_TOTAL_MB. */
const ATTACHMENT_TOTAL_MB_KEY = "attachment_total_mb";
+@Component()
export class ServerSettingsRepo {
- constructor(private readonly db: DatabaseSync) {}
+ @Use() private readonly db!: Db;
/** Returns the raw JSON-encoded value; null if never set. */
get(key: string): string | null {
diff --git a/packages/server/src/db/repos/sessions.ts b/packages/server/src/db/repos/sessions.ts
index ff768342..303df60e 100644
--- a/packages/server/src/db/repos/sessions.ts
+++ b/packages/server/src/db/repos/sessions.ts
@@ -2,9 +2,10 @@
* sessions table repo:
* Session index, approval mode, and auto-generated title; Session-level routes use this to look up project ownership.
*/
-import type { DatabaseSync } from "node:sqlite";
import type { ThinkingLevelName } from "@prismshadow/penguin-core/interfaces";
import type { ApprovalMode } from "../../api/types.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
export interface SessionRow {
sessionId: string;
@@ -71,8 +72,9 @@ function mapRow(r: Record<string, unknown>): SessionRow {
};
}
+@Component()
export class SessionsRepo {
- constructor(private readonly db: DatabaseSync) {}
+ @Use() private readonly db!: Db;
insert(row: SessionRow): void {
this.runInsert("INSERT", row);
diff --git a/packages/server/src/db/repos/trace-index.ts b/packages/server/src/db/repos/trace-index.ts
index f1375d65..c59ae3ab 100644
--- a/packages/server/src/db/repos/trace-index.ts
+++ b/packages/server/src/db/repos/trace-index.ts
@@ -3,9 +3,10 @@
* services/trace-index.ts for the cache rules). Pure row access — reconciliation
* policy (mtime gates, head-reads) lives in the service.
*/
-import type { DatabaseSync } from "node:sqlite";
import type { SessionSource } from "../../api/types.js";
import { asSessionSource } from "../../runtime/session-sources.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
/** One indexed Trace shard. */
export interface TraceFileRow {
@@ -59,8 +60,9 @@ function mapSession(r: Record<string, unknown>): TraceSessionRow {
};
}
+@Component()
export class TraceIndexRepo {
- constructor(private readonly db: DatabaseSync) {}
+ @Use() private readonly db!: Db;
upsertFile(row: TraceFileRow): void {
// page_stats is a derivation of the shard's CONTENT: any observed size change voids
diff --git a/packages/server/src/db/repos/ui-prefs.ts b/packages/server/src/db/repos/ui-prefs.ts
index 984d5bc3..bf9fb34f 100644
--- a/packages/server/src/db/repos/ui-prefs.ts
+++ b/packages/server/src/db/repos/ui-prefs.ts
@@ -1,10 +1,12 @@
/**
* ui_prefs table repo (UI preferences): free-form JSON storage.
*/
-import type { DatabaseSync } from "node:sqlite";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
+@Component()
export class UiPrefsRepo {
- constructor(private readonly db: DatabaseSync) {}
+ @Use() private readonly db!: Db;
/** Returns the raw JSON string; null if never set. */
get(userId: string): string | null {
diff --git a/packages/server/src/db/repos/usage.ts b/packages/server/src/db/repos/usage.ts
index a468ff7c..cfc49a3d 100644
--- a/packages/server/src/db/repos/usage.ts
+++ b/packages/server/src/db/repos/usage.ts
@@ -5,8 +5,9 @@
* so every aggregation is broken down by the `(provider, model_id)` pair and returns
* raw Token sums (a model_id shared across providers is aggregated separately; never concatenated).
*/
-import type { DatabaseSync } from "node:sqlite";
import type { UsageGroupBy } from "../../api/types.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
export interface UsageRecordInsert {
ts: string;
@@ -181,8 +182,9 @@ function toSums(r: Record<string, unknown>): UsageModelSums {
};
}
+@Component()
export class UsageRepo {
- constructor(private readonly db: DatabaseSync) {}
+ @Use() private readonly db!: Db;
insert(r: UsageRecordInsert): void {
this.db
diff --git a/packages/server/src/db/repos/users.ts b/packages/server/src/db/repos/users.ts
index e34e5125..6b8f344e 100644
--- a/packages/server/src/db/repos/users.ts
+++ b/packages/server/src/db/repos/users.ts
@@ -2,7 +2,8 @@
* users table repo: pure SQL wrapper, no business rules.
* user_id is the login name (a semantic id, specified at creation, immutable).
*/
-import type { DatabaseSync } from "node:sqlite";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Db } from "../../hmr/capabilities.js";
export interface UserRow {
userId: string;
@@ -29,8 +30,9 @@ function mapRow(r: Record<string, unknown>): UserRow {
};
}
+@Component()
export class UsersRepo {
- constructor(private readonly db: DatabaseSync) {}
+ @Use() private readonly db!: Db;
insert(row: UserRow): void {
this.db
diff --git a/packages/server/src/hmr/README.md b/packages/server/src/hmr/README.md
index b5ff5aea..2f64a55f 100644
--- a/packages/server/src/hmr/README.md
+++ b/packages/server/src/hmr/README.md
@@ -24,7 +24,7 @@ artifact storage and the atomic `harness.json` commit.
Authentication is NOT on that list, and used to be. Who may set a password, how long a session
lasts, how logins are throttled — that is policy, and a runtime that owned it made every auth
fix wait for a full reinstall: a platform naming a member an older runtime's AuthService lacked
-was refused at the handshake. The App builds its own AuthService now (app.ts's buildAppDeps).
+was refused at the handshake. The App builds its own AuthService now (the `auth` module under src/modules).
What the runtime still publishes is `runtime:auth-state`, the process-scoped values a push must
not forget — the state layer, not a capability.
diff --git a/packages/server/src/hmr/capabilities.ts b/packages/server/src/hmr/capabilities.ts
index f5dd75d1..4a983244 100644
--- a/packages/server/src/hmr/capabilities.ts
+++ b/packages/server/src/hmr/capabilities.ts
@@ -21,16 +21,17 @@
* registry.
*/
import type { DatabaseSync } from "node:sqlite";
-import type { Resources } from "@prismshadow/penguin-core/kernel";
+import type { Resources, Opaque, ClassCtx } from "@prismshadow/penguin-core/kernel";
import type { ServerConfig } from "../config.js";
import type { AuthRuntimeState } from "../auth/runtime-state.js";
import { newAuthRuntimeState } from "../auth/runtime-state.js";
-import type { ChannelHub } from "../runtime/channel.js";
+import type { ChannelHub, Channel } from "../runtime/channel.js";
import type { ProxySettings } from "../net/proxy.js";
import type { BuildDepsOverrides } from "../app.js";
-import type { HmrHost } from "../hmr/host.js";
+import type { HmrHost } from "./host.js";
import type { DesktopService } from "../services/desktop-service.js";
import type { LifecycleService } from "../services/lifecycle-service.js";
+import { Interface, Module, Provide } from "@prismshadow/penguin-core/kernel";
/**
* What one side of the seam speaks: a family, and a Go-style structural interface per
@@ -326,3 +327,134 @@ export function claimRuntimeCapabilities(resources: Resources): RuntimeClaim {
caps: { config, db, authState, channels, proxyControl, hmr, desktop, lifecycle, overrides },
};
}
+
+/**
+ * What the runtime publishes, as the platform's modules see it. The runtime registers live
+ * objects in the resource registry (hmr/capabilities.ts); this module claims them once and
+ * exposes each under an interface here. Every other module reaches the runtime only through
+ * these — `requires: { db: { iface: "runtime#Db", from: "RuntimeModule" } }` — so what a bundle
+ * needs from its host is written down and checked, not assumed.
+ */
+
+/** The process configuration object — one per process; the listen callback writes the real port into it. */
+export abstract class Config extends Interface<ServerConfig>() {}
+
+/** The SQLite handle (single-writer, one per process). Statements are host objects. */
+export abstract class Db extends Interface<{
+ prepare(sql: string): Opaque<"StatementSync", ReturnType<DatabaseSync["prepare"]>>;
+ exec(sql: string): void;
+ close(): void;
+}>() {}
+
+/** One SSE channel (the class in runtime/channel.ts satisfies this). */
+export type ChannelApi = Pick<Channel, "publish" | "sendTo" | "subscribe" | "replayAfter">;
+
+export abstract class Channels extends Interface<{
+ get(key: string): ChannelApi;
+ peek(key: string): ChannelApi | undefined;
+ broadcast(prefix: string, data: unknown, event?: string): void;
+ dispose(): void;
+ setActivityProbe(probe: (key: string) => boolean): void;
+}>() {}
+/** Compile-time proof the hub satisfies the contract. */
+export type _ChannelsCheck = ChannelHub extends Channels ? true : never;
+
+/** The global fetch dispatcher's settings — runtime-owned, since a bundle's own undici is not the one `globalThis.fetch` routes through. */
+export abstract class Proxy extends Interface<{
+ apply(settings: ProxySettings): void;
+}>() {}
+
+/** The hot-update host: the cross-generation resource registry and the current App. */
+export abstract class Hmr extends Interface<{
+ resources: Resources;
+ ensure(): Promise<Opaque<"PlatformInstance", Awaited<ReturnType<HmrHost["ensure"]>>>>;
+ resolveWebSource(): Opaque<
+ "WebSource",
+ NonNullable<ReturnType<HmrHost["resolveWebSource"]>>
+ > | null;
+ assetsDir(): string | null;
+ dispose(): void;
+}>() {}
+export type _HmrCheck = HmrHost extends Hmr ? true : never;
+
+export type DesktopApi = Pick<
+ DesktopService,
+ | "verifyToken"
+ | "redeemLoginToken"
+ | "onShutdownRequest"
+ | "requestShutdown"
+ | "getUpdateStatus"
+ | "setUpdateStatus"
+ | "onUpdateCommand"
+ | "requestUpdateCommand"
+>;
+
+/** The desktop shell's service, or null when this server is not the shell's child. */
+export abstract class Desktop extends Interface<{
+ current(): DesktopApi | null;
+}>() {}
+
+export abstract class AuthState extends Interface<AuthRuntimeState>() {}
+
+/** Process lifecycle: whether a supervisor relaunches this process, and the restart trigger. */
+export abstract class Lifecycle extends Interface<
+ Pick<LifecycleService, "supervised" | "onRestartRequest" | "requestRestart">
+>() {}
+
+/** Construction overrides — production publishes {}, tests publish live collaborators. */
+export abstract class Overrides extends Interface<{
+ value(): Opaque<"BuildDepsOverrides", BuildDepsOverrides>;
+}>() {}
+
+export abstract class Log extends Interface<{
+ line(text: string): void;
+}>() {}
+
+/**
+ * Whether a registry resource group inherited from the previous App may be adopted — the
+ * platform node decides from the resource-interfaces declaration (hmr/platform.ts); a
+ * module that parks handles asks before claiming them back.
+ */
+export abstract class ResourceGroups extends Interface<{
+ adoptable(group: string): boolean;
+}>() {}
+
+/**
+ * The claimed capabilities are handed in by the platform node, which is the one place the
+ * registry is read (see hmr/platform.ts): this module only presents them. It is the one
+ * module class with constructor arguments, so the platform pre-builds its instance.
+ */
+@Module()
+export class RuntimeModule {
+ @Provide() config!: Config;
+ @Provide() db!: Db;
+ @Provide() channels!: Channels;
+ @Provide() proxy!: Proxy;
+ @Provide() hmr!: Hmr;
+ @Provide() desktop!: Desktop;
+ @Provide() authState!: AuthState;
+ @Provide() lifecycle!: Lifecycle;
+ @Provide() overrides!: Overrides;
+ @Provide() log!: Log;
+ @Provide() resourceGroups!: ResourceGroups;
+ constructor(
+ private readonly caps: RuntimeCapabilities,
+ private readonly adoptable: (group: string) => boolean,
+ ) {}
+
+ setup(_ctx: ClassCtx) {
+ const { caps } = this;
+ const log = caps.overrides.log ?? ((line: string) => console.log(line));
+ this.config = caps.config;
+ this.db = caps.db;
+ this.channels = caps.channels;
+ this.proxy = { apply: caps.proxyControl };
+ this.hmr = caps.hmr;
+ this.desktop = { current: () => caps.desktop };
+ this.authState = caps.authState;
+ this.lifecycle = caps.lifecycle;
+ this.overrides = { value: () => caps.overrides };
+ this.log = { line: log };
+ this.resourceGroups = { adoptable: this.adoptable };
+ }
+}
diff --git a/packages/server/src/hmr/host.ts b/packages/server/src/hmr/host.ts
index 75e9e42b..a30b3a1a 100644
--- a/packages/server/src/hmr/host.ts
+++ b/packages/server/src/hmr/host.ts
@@ -74,8 +74,9 @@ import type { Instance, Json, AnyIface, AnyImpl } from "@prismshadow/penguin-cor
import { boot, initialDoc, upgrade } from "@prismshadow/penguin-core/kernel";
import { HotResources } from "./resources.js";
import type { Manifest } from "./manifest.js";
-import type { PlatformApi } from "../hmr/platform.js";
-import { packagedPlatform } from "../hmr/platform.js";
+import { MATERIALIZED } from "./manifest.js";
+import type { PlatformApi } from "./platform.js";
+import { packagedPlatform } from "./platform.js";
/**
* The contract every platform bundle must satisfy — packaged or pushed. `context` is the
@@ -125,13 +126,6 @@ export interface UpgradeAllTarget {
source?: GitSource;
}
-/**
- * Written into an assets directory once every file in it is on disk. Its absence marks a
- * directory whose materialization was interrupted; no asset path can collide with it
- * (assets arrive as `node_modules/...` paths).
- */
-export const MATERIALIZED = ".materialized";
-
export type UpgradeOutcome =
| {
status: "ok";
diff --git a/packages/server/src/hmr/manifest.ts b/packages/server/src/hmr/manifest.ts
index b21a4783..070c643d 100644
--- a/packages/server/src/hmr/manifest.ts
+++ b/packages/server/src/hmr/manifest.ts
@@ -30,6 +30,13 @@ import type { HarnessInfo } from "@prismshadow/penguin-core";
* only ever produce handles that fail to reclaim). Paths are relative to hmrDir
* (`<root>/hmr`).
*/
+/**
+ * Written into an assets directory once every file in it is on disk. Its absence marks a
+ * directory whose materialization was interrupted; no asset path can collide with it
+ * (assets arrive as `node_modules/...` paths).
+ */
+export const MATERIALIZED = ".materialized";
+
export interface Manifest {
platform?: { bundle: string };
/**
diff --git a/packages/server/src/hmr/platform.ts b/packages/server/src/hmr/platform.ts
index ec019cd6..da12907b 100644
--- a/packages/server/src/hmr/platform.ts
+++ b/packages/server/src/hmr/platform.ts
@@ -23,30 +23,44 @@
* 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 type {
+ Impl,
+ Json,
+ Park,
+ IfaceTable,
+ ManifestTable,
+ ModuleDef,
+ ModuleTree,
+} from "@prismshadow/penguin-core/kernel";
+import {
+ defineIface,
+ schema,
+ type,
+ bootModules,
+ moduleDefOf,
+} from "@prismshadow/penguin-core/kernel";
+import type { PlatformBundle } from "./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 type {
- PenguinInterface,
- SandboxProviderSource,
- SandboxSettings,
-} from "@prismshadow/penguin-core/plugin";
-import { SandboxService } from "../sandbox/index.js";
-import { buildAppDeps, createApp, type AppDeps, type BuildDepsOverrides } from "../app.js";
-import { seamHttp } from "./hono-seam.js";
+import { Hono } from "hono";
+import type { AppEnv } from "../auth/middleware.js";
+import type { AuthService } from "../auth/service.js";
+import type { SessionManager } from "../runtime/session-manager.js";
+import { terminalRoutes } from "../terminal/routes.js";
+import type { Identity } from "../terminal/identity.js";
+import { platformDef } from "../platform.js";
+import { SandboxModule } from "../sandbox/service.js";
+import ifaceTable from "../ifaces.json" with { type: "json" };
+import { declined, seamHttp } from "./hono-seam.js";
import {
PENGUIN_FAMILY,
RESOURCE_IFACES_RESOURCE_ID,
claimRuntimeCapabilities,
} from "./capabilities.js";
import type { Interfaces, MembersOf } from "./capabilities.js";
-import type { HarnessContext } from "../plugin/index.js";
import { pluginHostFrom } from "../plugin/host.js";
-import { instantiateWorkflows, WorkflowFactories } from "../plugin/workflow.js";
export interface PlatformApi extends Park {
info(): Json;
@@ -64,11 +78,11 @@ export interface PlatformApi extends Park {
terminals(): TerminalManager;
attachStream(ws: WebSocket, session: TerminalSession, url: URL, log: (l: string) => void): void;
/**
- * The business deps this App built (null on a declared bare kernel). In-process member,
+ * The module tree this App built (null on a declared bare kernel). In-process member,
* NOT a registry entry: the runtime holds this instance already (hmr.ensure()), so a
* "current App" pointer in the registry would be a duplicate channel.
*/
- business(): AppDeps | null;
+ business(): ModuleTree | null;
/** Process-exit graceful drain (manager ≤5s wrap-up, workflow park); no-op without business. */
shutdown(): Promise<void>;
/**
@@ -84,35 +98,73 @@ export interface PlatformApi extends Park {
* 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.
*/
+/**
+ * The platform node's parked document. It has ONE version and only grows: a field, once
+ * written, keeps its meaning and stays written, so any platform ever pushed to a data
+ * root can read the document the newest one parks — the rollback a hot update must never
+ * lose. `terminals` and `sandbox` are what the first platforms parked and still read;
+ * `modules` is what the module tree parks, one document per node. This platform writes
+ * all three and reads `modules` first.
+ */
export type PlatformCtx = {
motd: string;
+ /** pty handle ids (the terminal module's parked state, also written here for older readers). */
terminals?: string[];
- /**
- * Active sandbox settings — parked state, not service memory: a hot swap constructs a
- * fresh SandboxService, and without this the swap would silently reset a confining
- * deployment to unconfined. Optional so a document parked before the field existed
- * (and a default deployment, which never writes it) restores as confinement off.
- */
- sandbox?: SandboxSettings;
+ /** Sandbox settings (the sandbox module's parked state, also written here for older readers). */
+ sandbox?: Json;
+ /** Each module's parked document, by node name (kernel bootModules). */
+ modules?: Record<string, Json>;
};
export const PlatformIface = defineIface<PlatformApi, PlatformCtx>({
name: "platform",
version: 1,
context: schema<PlatformCtx>(
+ // arktype infers `unknown` for the index signature where the context says Json; the
+ // runtime shape is the same, so the one cast lives here. Undeclared keys pass, so a
+ // reader that predates a field is not stopped by it.
type({
motd: "string",
"terminals?": "string[]",
- "sandbox?": {
- mode: "'read-only' | 'workspace-write' | 'danger-full-access'",
- "network?": "'none'",
- "maskPaths?": "string[]",
- },
- }),
+ "sandbox?": "unknown",
+ "modules?": { "[string]": "unknown" },
+ }) as never,
),
methods: ["park", "info", "http", "terminals", "attachStream"],
});
+/** The node names the two parking modules were keyed by before nodes were named by class. */
+const RENAMED_NODES: Record<string, string> = {
+ terminal: "TerminalModule",
+ sandbox: "SandboxModule",
+};
+
+/**
+ * The module documents to boot from: what the last platform parked under `modules`
+ * (older node names mapped to the current ones), completed from the top-level fields
+ * when a platform older than the module tree parked them there.
+ */
+function parkedModules(context: PlatformCtx): Record<string, Json> {
+ const modules: Record<string, Json> = {};
+ for (const [key, value] of Object.entries(context.modules ?? {}))
+ modules[RENAMED_NODES[key] ?? key] = value;
+ if (modules.TerminalModule === undefined && context.terminals !== undefined)
+ modules.TerminalModule = { v: 1, self: { terminals: context.terminals } };
+ if (modules.SandboxModule === undefined && context.sandbox !== undefined)
+ modules.SandboxModule = { v: 1, self: { settings: context.sandbox } };
+ return modules;
+}
+
+/** A parking module's own state out of the tree's parked documents, for the top-level fields. */
+function parkedSelf(modules: Record<string, Json>, node: string): Record<string, Json> | null {
+ const doc = modules[node];
+ if (doc === null || typeof doc !== "object" || Array.isArray(doc)) return null;
+ const self = (doc as { self?: Json }).self;
+ return self !== null && typeof self === "object" && !Array.isArray(self)
+ ? (self as Record<string, Json>)
+ : null;
+}
+
/**
* The resource interfaces this platform parks, by ID-prefix group (see
* RESOURCE_IFACES_RESOURCE_ID in ./capabilities.ts): create() integrates a group its
@@ -188,10 +240,10 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
const inheritable = inherited !== undefined && inherited.family === DECLARED_RESOURCES.family;
// DECIDE ONLY. Disposing a group kills live ptys and child processes, and nothing
// brings them back — so the decision is computed here and ACTED ON at the bottom,
- // once this App is fully built. Everything between can still throw (plugin handlers,
- // workflow factories, the scheduler), and a boot that fails there is recovered by
- // re-booting the previous bundle; that recovery is only honest if the resources it
- // re-adopts are still alive.
+ // once this App is fully built. Everything between can still throw (a module's
+ // create, a workflow factory), and a boot that fails there is recovered by re-booting
+ // the previous bundle; that recovery is only honest if the resources it re-adopts are
+ // still alive.
const doomedGroups = Object.entries(inherited ?? {})
.filter(([group]) => group !== "family")
.filter(([group, offered]) => {
@@ -203,135 +255,65 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
return !inheritable || !offers;
})
.map(([group]) => group);
+ const adoptable = (group: string) => !doomedGroups.includes(group);
- const terminals = new TerminalManager(ctx.resources, {
- // A pushed bundle's node-pty binaries live where the host materialized them.
- assets: () => caps?.hmr.assetsDir() ?? null,
- });
- // 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 — unless their group
- // is doomed, in which case this build cannot speak the contract behind those handles
- // and must not adopt them. It does not dispose them either: that happens at the
- // commit below, so a failed boot leaves them for the recovered predecessor.
- terminals.adopt(doomedGroups.includes("terminal") ? [] : (context.terminals ?? []));
- // The plugin seam (see ../plugin/index.ts): the definition view first, then the
- // instance context, with the workflows built in between — so a plugin that registers
- // one always sees it instantiated in the App it registered into. The host is CLAIMED
- // from the registry, never imported (see pluginHostFrom).
+ // Plugins are modules (see ../plugin/): the host is CLAIMED from the registry,
+ // never imported (see pluginHostFrom), and its modules join the tree below.
const plugins = pluginHostFrom(ctx.resources);
- // Sandbox backends arrive as plugins through iface.sandbox (see ../plugin/);
- // duplicates are refused, and the service routes policies by capability.
- const sandboxProviders = new Map<string, SandboxProviderSource>();
- const pluginIface: PenguinInterface = {
- workflow: new WorkflowFactories(),
- tool: new Map(),
- sandbox: {
- registerProvider(name, provider) {
- if (sandboxProviders.has(name)) {
- throw new Error(`sandbox provider '${name}' is already registered`);
- }
- sandboxProviders.set(name, provider);
- },
- },
- };
- plugins.emit("initialize", pluginIface);
- // "Which commands run confined, under which policy, by which backend" is policy —
- // the whole capability lives in ../sandbox/ and reaches deployed machines by push;
- // only core's spawn seam is mechanism. The confiner reaches core as a plain argument
- // to buildAppDeps below — same-generation wiring, because the sessions that spawn
- // through it are hard-stopped with this App (see the dispose effect), so nothing
- // outlives the service that confines it.
- const sandbox = new SandboxService(sandboxProviders);
- // Rehydrate the parked settings (state rides the swap): without this, every hot push
- // would construct a fresh service on defaults and silently un-confine a deployment
- // that had confinement on.
- if (context.sandbox !== undefined) sandbox.configure(context.sandbox);
- // Typed as HarnessContext, not the bare contract: `terminals` is this harness's own
- // (see ../plugin/index.ts). Handlers receive it as PenguinContext and reach that
- // member only by casting, which is where the dependency on this embedder gets stated.
- const pluginContext: HarnessContext = {
- workflows: instantiateWorkflows(pluginIface.workflow),
- terminals,
- sandbox: {
- configure: (settings) => sandbox.configure(settings),
- settings: () => sandbox.currentSettings(),
- },
- };
- plugins.emit("create", pluginContext);
- // 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;
- // every other capability-less host was refused above.
- let deps: AppDeps | null = null;
+ let tree: ModuleTree;
+ let business: ModuleTree | null = null;
+ let terminals: TerminalManager;
if (caps === null) {
+ // A declared bare kernel: terminals only, no business surface. The module tree is
+ // reduced to what needs no runtime capability — the sandbox floor and the backends
+ // registered into it — so confinement settings still park and restore.
console.warn("[platform] bare kernel: terminals only, no business surface");
- } else {
- deps = buildAppDeps(caps, caps.overrides, () => sandbox.confiner());
- // Schedule scheduler: startup reconciliation (missed, don't backfill) + periodic
- // scan; only active while this App is.
- await deps.scheduler.start();
- // Messaging bridge: connect every enabled Session binding (channel event
- // streams); only active while this App is, like the scheduler.
- await deps.messaging.start();
- // Startup adoption sweep: fold Trace-only Sessions (legacy CLI-direct runs) into
- // the sessions index as client:'cli' rows, so every later list is pure SQLite.
- // Fire-and-forget — a broken trace shard must not block the boot — with failures
- // recorded like any background capture point. Idempotent and mtime-gated, so the
- // re-run after a hot swap costs only the gate checks.
- const errors = deps.errors;
- void deps.sessionService.adoptUnmanagedTraceSessions().catch((err: unknown) => {
- errors.record({ source: "process", err, code: "trace_adoption_failed" });
+ terminals = new TerminalManager(ctx.resources, { assets: () => null });
+ terminals.adopt(adoptable("TerminalModule") ? (context.terminals ?? []) : []);
+ tree = await bootModules(bareTree([...plugins.modules()]), {
+ ifaces: plugins.ifaces(ifaceTable as unknown as IfaceTable),
+ resources: ctx.resources,
+ parked: parkedModules(context),
});
- // Machines, in one sweep (service.ts start()): a push here is a push everywhere, so
- // this App booting hands the same build on to any machine still carrying a different
- // one — cheap when there is nothing to do, since which machines are behind is read
- // from the install records, not asked over the network — and then re-holds every
- // connection the record says was held, starting a remote server that is down on the
- // way and handing each its Model config as it connects. Fire-and-forget for the same
- // reason as the adoption sweep: a host that is slow to answer must not hold up the
- // App that serves everything else.
- void deps.machines.start().catch((err: unknown) => {
- errors.record({ source: "process", err, code: "machines_reconnect_failed" });
+ } else {
+ // THE MODULE TREE (see ../platform.ts): every business service, every route
+ // group and the terminal manager are modules wired by their manifests — checked as
+ // data before any create() runs, created in dependency order. Sandbox backends the
+ // plugin host registered enter the same tree as one contributing module.
+ tree = await bootModules(platformDef(caps, adoptable, [...plugins.modules()]), {
+ ifaces: plugins.ifaces(ifaceTable as unknown as IfaceTable),
+ resources: ctx.resources,
+ parked: parkedModules(context),
});
+ business = tree;
+ terminals = tree.api<TerminalManager>("TerminalModule", "terminals");
}
-
- // Ordinary code over this App's own auth (terminal/identity.ts): the same object the
- // business routes authenticate with. A bare kernel has none — terminals stay fail-closed.
- const identity = identityFrom(deps?.authService ?? null);
-
- // 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;
+ // Ordinary code over this App's own auth: the same object the business routes
+ // authenticate with. A bare kernel has none — terminals stay fail-closed.
+ const auth = business?.api<AuthService>("AuthService", "AuthService") ?? null;
+ const identity = identityFrom(auth);
+ const manager = business?.api<SessionManager>("SessionsModule", "manager") ?? null;
// The runtime's one mid-request need of the CURRENT App is a hook installed over a
// claimed capability — overwrite-only across swaps, so a dead generation's hook is
// replaced and never removed: "is this session busy" for the channel sweep.
- if (caps !== null && business !== null) {
- caps.channels.setActivityProbe((key) => business.manager.statusOf(key) !== "idle");
+ if (caps !== null && manager !== null) {
+ caps.channels.setActivityProbe((key) => manager.statusOf(key) !== "idle");
}
- // PARK — the App's complete resource inventory, split by fate. Everything stateful
- // this App creates is on one of these three lists; a new resource must pick its list
- // when it is added, or the swap leaks it.
+ // PARK — the App's resource inventory, split by fate:
//
// DELIVERED (survives the swap; the successor adopts it at load):
- // - pty sessions registry `terminal:*` + parked handle ids → terminals.adopt
+ // - pty sessions registry `terminal:*` + the terminal module's parked ids
// - machine tunnels ssh children + machines-connect.json (pid/port) → adopted by
// the successor's tunnelPortFor, which checks the pid is alive
- // - runtime singletons db / auth / channels / config / proxy / desktop —
- // runtime-owned, re-claimed by every App; not this App's to park
+ // - runtime singletons db / auth-state / channels / config / proxy / desktop —
+ // runtime-owned, re-claimed by every App
// SUSPENDED (stopped here; the successor rebuilds it fresh at load):
- // - scheduler stop() now; successor start() reconciles missed fires
- // - messaging bridge stop() closes the channel connections; successor start()
- // reconnects every enabled binding from the DB
- // - agent runs approvals → deny, drives → abort; a goal's GOAL.json reads
- // as aborted once its Session is idle (GET /goal)
- // - session environments dispose() after the drive settles — kills background
- // commands (dev servers etc.) that would otherwise run on
- // orphaned and invisible to the successor's fresh Session
- // - reap timers TerminalManager.quiesce runs them now (dead ptys only)
- // - machine connections stop() closes every ssh session this generation opened;
- // successor start() re-holds each the record says was held
+ // - scheduler, messaging bridge, machine connections their modules' dispose effects
+ // stop them; each successor's setup starts over from the record
+ // - agent runs approvals → deny, drives → abort (manager.shutdown below)
+ // - session environments dispose() after the drive settles
+ // - reap timers the terminal module's effect quiesces them
// DETACHED (the object survives, this App's grip on it does not):
// - pty exit listeners unsubscribed, so a dead generation never releases a
// registry id the successor owns
@@ -342,27 +324,23 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
// and the progress log is simply lost, which re-running recovers); and SSE subscriber
// closures (they serve the old generation's stream until the client reloads on
// web_updated — the channel hub itself is runtime-owned).
- // A build that adds a service with state of its own (sandbox settings, workflow
- // refs, ssh tunnels, an in-flight job) adds it to the right list here — the list is
- // the contract, not a description of today's services.
- //
- // The synchronous part runs here; the ASYNC part (waiting for aborted runs to
- // actually end) cannot — dispose is sync — so it is exposed as api.drained(), which
- // the KERNEL awaits between dispose and the successor's boot (kernel/upgrade.ts).
- // Nothing about the handover touches the registry.
+ // A module with state of its own (sandbox settings, workflow refs, ssh tunnels, an
+ // in-flight job) belongs in the right list here — the list is the contract, not a
+ // description of today's modules.
+ // The tree's dispose runs every module's effects in reverse creation order; the
+ // asynchronous tail (waiting for aborted runs to end) cannot run inside a sync
+ // effect, so it is exposed as api.drained(), which the KERNEL awaits between dispose
+ // and the successor's boot (kernel/upgrade.ts). Nothing about the handover touches
+ // the registry.
let drained: Promise<void> | undefined;
ctx.effect(() => {
- terminals.quiesce();
// Forwards to machines are DELIVERED, not suspended: the ssh children are separate
// processes that keep forwarding across the swap, and the successor adopts them by the
// pid recorded in web.db (machines/service.ts).
const drains: Promise<unknown>[] = [];
- if (business !== null) {
- business.scheduler.stop();
- business.messaging.stop();
- business.machines.stop();
- drains.push(business.manager.shutdown(DRAIN_GRACE_MS));
- }
+ if (manager !== null) drains.push(manager.shutdown(DRAIN_GRACE_MS));
+ tree.dispose();
+ if (business === null) terminals.quiesce();
drained = Promise.allSettled(drains).then(() => undefined);
});
@@ -373,22 +351,28 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
for (const group of doomedGroups) ctx.resources.disposeGroup?.(group);
ctx.resources.register(RESOURCE_IFACES_RESOURCE_ID, DECLARED_RESOURCES);
- const http = seamHttp(app);
+ const httpApi = business?.api<{ fetch(request: Request): Promise<Response> }>(
+ "HttpModule",
+ "http",
+ );
+ const http = httpApi !== undefined ? seamHttp(httpApi) : seamHttp(bareApp(terminals, identity));
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: () => {
- // The sandbox field is omitted while settings are the pristine default: a
- // default deployment keeps parking what it always did, compatible with any
- // bundle's schema; once confinement is configured, pushing a sandbox-ignorant
- // bundle blocks rather than silently un-confining.
- const parkedSandbox = sandbox.parkedSettings();
+ const modules = tree.park();
+ // The top-level fields are written for every platform that reads them: a bare
+ // kernel's own ptys, and the two parking modules' state in the form the first
+ // platforms parked it — so a rollback to any of them keeps terminals and confinement.
+ const terminalIds =
+ business === null
+ ? terminals.handleIds()
+ : (parkedSelf(modules, "TerminalModule")?.terminals as string[] | undefined);
+ const sandbox = parkedSelf(modules, "SandboxModule")?.settings;
return {
motd: context.motd,
- terminals: terminals.handleIds(),
- ...(parkedSandbox !== undefined ? { sandbox: parkedSandbox } : {}),
+ modules,
+ ...(terminalIds !== undefined ? { terminals: terminalIds } : {}),
+ ...(sandbox !== undefined ? { sandbox } : {}),
};
},
info: () => ({
@@ -404,13 +388,39 @@ export const platformImpl: Impl<PlatformApi, PlatformCtx> = {
// Process exit wants the manager's graceful ≤5s drain, which a synchronous dispose
// effect cannot await — exposed for index.ts's shutdown to call before disposing.
shutdown: async () => {
- if (business !== null) await business.manager.shutdown(DRAIN_GRACE_MS);
+ if (manager !== null) await manager.shutdown(DRAIN_GRACE_MS);
},
drained: () => drained,
};
},
};
+/** A bare kernel's tree: the sandbox floor and whatever contributes to it, nothing that needs a capability. */
+function bareTree(plugins: ModuleDef[]): ModuleDef {
+ return {
+ manifest: {
+ name: "platform",
+ requires: {},
+ provides: {},
+ contributes: {},
+ children: ["SandboxModule", "*"],
+ },
+ children: [
+ moduleDefOf(SandboxModule, { manifests: ifaceTable.modules as ManifestTable }),
+ ...plugins,
+ ],
+ create: () => ({ api: {} }),
+ };
+}
+
+/** The terminal-only surface of a declared bare kernel. */
+function bareApp(terminals: TerminalManager, identity: Identity): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+ app.notFound(() => declined());
+ app.route("/", terminalRoutes(terminals, identity));
+ return app;
+}
+
/**
* 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
diff --git a/packages/server/src/hmr/routes.ts b/packages/server/src/hmr/routes.ts
index 37c5042a..515f4de4 100644
--- a/packages/server/src/hmr/routes.ts
+++ b/packages/server/src/hmr/routes.ts
@@ -19,7 +19,18 @@
*/
import zlib from "node:zlib";
import { Hono } from "hono";
-import type { AppDeps } from "../app.js";
+import type { ServerConfig } from "../config.js";
+import type { AuthService } from "../auth/service.js";
+import type { HmrHost } from "./host.js";
+import type { ChannelHub } from "../runtime/channel.js";
+
+/** What the hot-update routes reach: runtime capabilities and the current App's auth. */
+export interface HmrRouteDeps {
+ hmr: HmrHost;
+ authService: AuthService;
+ config: ServerConfig;
+ channels: ChannelHub;
+}
import { authMiddleware } from "../auth/middleware.js";
import type { AppEnv } from "../auth/middleware.js";
import { HttpError } from "../http/errors.js";
@@ -27,7 +38,7 @@ import { HttpError } from "../http/errors.js";
/** Bind addresses considered safe by default; anything else needs HTTPS. */
const LOOPBACK_HOSTS = new Set(["127.0.0.1", "::1", "localhost"]);
-export function hmrRoutes(deps: AppDeps): Hono<AppEnv> {
+export function hmrRoutes(deps: HmrRouteDeps): Hono<AppEnv> {
const routes = new Hono<AppEnv>();
const hmr = deps.hmr;
// Mounted BEFORE the global cookie-auth middleware (see app.ts): this gate
diff --git a/packages/server/src/http/app.ts b/packages/server/src/http/app.ts
new file mode 100644
index 00000000..bbb42166
--- /dev/null
+++ b/packages/server/src/http/app.ts
@@ -0,0 +1,127 @@
+import { Interface, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";
+import type { Opaque, Slot, ClassCtx } from "@prismshadow/penguin-core/kernel";
+import { Hono } from "hono";
+import type { AppEnv } from "../auth/middleware.js";
+import { Config, Log, RuntimeModule } from "../hmr/capabilities.js";
+import type { MiddlewareHandler } from "hono";
+import { bodyLimit } from "hono/body-limit";
+import { authMiddleware, jsonOnlyWrites } from "../auth/middleware.js";
+import type { AuthService } from "../auth/service.js";
+import { HttpError, handleError } from "./errors.js";
+import { attributedProjectId } from "./attribution.js";
+import { bodyLimitBytes } from "../services/attachment-limits.js";
+import { declined } from "../hmr/hono-seam.js";
+import type { ErrorRecorder } from "../runtime/error-recorder.js";
+import type { ProjectAccess } from "../services/project-access.js";
+import type { ServerSettingsRepo } from "../db/repos/server-settings.js";
+
+/** The assembled business surface: one request in, one response (or a decline) out. */
+export abstract class Http extends Interface<{
+ fetch(request: Opaque<"Request", Request>): Promise<Opaque<"Response", Response>>;
+}>() {}
+
+export interface HttpSlots {
+ /**
+ * A route group. `auth: "user"` mounts it behind the cookie gate, `"none"` in front of
+ * it; `order` is the mount position (a stable number, since Hono matches in order). The
+ * code half is the group's Hono app.
+ */
+ routes: Slot<
+ { prefix: string; auth: "user" | "none"; order: number },
+ Opaque<"Hono", Hono<AppEnv>>
+ >;
+}
+
+/** Prefixes the runtime owns; the platform declines them before anything else runs — in particular before the auth gate, which would otherwise 401 an unauthenticated /api/auth/login. */
+const RUNTIME_PREFIXES = ["/api/auth", "/api/desktop", "/api/hmr"];
+
+/**
+ * The platform's whole HTTP surface, assembled from `HttpModule.routes` contributions: every
+ * module that serves requests contributes its groups here as data (prefix, auth, order)
+ * and binds the Hono app by id. Adding an endpoint is adding a line to a manifest.
+ */
+@Module()
+export class HttpModule {
+ @Use(RuntimeModule) private readonly config!: Config;
+ @Use(RuntimeModule) private readonly log!: Log;
+ @Use() private readonly auth!: AuthService;
+ @Use() private readonly errors!: ErrorRecorder;
+ @Use() private readonly settings!: ServerSettingsRepo;
+ @Use() private readonly access!: ProjectAccess;
+ @Provide() http!: Http;
+ setup({ contributions }: ClassCtx) {
+ const errors = this.errors;
+ const access = this.access;
+ const app = new Hono<AppEnv>();
+ app.onError((err, c) => {
+ const projectId = attributedProjectId(c, { access });
+ errors.record({
+ source: "http",
+ err,
+ ...(projectId !== undefined ? { ctx: { projectId } } : {}),
+ });
+ return handleError(err, c);
+ });
+ app.notFound(() => declined());
+ app.use("*", async (c, next) => {
+ const start = performance.now();
+ await next();
+ this.log.line(
+ `${c.req.method} ${c.req.path} ${c.res.status} ${Math.round(performance.now() - start)}ms`,
+ );
+ });
+ let capped: { size: number; mw: MiddlewareHandler } | null = null;
+ app.use("/api/*", (c, next) => {
+ const size = bodyLimitBytes(this.settings.getAttachmentLimitsMb());
+ if (capped === null || capped.size !== size) {
+ capped = {
+ size,
+ mw: bodyLimit({
+ maxSize: size,
+ 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);
+
+ const routes = [...(contributions.routes ?? [])]
+ .map((c) => ({
+ id: c.id,
+ prefix: c.data.prefix as string,
+ auth: c.data.auth as "user" | "none",
+ order: c.data.order as number,
+ app: c.code as Hono<AppEnv>,
+ }))
+ .sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));
+ let gated = false;
+ let declinedRuntime = false;
+ for (const r of routes) {
+ // The terminal group (order 0) sits before the runtime-prefix decline, so a matched
+ // terminal route ends the chain first; everything after it declines /api/auth etc.
+ if (!declinedRuntime && r.order > 0) {
+ app.use("*", async (c, next) => {
+ if (RUNTIME_PREFIXES.some((p) => c.req.path === p || c.req.path.startsWith(`${p}/`))) {
+ return declined();
+ }
+ await next();
+ });
+ declinedRuntime = true;
+ }
+ if (!gated && r.auth === "user") {
+ // Protected routes: cookie -> auth_session -> user.
+ app.use("/api/*", authMiddleware(this.auth, this.config.trustProxy));
+ gated = true;
+ }
+ app.route(r.prefix, r.app);
+ }
+ this.http = { fetch: (request: Request) => Promise.resolve(app.fetch(request)) };
+ }
+}
diff --git a/packages/server/src/http/attribution.ts b/packages/server/src/http/attribution.ts
index eccfc0fe..d0d7e755 100644
--- a/packages/server/src/http/attribution.ts
+++ b/packages/server/src/http/attribution.ts
@@ -4,7 +4,7 @@
* it without dragging the runtime shell into its graph.
*/
import type { Context } from "hono";
-import type { AppDeps } from "../app.js";
+import type { ProjectAccess } from "../services/project-access.js";
import type { AppEnv } from "../auth/middleware.js";
import type { UserRow } from "../db/repos/users.js";
@@ -30,13 +30,16 @@ import type { UserRow } from "../db/repos/users.js";
* - 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 {
+export function attributedProjectId(
+ c: Context<AppEnv>,
+ deps: { access: ProjectAccess },
+): 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;
+ return deps.access.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 8bfc512d..60797936 100644
--- a/packages/server/src/http/routes/admin-settings.ts
+++ b/packages/server/src/http/routes/admin-settings.ts
@@ -24,7 +24,14 @@ import type {
import { HttpError } from "../errors.js";
import type { AppEnv } from "../../auth/middleware.js";
import { optionalBoolean, readJson } from "../validate.js";
-import type { AppDeps } from "../../app.js";
+import type { ServerSettingsRepo } from "../../db/repos/server-settings.js";
+import type { ProxyControl } from "../../hmr/capabilities.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface AdminSettingsRouteDeps {
+ proxyControl: ProxyControl;
+ serverSettingsRepo: ServerSettingsRepo;
+}
import { applyProxySettings, normalizeProxyUrl } from "../../net/proxy.js";
import { MAX_ATTACHMENT_MB, MIN_ATTACHMENT_MB } from "../../services/attachment-limits.js";
import {
@@ -69,7 +76,7 @@ function parseAttachmentMb(value: unknown, field: string): number {
);
}
-export function adminSettingsRoutes(deps: AppDeps): Hono<AppEnv> {
+export function adminSettingsRoutes(deps: AdminSettingsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.use("*", async (c, next) => {
diff --git a/packages/server/src/http/routes/admin.ts b/packages/server/src/http/routes/admin.ts
index 522436f5..6eb096ac 100644
--- a/packages/server/src/http/routes/admin.ts
+++ b/packages/server/src/http/routes/admin.ts
@@ -7,11 +7,22 @@ import { Hono } from "hono";
import type { AdminUserCreateResponse, AdminUsersResponse } from "../../api/types.js";
import { HttpError } from "../errors.js";
import { rejectInDesktopMode } from "./desktop.js";
+import type { DesktopService } from "../../services/desktop-service.js";
import type { AppEnv } from "../../auth/middleware.js";
import { pathParam, readJson, requireString } from "../validate.js";
-import type { AppDeps } from "../../app.js";
+import type { AdminService } from "../../services/admin-service.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Desktop, Proxy } from "../../hmr/capabilities.js";
+import type { ServerSettingsRepo } from "../../db/repos/server-settings.js";
+import { adminSettingsRoutes } from "./admin-settings.js";
-export function adminUsersRoutes(deps: AppDeps): Hono<AppEnv> {
+/** What this route group reaches — bound by its module (src/modules). */
+export interface AdminRouteDeps {
+ desktop: DesktopService | null;
+ adminService: AdminService;
+}
+
+export function adminUsersRoutes(deps: AdminRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.use("*", rejectInDesktopMode(deps));
@@ -48,3 +59,40 @@ export function adminUsersRoutes(deps: AppDeps): Hono<AppEnv> {
return app;
}
+
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "admin-api.users",
+ prefix: "/api/admin/users",
+ auth: "user",
+ order: 30,
+ },
+ {
+ id: "admin-api.settings",
+ prefix: "/api/admin/settings",
+ auth: "user",
+ order: 40,
+ },
+ ],
+ },
+})
+export class AdminRoutes {
+ @Use() private readonly admin!: AdminService;
+ @Use() private readonly desktop!: Desktop;
+ @Use() private readonly proxy!: Proxy;
+ @Use() private readonly settings!: ServerSettingsRepo;
+ @Bind("admin-api.users") usersRoutes!: Hono<AppEnv>;
+ @Bind("admin-api.settings") settingsRoutes!: Hono<AppEnv>;
+ setup() {
+ this.usersRoutes = adminUsersRoutes({
+ adminService: this.admin,
+ desktop: this.desktop.current() as DesktopService | null,
+ });
+ this.settingsRoutes = adminSettingsRoutes({
+ proxyControl: (settings) => this.proxy.apply(settings),
+ serverSettingsRepo: this.settings,
+ });
+ }
+}
diff --git a/packages/server/src/http/routes/agent-config.ts b/packages/server/src/http/routes/agent-config.ts
index a1f0e35d..2e838a33 100644
--- a/packages/server/src/http/routes/agent-config.ts
+++ b/packages/server/src/http/routes/agent-config.ts
@@ -20,19 +20,28 @@ import type {
} from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
import { badRequest, optionalString, readJson, requireValidId } from "../validate.js";
-import type { AppDeps } from "../../app.js";
+import type { SessionManager } from "../../runtime/session-manager.js";
+import type { AgentConfigService } from "../../services/agent-config-service.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface AgentConfigRouteDeps {
+ agentConfigService: AgentConfigService;
+ manager: SessionManager;
+ access: ProjectAccess;
+}
/** Ceiling on a single mcp-test probe's connect budget (an entry may configure minutes). */
const MCP_TEST_TIMEOUT_CAP_MS = 30_000;
-export function agentConfigRoutes(deps: AppDeps): Hono<AppEnv> {
+export function agentConfigRoutes(deps: AgentConfigRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
// Id validation happens before any path construction: prevents agentId path traversal for cross-Project privilege escalation.
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const view = await deps.agentConfigService.getConfig(projectId, agentId);
return c.json({
...view,
@@ -43,7 +52,7 @@ export function agentConfigRoutes(deps: AppDeps): Hono<AppEnv> {
app.put("/", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const body = await readJson(c);
const req: AgentConfigUpdateRequest = {};
const agentsMd = optionalString(body, "agentsMd", { label: "agentsMd" });
@@ -78,7 +87,7 @@ export function agentConfigRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/mcp-test", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const body = await readJson(c);
if (typeof body.name !== "string" || body.name.length === 0) {
throw badRequest("name must be a non-empty string.");
@@ -142,7 +151,7 @@ export function agentConfigRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/kernel-update", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const result = await deps.agentConfigService.kernelUpdate(projectId, agentId);
return c.json(result satisfies AgentKernelUpdateResponse);
});
@@ -153,7 +162,7 @@ export function agentConfigRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/reset", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
await deps.agentConfigService.resetConfig(projectId, agentId);
// The defaults carry no `hooks` section, so a reset can switch hooks back on; cached
// runtimes hold the set they were built with (see the PUT above).
diff --git a/packages/server/src/http/routes/agent-traces.ts b/packages/server/src/http/routes/agent-traces.ts
index f8632232..d8bfe115 100644
--- a/packages/server/src/http/routes/agent-traces.ts
+++ b/packages/server/src/http/routes/agent-traces.ts
@@ -33,7 +33,16 @@ import {
requireString,
requireValidId,
} from "../validate.js";
-import type { AppDeps } from "../../app.js";
+import type { AgentConfigService } from "../../services/agent-config-service.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+import type { TraceService } from "../../services/trace-service.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface AgentTracesRouteDeps {
+ agentConfigService: AgentConfigService;
+ access: ProjectAccess;
+ traceService: TraceService;
+}
/** Import file size cap: aligned with the snapshot import (stays within the 20MB body limit after base64). */
const MAX_TRACE_BYTES = 14 * 1024 * 1024;
@@ -47,14 +56,14 @@ const SESSION_CATEGORIES: readonly SessionCategory[] = [
"archived",
];
-export function agentTracesRoutes(deps: AppDeps): Hono<AppEnv> {
+export function agentTracesRoutes(deps: AgentTracesRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
// Id validation happens before any path construction: prevents agentId path traversal for cross-Project privilege escalation.
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
// Both params absent -> null -> the legacy full response, byte-for-byte as before.
const paging = optionalPagingQuery(c);
// Optional category filter (paging then applies within the category): only meaningful
@@ -79,7 +88,7 @@ export function agentTracesRoutes(deps: AppDeps): Hono<AppEnv> {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
const sessionId = requireValidId(c, "sessionId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const index = positiveIntParam(c, "index");
const { offset, limit } = paginationQuery(c);
return c.json(
@@ -91,7 +100,7 @@ export function agentTracesRoutes(deps: AppDeps): Hono<AppEnv> {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
const sessionId = requireValidId(c, "sessionId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const index = positiveIntParam(c, "index");
return c.json(await deps.traceService.analyze(projectId, agentId, sessionId, index));
});
@@ -102,7 +111,7 @@ export function agentTracesRoutes(deps: AppDeps): Hono<AppEnv> {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
const sessionId = requireValidId(c, "sessionId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const index = positiveIntParam(c, "index");
const bytes = await deps.traceService.readFileRaw(projectId, agentId, sessionId, index);
const fileName = `${sessionId}_${String(index).padStart(3, "0")}.jsonl`;
@@ -121,7 +130,7 @@ export function agentTracesRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/import", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
await deps.agentConfigService.requireExists(projectId, agentId);
const body = await readJson(c);
const dataBase64 = requireString(body, "dataBase64", { minLen: 1, maxLen: 20 * 1024 * 1024 });
diff --git a/packages/server/src/http/routes/agent-transfer.ts b/packages/server/src/http/routes/agent-transfer.ts
index 767811b8..e51d728f 100644
--- a/packages/server/src/http/routes/agent-transfer.ts
+++ b/packages/server/src/http/routes/agent-transfer.ts
@@ -7,7 +7,16 @@ import fs from "node:fs/promises";
import { Hono } from "hono";
import type { AgentImportResponse } from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
-import type { AppDeps } from "../../app.js";
+import type { AgentConfigService } from "../../services/agent-config-service.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+import type { SnapshotService } from "../../services/snapshot-service.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface AgentTransferRouteDeps {
+ agentConfigService: AgentConfigService;
+ access: ProjectAccess;
+ snapshots: SnapshotService;
+}
import { badRequest, readJson, requireString, requireValidId } from "../validate.js";
/** Import archive size cap: aligned with the global request body limit (stays within 20MB after base64). */
@@ -31,13 +40,13 @@ export function readArchiveBase64(body: Record<string, unknown>): Buffer {
return archive;
}
-export function agentTransferRoutes(deps: AppDeps): Hono<AppEnv> {
+export function agentTransferRoutes(deps: AgentTransferRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/export", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const { file, fileName } = await deps.snapshots.exportArchive(projectId, agentId);
const bytes = await fs.readFile(file);
return new Response(new Uint8Array(bytes), {
@@ -51,7 +60,7 @@ export function agentTransferRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/import", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
await deps.agentConfigService.requireExists(projectId, agentId);
const body = await readJson(c);
const archive = readArchiveBase64(body);
diff --git a/packages/server/src/http/routes/agents.ts b/packages/server/src/http/routes/agents.ts
index 632f4fd4..652afca8 100644
--- a/packages/server/src/http/routes/agents.ts
+++ b/packages/server/src/http/routes/agents.ts
@@ -18,18 +18,39 @@ import {
requireValidId,
} from "../validate.js";
import { readArchiveBase64 } from "./agent-transfer.js";
-import type { AppDeps } from "../../app.js";
+import type { ErrorsRepo } from "../../db/repos/errors.js";
+import type { SchedulesRepo } from "../../db/repos/schedules.js";
+import type { SessionsRepo } from "../../db/repos/sessions.js";
+import type { SessionManager } from "../../runtime/session-manager.js";
+import type { AgentConfigService } from "../../services/agent-config-service.js";
+import type { AgentService } from "../../services/agent-service.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+import type { SessionService } from "../../services/session-service.js";
+import type { TraceIndexService } from "../../services/trace-index.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface AgentsRouteDeps {
+ agentConfigService: AgentConfigService;
+ agentService: AgentService;
+ errorsRepo: ErrorsRepo;
+ manager: SessionManager;
+ access: ProjectAccess;
+ schedulesRepo: SchedulesRepo;
+ sessionService: SessionService;
+ sessionsRepo: SessionsRepo;
+ traceIndex: TraceIndexService;
+}
/** Window size in days for the card's activity sparkline (last 30 days, including today). */
const ACTIVITY_DAYS = 30;
-export function agentsRoutes(deps: AppDeps): Hono<AppEnv> {
+export function agentsRoutes(deps: AgentsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
// Defensive id validation: don't rely on the implicit invariant that requireProjectAccess always runs before path construction.
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const items = await deps.agentService.listAgents(projectId);
const agents: AgentSummary[] = await Promise.all(
items.map(async (item) => {
@@ -51,7 +72,7 @@ export function agentsRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const body = await readJson(c);
const agentId = requireString(body, "agentId", { label: "agentId" });
const name = optionalString(body, "name", { minLen: 1, maxLen: 100, label: "name" });
@@ -105,7 +126,7 @@ export function agentsRoutes(deps: AppDeps): Hono<AppEnv> {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
// Deletion is a Project-level management operation: owner only.
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
await deps.agentConfigService.requireExists(projectId, agentId);
// Mark as deleting and converge active runs (beginAgentDeletion): any new Task during
// this window gets 409, preventing the race where a new task recreates the directory
diff --git a/packages/server/src/http/routes/auth.ts b/packages/server/src/http/routes/auth.ts
index 121e4b36..078f176c 100644
--- a/packages/server/src/http/routes/auth.ts
+++ b/packages/server/src/http/routes/auth.ts
@@ -12,9 +12,18 @@ import type { AuthResponse } from "../../api/types.js";
import { SESSION_COOKIE, cookieOptions } from "../../auth/middleware.js";
import type { AppEnv } from "../../auth/middleware.js";
import { readJson, requireString } from "../validate.js";
-import type { AppDeps } from "../../app.js";
+import type { AuthService } from "../../auth/service.js";
+import type { ServerConfig } from "../../config.js";
+import type { DesktopService } from "../../services/desktop-service.js";
-export function authRoutes(deps: AppDeps): Hono<AppEnv> {
+/** What this route group reaches — bound by its module (src/modules). */
+export interface AuthRouteDeps {
+ authService: AuthService;
+ config: ServerConfig;
+ desktop: DesktopService | null;
+}
+
+export function authRoutes(deps: AuthRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.post("/login", async (c) => {
diff --git a/packages/server/src/http/routes/benchmarks.ts b/packages/server/src/http/routes/benchmarks.ts
index 302a2095..d6198baf 100644
--- a/packages/server/src/http/routes/benchmarks.ts
+++ b/packages/server/src/http/routes/benchmarks.ts
@@ -15,9 +15,9 @@
import { Hono, type Context } from "hono";
import { isValidId } from "@prismshadow/penguin-core";
import type { AppEnv } from "../../auth/middleware.js";
-import type { AppDeps } from "../../app.js";
import type { BenchmarkCreateResponse, CaseMaterial } from "../../api/types.js";
-import type { BenchmarkCaseInput } from "../../services/benchmark-service.js";
+import type { BenchmarkCaseInput, BenchmarkService } from "../../services/benchmark-service.js";
+import type { ProjectAccess } from "../../services/project-access.js";
import {
badRequest,
optionalNumber,
@@ -27,6 +27,12 @@ import {
requireValidId,
} from "../validate.js";
+/** What this route group reaches — bound by its module (src/modules). */
+export interface BenchmarksRouteDeps {
+ benchmarks: BenchmarkService;
+ access: ProjectAccess;
+}
+
const TEXT_PREVIEW_BYTES = 256 * 1024;
/** Case directories carry the `CASE-` prefix the reader lists by; the rest is the shared id alphabet. */
@@ -78,12 +84,12 @@ function requireCases(body: Record<string, unknown>): BenchmarkCaseInput[] {
});
}
-function listCaseFiles(deps: AppDeps, material: CaseMaterial) {
+function listCaseFiles(deps: BenchmarksRouteDeps, material: CaseMaterial) {
return async (c: Context<AppEnv>) => {
const projectId = requireValidId(c, "projectId");
const benchmarkId = requireValidId(c, "benchmarkId");
const caseId = requireValidId(c, "caseId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
return c.json(
await deps.benchmarks.listCaseFiles(
projectId,
@@ -96,12 +102,12 @@ function listCaseFiles(deps: AppDeps, material: CaseMaterial) {
};
}
-function readCaseFile(deps: AppDeps, material: CaseMaterial) {
+function readCaseFile(deps: BenchmarksRouteDeps, material: CaseMaterial) {
return async (c: Context<AppEnv>) => {
const projectId = requireValidId(c, "projectId");
const benchmarkId = requireValidId(c, "benchmarkId");
const caseId = requireValidId(c, "caseId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const download = c.req.query("download") === "1";
const boundedPreview = !download && c.req.query("preview") === "1";
const { data, fileName, contentType, scriptable, truncated } =
@@ -130,12 +136,12 @@ function readCaseFile(deps: AppDeps, material: CaseMaterial) {
};
}
-export function benchmarksRoutes(deps: AppDeps): Hono<AppEnv> {
+export function benchmarksRoutes(deps: BenchmarksRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
return c.json(await deps.benchmarks.list(projectId));
});
@@ -143,7 +149,7 @@ export function benchmarksRoutes(deps: AppDeps): Hono<AppEnv> {
const projectId = requireValidId(c, "projectId");
// Writing into the Project's benchmarks directory is Project management: owner only, like
// schedules and imports.
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const body = await readJson(c);
const id = requireString(body, "id", { minLen: 1, maxLen: 100 });
if (!isValidId(id)) throw badRequest('id may only contain letters, digits, "_" and "-".');
@@ -167,7 +173,7 @@ export function benchmarksRoutes(deps: AppDeps): Hono<AppEnv> {
app.delete("/:benchmarkId", async (c) => {
const projectId = requireValidId(c, "projectId");
const benchmarkId = requireValidId(c, "benchmarkId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
await deps.benchmarks.remove(projectId, benchmarkId);
return c.body(null, 204);
});
@@ -175,7 +181,7 @@ export function benchmarksRoutes(deps: AppDeps): Hono<AppEnv> {
app.get("/:benchmarkId/cases", async (c) => {
const projectId = requireValidId(c, "projectId");
const benchmarkId = requireValidId(c, "benchmarkId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
return c.json(await deps.benchmarks.listCases(projectId, benchmarkId));
});
diff --git a/packages/server/src/http/routes/chat-defaults.ts b/packages/server/src/http/routes/chat-defaults.ts
index 67771556..63ef0977 100644
--- a/packages/server/src/http/routes/chat-defaults.ts
+++ b/packages/server/src/http/routes/chat-defaults.ts
@@ -12,21 +12,30 @@ import type { AppEnv } from "../../auth/middleware.js";
import { HttpError } from "../errors.js";
import { optionalEnum, optionalString, readJson, requireValidId } from "../validate.js";
import { APPROVAL_MODES } from "./sessions.js";
-import type { AppDeps } from "../../app.js";
+import type { AgentConfigService } from "../../services/agent-config-service.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+import type { ProjectConfigService } from "../../services/project-config-service.js";
-export function chatDefaultsRoutes(deps: AppDeps): Hono<AppEnv> {
+/** What this route group reaches — bound by its module (src/modules). */
+export interface ChatDefaultsRouteDeps {
+ agentConfigService: AgentConfigService;
+ projectConfigService: ProjectConfigService;
+ access: ProjectAccess;
+}
+
+export function chatDefaultsRoutes(deps: ChatDefaultsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
// Defensive id validation.
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
return c.json(await deps.projectConfigService.getChatDefaults(projectId));
});
app.put("/", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const body = await readJson(c);
const req: ChatDefaultsDto = {};
diff --git a/packages/server/src/http/routes/command-policy.ts b/packages/server/src/http/routes/command-policy.ts
index 463896ea..fd862d5b 100644
--- a/packages/server/src/http/routes/command-policy.ts
+++ b/packages/server/src/http/routes/command-policy.ts
@@ -11,7 +11,14 @@ import { Hono } from "hono";
import type { AppEnv } from "../../auth/middleware.js";
import { HttpError } from "../errors.js";
import { readJson, requireValidId } from "../validate.js";
-import type { AppDeps } from "../../app.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+import type { ProjectConfigService } from "../../services/project-config-service.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface CommandPolicyRouteDeps {
+ projectConfigService: ProjectConfigService;
+ access: ProjectAccess;
+}
/** Bounds for the rule list: enough for a serious deny list, small enough to stay a config file. */
const MAX_RULES = 64;
@@ -93,18 +100,18 @@ function validateRules(value: unknown): RuleInput[] {
return rules;
}
-export function commandPolicyRoutes(deps: AppDeps): Hono<AppEnv> {
+export function commandPolicyRoutes(deps: CommandPolicyRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
return c.json(await deps.projectConfigService.getCommandPolicy(projectId));
});
app.put("/", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const body = await readJson(c);
if (body.enabled !== undefined && typeof body.enabled !== "boolean") {
diff --git a/packages/server/src/http/routes/contributions.ts b/packages/server/src/http/routes/contributions.ts
new file mode 100644
index 00000000..66405dd2
--- /dev/null
+++ b/packages/server/src/http/routes/contributions.ts
@@ -0,0 +1,73 @@
+/**
+ * GET /api/contributions — the web slots' contributions, as data. What a pushed platform
+ * or an installed plugin adds to the web app arrives here; the app merges it with its
+ * own module.json and renders what it has a renderer for.
+ */
+import { Hono } from "hono";
+import type { AppEnv } from "../../auth/middleware.js";
+import { Interface, Bind, Module, Provide } from "@prismshadow/penguin-core/kernel";
+import type { ContributionsResponse, RendererRef, WebContribution } from "../../api/types.js";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
+
+export interface ContributionsRouteDeps {
+ web: WebShell;
+}
+
+export function contributionsRoutes(deps: ContributionsRouteDeps): Hono<AppEnv> {
+ const routes = new Hono<AppEnv>();
+ routes.get("/", (c) => c.json(deps.web.contributions()));
+ return routes;
+}
+
+/**
+ * The frontend's slots, declared on the SERVER so a server module (or a plugin) can
+ * contribute a page, an Agent settings tab or a Session tab as manifest data. The web
+ * app reads them back through GET /api/contributions and renders the ones whose
+ * renderer it knows: a `builtin` name from its own registry, or an `iframe`. No code
+ * crosses this boundary — only data.
+ */
+
+export abstract class WebShell extends Interface<{
+ /** Every contribution to the web slots, by slot, in module order. */
+ contributions(): ContributionsResponse;
+}>() {}
+
+export interface WebShellSlots {
+ /** A page: its route, whether it sits in the main nav, whether it is admin-only. */
+ pages: { key: string; path: string; nav: "main" | "none"; admin: boolean; renderer: RendererRef };
+ /** A tab on the Agent settings page. */
+ agentTabs: { key: string; order: number; renderer: RendererRef };
+ /** A tab beside a Session's chat (a workflow UI lives here). */
+ sessionTabs: { key: string; renderer: RendererRef };
+}
+
+@Module({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "web.contributions",
+ prefix: "/api/contributions",
+ auth: "user",
+ order: 65,
+ },
+ ],
+ },
+})
+export class WebModule {
+ @Provide() web!: WebShell;
+ @Bind("web.contributions") contributionsRoutes!: Hono<AppEnv>;
+ setup({ contributions }: ClassCtx) {
+ const collect = (slot: string): WebContribution[] =>
+ (contributions[slot] ?? []).map(
+ (c) => ({ id: c.id, from: c.from, ...c.data }) as WebContribution,
+ );
+ const response: ContributionsResponse = {
+ pages: collect("pages"),
+ agentTabs: collect("agentTabs"),
+ sessionTabs: collect("sessionTabs"),
+ };
+ const web: WebShell = { contributions: () => response };
+ this.web = web;
+ this.contributionsRoutes = contributionsRoutes({ web });
+ }
+}
diff --git a/packages/server/src/http/routes/desktop.ts b/packages/server/src/http/routes/desktop.ts
index 93e0db4a..3326ec00 100644
--- a/packages/server/src/http/routes/desktop.ts
+++ b/packages/server/src/http/routes/desktop.ts
@@ -19,7 +19,11 @@ import type {
} from "../../api/types.js";
import { HttpError } from "../errors.js";
import type { AppEnv } from "../../auth/middleware.js";
-import type { AppDeps } from "../../app.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface DesktopRouteDeps {
+ desktop: DesktopService | null;
+}
import type { DesktopService } from "../../services/desktop-service.js";
/**
@@ -29,7 +33,7 @@ import type { DesktopService } from "../../services/desktop-service.js";
* users and memberships in the data root are untouched; only the management routes are
* closed while the server runs under the desktop shell.
*/
-export function rejectInDesktopMode(deps: AppDeps): MiddlewareHandler {
+export function rejectInDesktopMode(deps: DesktopRouteDeps): MiddlewareHandler {
return async (_c, next) => {
if (deps.desktop !== null) {
throw new HttpError(
@@ -45,7 +49,7 @@ export function rejectInDesktopMode(deps: AppDeps): MiddlewareHandler {
/** Delay between answering 202 and starting shutdown: lets the response flush. */
const SHUTDOWN_DELAY_MS = 50;
-export function desktopRoutes(deps: AppDeps): Hono {
+export function desktopRoutes(deps: DesktopRouteDeps): Hono {
const app = new Hono();
app.post("/shutdown", (c) => {
@@ -70,7 +74,11 @@ export function desktopRoutes(deps: AppDeps): Hono {
* desktop-mode server must not read the machine's updater state, restart its GUI app, or
* reach into the chrome of a window it is not looking at.
*/
-function shellSessionOf(deps: AppDeps, c: Context<AppEnv>, refusal: string): DesktopService {
+function shellSessionOf(
+ deps: DesktopRouteDeps,
+ c: Context<AppEnv>,
+ refusal: string,
+): DesktopService {
const desktop = deps.desktop;
if (!desktop) throw new HttpError(404, "not_found", "Desktop mode is not enabled.");
if (c.var.sessionVia !== "desktop") throw new HttpError(403, "desktop_shell_only", refusal);
@@ -86,7 +94,7 @@ function shellSessionOf(deps: AppDeps, c: Context<AppEnv>, refusal: string): Des
* fetches only the release the shell has offered, and `install` restarts only into what
* its updater already downloaded and verified.
*/
-export function desktopUpdateRoutes(deps: AppDeps): Hono<AppEnv> {
+export function desktopUpdateRoutes(deps: DesktopRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
const requireShellSession = (c: Context<AppEnv>): DesktopService =>
@@ -131,7 +139,7 @@ export function desktopUpdateRoutes(deps: AppDeps): Hono<AppEnv> {
* page's UI language, or both; the shell applies it, persists it and pushes the new state
* straight back, so the answer here is an acknowledgement and the GET is what tells the truth.
*/
-export function desktopTrayRoutes(deps: AppDeps): Hono<AppEnv> {
+export function desktopTrayRoutes(deps: DesktopRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
const refusal = "The tray icon is managed from the desktop app's own window.";
diff --git a/packages/server/src/http/routes/directory-skills.ts b/packages/server/src/http/routes/directory-skills.ts
index a24bde25..9d44679a 100644
--- a/packages/server/src/http/routes/directory-skills.ts
+++ b/packages/server/src/http/routes/directory-skills.ts
@@ -17,16 +17,21 @@ import { Hono } from "hono";
import type { DirectorySkillsResponse } from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
import { requireProjectDir, requireValidId } from "../validate.js";
-import type { AppDeps } from "../../app.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface DirectorySkillsRouteDeps {
+ access: ProjectAccess;
+}
import { discoverDirectorySkills } from "../../services/directory-skills.js";
import { toSkillItem } from "../../services/plugin-library.js";
-export function directorySkillsRoutes(deps: AppDeps): Hono<AppEnv> {
+export function directorySkillsRoutes(deps: DirectorySkillsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const real = await requireProjectDir(c.req.query("path"));
diff --git a/packages/server/src/http/routes/dirs.ts b/packages/server/src/http/routes/dirs.ts
index d7a89b63..5948f49e 100644
--- a/packages/server/src/http/routes/dirs.ts
+++ b/packages/server/src/http/routes/dirs.ts
@@ -17,14 +17,21 @@ import { Hono } from "hono";
import type { DirListResponse } from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
import { requireProjectDir, requireValidId } from "../validate.js";
-import type { AppDeps } from "../../app.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import { directorySkillsRoutes } from "./directory-skills.js";
-export function dirsRoutes(deps: AppDeps): Hono<AppEnv> {
+/** What this route group reaches — bound by its module (src/modules). */
+export interface DirsRouteDeps {
+ access: ProjectAccess;
+}
+
+export function dirsRoutes(deps: DirsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
// Default starting point: home directory; an explicit path must be absolute (the frontend always sends back the realpath result).
const raw = c.req.query("path");
@@ -52,3 +59,32 @@ export function dirsRoutes(deps: AppDeps): Hono<AppEnv> {
return app;
}
+
+/** The Project-scoped directory routes; the repos and the access check are components of their own. */
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "projects.dirs",
+ prefix: "/api/projects/:projectId/dirs",
+ auth: "user",
+ order: 150,
+ },
+ {
+ id: "projects.dir-skills",
+ prefix: "/api/projects/:projectId/dir-skills",
+ auth: "user",
+ order: 160,
+ },
+ ],
+ },
+})
+export class ProjectsRoutes {
+ @Use() private readonly access!: ProjectAccess;
+ @Bind("projects.dirs") dirsRoutes!: Hono<AppEnv>;
+ @Bind("projects.dir-skills") dirSkillsRoutes!: Hono<AppEnv>;
+ setup() {
+ this.dirsRoutes = dirsRoutes({ access: this.access });
+ this.dirSkillsRoutes = directorySkillsRoutes({ access: this.access });
+ }
+}
diff --git a/packages/server/src/http/routes/events.ts b/packages/server/src/http/routes/events.ts
index 7084d7c6..44d9820d 100644
--- a/packages/server/src/http/routes/events.ts
+++ b/packages/server/src/http/routes/events.ts
@@ -5,14 +5,22 @@
import { Hono } from "hono";
import type { AppEnv } from "../../auth/middleware.js";
import { sseEndpoint } from "../sse.js";
-import type { AppDeps } from "../../app.js";
+import type { ChannelHub } from "../../runtime/channel.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
+import { Channels, RuntimeModule } from "../../hmr/capabilities.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface EventsRouteDeps {
+ channels: ChannelHub;
+}
/** The user channel's key in ChannelHub. */
export function userChannelKey(userId: string): string {
return `user:${userId}`;
}
-export function eventsRoutes(deps: AppDeps): Hono<AppEnv> {
+export function eventsRoutes(deps: EventsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", (c) => {
@@ -22,3 +30,23 @@ export function eventsRoutes(deps: AppDeps): Hono<AppEnv> {
return app;
}
+
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "EventsRoutes.routes",
+ prefix: "/api/events",
+ auth: "user",
+ order: 60,
+ },
+ ],
+ },
+})
+export class EventsRoutes {
+ @Use(RuntimeModule) private readonly channels!: Channels;
+ @Bind("EventsRoutes.routes") routes!: Hono<AppEnv>;
+ setup() {
+ this.routes = eventsRoutes({ channels: this.channels as ChannelHub });
+ }
+}
diff --git a/packages/server/src/http/routes/hooks.ts b/packages/server/src/http/routes/hooks.ts
index f88ef3f2..6945f5c0 100644
--- a/packages/server/src/http/routes/hooks.ts
+++ b/packages/server/src/http/routes/hooks.ts
@@ -30,7 +30,7 @@ import {
import type { HookCommand, HookManifest } from "@prismshadow/penguin-core";
import type { AgentHooksResponse, HookItem } from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
-import type { AppDeps } from "../../app.js";
+import type { PluginsRouteDeps } from "./plugins.js";
import { HttpError } from "../errors.js";
import { badRequest, readJson, requireString, requireValidId } from "../validate.js";
import { toHookItem } from "../../services/plugin-library.js";
@@ -249,7 +249,7 @@ async function collectHookArchive(dir: string, name: string): Promise<Record<str
}
/** /api/projects/:p/agents/:a/hooks: read, import/export and uninstall are all Project-member operations. */
-export function agentHooksRoutes(deps: AppDeps): Hono<AppEnv> {
+export function agentHooksRoutes(deps: PluginsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
const installedItems = async (projectId: string, agentId: string): Promise<HookItem[]> =>
@@ -274,7 +274,7 @@ export function agentHooksRoutes(deps: AppDeps): Hono<AppEnv> {
// Defensive id validation happens before any path construction: prevents path traversal for cross-Project privilege escalation.
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
await deps.agentConfigService.requireExists(projectId, agentId);
return c.json({ hooks: await installedItems(projectId, agentId) } satisfies AgentHooksResponse);
});
@@ -283,7 +283,7 @@ export function agentHooksRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/archive", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
await deps.agentConfigService.requireExists(projectId, agentId);
const body = await readJson(c);
const dataBase64 = requireString(body, "dataBase64", { minLen: 1, maxLen: 20 * 1024 * 1024 });
@@ -327,7 +327,7 @@ export function agentHooksRoutes(deps: AppDeps): Hono<AppEnv> {
app.get("/:name/archive", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const name = requireValidId(c, "name");
const dir = await requireInstalled(projectId, agentId, name);
const archiveFiles = await collectHookArchive(dir, name);
@@ -359,7 +359,7 @@ export function agentHooksRoutes(deps: AppDeps): Hono<AppEnv> {
app.delete("/:name", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const name = requireValidId(c, "name");
await requireInstalled(projectId, agentId, name);
await removeHook(deps.config.root, projectId, agentId, name);
diff --git a/packages/server/src/http/routes/install.ts b/packages/server/src/http/routes/install.ts
index 74223d8d..69daa331 100644
--- a/packages/server/src/http/routes/install.ts
+++ b/packages/server/src/http/routes/install.ts
@@ -22,10 +22,18 @@
import { Hono } from "hono";
import type { InstallResponse } from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
-import type { AppDeps } from "../../app.js";
+import type { ServerConfig } from "../../config.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface InstallRouteDeps {
+ config: ServerConfig;
+}
import { ensureInstallId } from "../../install-id.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
+import { Config, RuntimeModule } from "../../hmr/capabilities.js";
-export function installRoutes(deps: AppDeps): Hono<AppEnv> {
+export function installRoutes(deps: InstallRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", (c) => {
@@ -34,3 +42,28 @@ export function installRoutes(deps: AppDeps): Hono<AppEnv> {
return app;
}
+
+/**
+ * The data root's install identity, public (auth: none): the web app compares it against
+ * localStorage before React mounts, before anyone is signed in. Mounted in the PLATFORM
+ * because a push carries platform + web dist together, so the route and its caller move as one.
+ */
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "InstallRoutes.routes",
+ prefix: "/api/install",
+ auth: "none",
+ order: 5,
+ },
+ ],
+ },
+})
+export class InstallRoutes {
+ @Use(RuntimeModule) private readonly config!: Config;
+ @Bind("InstallRoutes.routes") routes!: Hono<AppEnv>;
+ setup() {
+ this.routes = installRoutes({ config: this.config });
+ }
+}
diff --git a/packages/server/src/http/routes/machines.ts b/packages/server/src/http/routes/machines.ts
index 7661f221..8c9b627f 100644
--- a/packages/server/src/http/routes/machines.ts
+++ b/packages/server/src/http/routes/machines.ts
@@ -29,9 +29,16 @@ import type { DirListResponse, MachinesResponse } from "../../api/types.js";
import { HttpError } from "../errors.js";
import { requireValidId } from "../validate.js";
import type { AppEnv } from "../../auth/middleware.js";
-import type { AppDeps } from "../../app.js";
+import type { MachinesService } from "../../machines/service.js";
+import type { ProjectAccess } from "../../services/project-access.js";
-export function machinesRoutes(deps: AppDeps): Hono<AppEnv> {
+/** What this route group reaches — bound by its module (src/modules). */
+export interface MachinesRouteDeps {
+ machines: MachinesService;
+ access: ProjectAccess;
+}
+
+export function machinesRoutes(deps: MachinesRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
// Admin AND a member of the Project: the Project scope says WHICH machines are answered,
@@ -41,7 +48,7 @@ export function machinesRoutes(deps: AppDeps): Hono<AppEnv> {
if (!c.var.user.isAdmin) {
throw new HttpError(403, "admin_required", "Only an admin can install on a machine.");
}
- deps.projectService.requireProjectAccess(c.var.user.userId, requireValidId(c, "projectId"));
+ deps.access.requireProjectAccess(c.var.user.userId, requireValidId(c, "projectId"));
await next();
});
diff --git a/packages/server/src/http/routes/me.ts b/packages/server/src/http/routes/me.ts
index eb9404e0..6b6323df 100644
--- a/packages/server/src/http/routes/me.ts
+++ b/packages/server/src/http/routes/me.ts
@@ -25,7 +25,23 @@ import { SESSION_COOKIE, cookieOptions } from "../../auth/middleware.js";
import type { AppEnv } from "../../auth/middleware.js";
import { badRequest, readJson, requireString } from "../validate.js";
import { HttpError } from "../errors.js";
-import type { AppDeps } from "../../app.js";
+import type { AuthService } from "../../auth/service.js";
+import type { ServerConfig } from "../../config.js";
+import type { ServerSettingsRepo } from "../../db/repos/server-settings.js";
+import type { UiPrefsRepo } from "../../db/repos/ui-prefs.js";
+import type { UsersRepo } from "../../db/repos/users.js";
+import type { DesktopService } from "../../services/desktop-service.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface MeRouteDeps {
+ authService: AuthService;
+ config: ServerConfig;
+ desktop: DesktopService | null;
+ prefsRepo: UiPrefsRepo;
+ serverSettingsRepo: ServerSettingsRepo;
+ /** The `users` table itself, for the one route that writes a column no service owns (PUT /api/me/profile). */
+ usersRepo: UsersRepo;
+}
import { resolvePreviewTarget } from "../../services/preview-token.js";
import { validateDraftShortcuts } from "../../services/draft-shortcuts.js";
import {
@@ -34,6 +50,9 @@ import {
MAX_ATTACHMENT_MB,
MIN_ATTACHMENT_MB,
} from "../../services/attachment-limits.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
+import { Config, Desktop, RuntimeModule } from "../../hmr/capabilities.js";
/** Nickname bounds, counted in user-perceived code points so a CJK name is 32 characters, not 96. */
const DISPLAY_NAME_MIN = 1;
@@ -99,7 +118,7 @@ function parseAvatar(raw: unknown): string | null {
return raw;
}
-export function meRoutes(deps: AppDeps): Hono<AppEnv> {
+export function meRoutes(deps: MeRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", (c) => {
@@ -232,3 +251,35 @@ export function meRoutes(deps: AppDeps): Hono<AppEnv> {
return app;
}
+
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "MeRoutes.routes",
+ prefix: "/api/me",
+ auth: "user",
+ order: 10,
+ },
+ ],
+ },
+})
+export class MeRoutes {
+ @Use(RuntimeModule) private readonly config!: Config;
+ @Use(RuntimeModule) private readonly desktop!: Desktop;
+ @Use() private readonly auth!: AuthService;
+ @Use() private readonly prefs!: UiPrefsRepo;
+ @Use() private readonly settings!: ServerSettingsRepo;
+ @Use() private readonly users!: UsersRepo;
+ @Bind("MeRoutes.routes") routes!: Hono<AppEnv>;
+ setup() {
+ this.routes = meRoutes({
+ authService: this.auth,
+ config: this.config,
+ desktop: this.desktop.current() as DesktopService | null,
+ prefsRepo: this.prefs,
+ serverSettingsRepo: this.settings,
+ usersRepo: this.users,
+ });
+ }
+}
diff --git a/packages/server/src/http/routes/members.ts b/packages/server/src/http/routes/members.ts
index c0a66d0b..c92ff0eb 100644
--- a/packages/server/src/http/routes/members.ts
+++ b/packages/server/src/http/routes/members.ts
@@ -8,10 +8,17 @@ import { Hono } from "hono";
import type { MemberAddResponse, MembersResponse } from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
import { rejectInDesktopMode } from "./desktop.js";
+import type { DesktopService } from "../../services/desktop-service.js";
import { pathParam, readJson, requireString, requireValidId } from "../validate.js";
-import type { AppDeps } from "../../app.js";
+import type { ProjectService } from "../../services/project-service.js";
-export function membersRoutes(deps: AppDeps): Hono<AppEnv> {
+/** What this route group reaches — bound by its module (src/modules). */
+export interface MembersRouteDeps {
+ desktop: DesktopService | null;
+ projectService: ProjectService;
+}
+
+export function membersRoutes(deps: MembersRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.use("*", rejectInDesktopMode(deps));
diff --git a/packages/server/src/http/routes/memory.ts b/packages/server/src/http/routes/memory.ts
index 57104130..f02d5615 100644
--- a/packages/server/src/http/routes/memory.ts
+++ b/packages/server/src/http/routes/memory.ts
@@ -24,7 +24,15 @@
import { Hono } from "hono";
import type { Context } from "hono";
import type { AppEnv } from "../../auth/middleware.js";
-import type { AppDeps } from "../../app.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+
+import type { MemoryService } from "../../services/memory-service.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface MemoryRouteDeps {
+ memoryService: MemoryService;
+ access: ProjectAccess;
+}
import type { MemoryImportMode } from "../../api/types.js";
import { optionalBoolean, optionalEnum, pathParam, readJson, requireValidId } from "../validate.js";
@@ -37,14 +45,14 @@ function exportStamp(exportedAt: string): string {
return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`;
}
-export function memoryRoutes(deps: AppDeps): Hono<AppEnv> {
+export function memoryRoutes(deps: MemoryRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
/** Shared preamble: id validation before any path construction, then the Project membership check. */
const scope = (c: Context<AppEnv>) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
return { projectId, agentId };
};
@@ -94,7 +102,7 @@ export function memoryRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/scopes/:scopeKey/import", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const key = pathParam(c, "scopeKey");
const body = await readJson(c);
return c.json(
diff --git a/packages/server/src/http/routes/messaging.ts b/packages/server/src/http/routes/messaging.ts
index 87707cda..9e258d0a 100644
--- a/packages/server/src/http/routes/messaging.ts
+++ b/packages/server/src/http/routes/messaging.ts
@@ -72,8 +72,11 @@ import type {
WeChatTestResponse,
} from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
-import type { MessagingBindingRow } from "../../db/repos/messaging-bindings.js";
-import type { SessionRow } from "../../db/repos/sessions.js";
+import type {
+ MessagingBindingRow,
+ MessagingBindingsRepo,
+} from "../../db/repos/messaging-bindings.js";
+import type { SessionRow, SessionsRepo } from "../../db/repos/sessions.js";
import { FEISHU_DEFAULT_DOMAIN, feishuConfigOf } from "../../runtime/messaging/feishu-connector.js";
import { telegramBotIdOf } from "../../runtime/messaging/telegram-connector.js";
import { maskApiKey } from "../../services/project-config-service.js";
@@ -85,7 +88,6 @@ import {
readJson,
requireString,
} from "../validate.js";
-import type { AppDeps } from "../../app.js";
import {
commonBindingFields,
deliveryPatchOf,
@@ -94,6 +96,20 @@ import {
} from "./messaging-channels.js";
import type { MessagingChannelSpec } from "./messaging-channels.js";
import type { MessagingChannel } from "../../runtime/messaging/connector.js";
+import type { MessagingBridge } from "../../runtime/messaging/bridge.js";
+import type { QQScanService } from "../../runtime/messaging/qq-scan.js";
+import type { WeChatScanService } from "../../runtime/messaging/wechat-scan.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface MessagingRouteDeps {
+ messaging: MessagingBridge;
+ messagingRepo: MessagingBindingsRepo;
+ access: ProjectAccess;
+ qqScan: QQScanService;
+ wechatScan: WeChatScanService;
+ sessionsRepo: SessionsRepo;
+}
/** The stored feishu config, tolerated loosely (a malformed document reads as blanks). */
function feishuFieldsOf(row: MessagingBindingRow): {
@@ -241,7 +257,7 @@ function parseBaseDomain(raw: string | undefined): string {
}
/** Session-level entry: /api/sessions/:sessionId/messaging[...]. */
-export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
+export function sessionMessagingRoutes(deps: MessagingRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
/** Same lookup-and-authz shape as the sessions routes: 404 without leaking existence. */
@@ -256,7 +272,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
);
}
try {
- deps.projectService.requireProjectAccess(c.var.user.userId, row.projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, row.projectId);
} catch {
throw new HttpError(
404,
@@ -428,7 +444,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
// intents, and the toggle must work without re-submitting any credential.
app.post(`${base}/state`, async (c) => {
const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, row.projectId);
const enabled = await readStateBody(c);
const binding = boundOr404(row.sessionId);
if (enabled) guardEnable(row.sessionId, spec.channel, binding);
@@ -441,7 +457,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
// affordance is the per-field clear (PUT clear flag), not this.
app.delete(base, (c) => {
const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, row.projectId);
deps.messaging.unbind(row.sessionId, spec.channel);
return c.body(null, 204);
});
@@ -476,7 +492,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
app.put("/:sessionId/messaging/feishu", async (c) => {
const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, row.projectId);
const body = await readJson(c);
const appId = requireString(body, "appId", { minLen: 1, maxLen: 200 }).trim();
if (appId === "") throw badRequest("appId must not be blank.");
@@ -541,7 +557,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
app.put("/:sessionId/messaging/telegram", async (c) => {
const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, row.projectId);
const body = await readJson(c);
const existing = deps.messagingRepo.find(row.sessionId, "telegram");
const { secret: botToken, fromRequest } = resolveSecret({
@@ -614,7 +630,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
app.put("/:sessionId/messaging/qq", async (c) => {
const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, row.projectId);
const body = await readJson(c);
const appId = requireString(body, "appId", { minLen: 1, maxLen: 200 }).trim();
if (appId === "") throw badRequest("appId must not be blank.");
@@ -656,7 +672,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/:sessionId/messaging/qq/scan", async (c) => {
const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, row.projectId);
guardScanStart(row.sessionId, "qq");
let started: { taskId: string; qrUrl: string; pollMs: number };
try {
@@ -669,7 +685,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/:sessionId/messaging/qq/scan/poll", async (c) => {
const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, row.projectId);
const body = await readJson(c);
const taskId = requireString(body, "taskId", { minLen: 1, maxLen: 500 });
let result: Awaited<ReturnType<typeof deps.qqScan.poll>>;
@@ -704,7 +720,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/:sessionId/messaging/qq/scan/cancel", async (c) => {
const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, row.projectId);
const body = await readJson(c);
deps.qqScan.cancel(row.sessionId, requireString(body, "taskId", { minLen: 1, maxLen: 500 }));
return c.body(null, 204);
@@ -747,7 +763,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
*/
app.put("/:sessionId/messaging/wechat", async (c) => {
const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, row.projectId);
const body = await readJson(c);
const existing = deps.messagingRepo.find(row.sessionId, "wechat");
if (existing === null) {
@@ -795,7 +811,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/:sessionId/messaging/wechat/scan", async (c) => {
const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, row.projectId);
guardScanStart(row.sessionId, "wechat");
let started: { taskId: string; qrUrl: string; pollMs: number };
try {
@@ -812,7 +828,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/:sessionId/messaging/wechat/scan/poll", async (c) => {
const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, row.projectId);
const body = await readJson(c);
const taskId = requireString(body, "taskId", { minLen: 1, maxLen: 500 });
let result: Awaited<ReturnType<typeof deps.wechatScan.poll>>;
@@ -854,7 +870,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/:sessionId/messaging/wechat/scan/verify", async (c) => {
const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, row.projectId);
const body = await readJson(c);
const taskId = requireString(body, "taskId", { minLen: 1, maxLen: 500 });
// The platform shows a short numeric code; the bound is generous rather than exact
@@ -874,7 +890,7 @@ export function sessionMessagingRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/:sessionId/messaging/wechat/scan/cancel", async (c) => {
const row = resolveSession(c);
- deps.projectService.requireProjectOwner(c.var.user.userId, row.projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, row.projectId);
const body = await readJson(c);
deps.wechatScan.cancel(
row.sessionId,
diff --git a/packages/server/src/http/routes/model-oauth.ts b/packages/server/src/http/routes/model-oauth.ts
index 689abbcc..5771a692 100644
--- a/packages/server/src/http/routes/model-oauth.ts
+++ b/packages/server/src/http/routes/model-oauth.ts
@@ -22,10 +22,22 @@ import type {
ModelOAuthStatusResponse,
} from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
-import type { AppDeps } from "../../app.js";
+import type { ServerConfig } from "../../config.js";
+import type { SessionManager } from "../../runtime/session-manager.js";
+import type { ModelOAuthService } from "../../services/model-oauth-service.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface ModelOauthRouteDeps extends ModelsRouteDeps {
+ config: ServerConfig;
+ manager: SessionManager;
+ modelOAuth: ModelOAuthService;
+ access: ProjectAccess;
+}
import { HttpError } from "../errors.js";
import { badRequest, readJson, requireString, requireValidId } from "../validate.js";
import { modelConfigChanged } from "./models.js";
+import type { ModelsRouteDeps } from "./models.js";
/** Flow ids are base64url (`randomBytes(32)`); reject anything else before it reaches the store. */
const FLOW_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
@@ -110,7 +122,7 @@ p { margin: 0; color: #4b5563; }
* key up, open tabs unlock, and the machines this Project uses receive it. One helper for
* every write path, so a key minted here reaches a machine the same way one pasted does.
*/
-function credentialsChanged(deps: AppDeps, projectId: string): void {
+function credentialsChanged(deps: ModelOauthRouteDeps, projectId: string): void {
modelConfigChanged(deps, projectId);
}
@@ -149,7 +161,7 @@ function credentialsChanged(deps: AppDeps, projectId: string): void {
*
* Answers HTML throughout — a person is looking at this tab, not a client parsing JSON.
*/
-export function modelOAuthCallbackRoutes(deps: AppDeps): Hono<AppEnv> {
+export function modelOAuthCallbackRoutes(deps: ModelOauthRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", (c) => {
@@ -195,7 +207,7 @@ export function modelOAuthCallbackRoutes(deps: AppDeps): Hono<AppEnv> {
return app;
}
-export function modelOAuthRoutes(deps: AppDeps): Hono<AppEnv> {
+export function modelOAuthRoutes(deps: ModelOauthRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
// Opens a flow and returns the page to send the user to. The provider is looked up in the
@@ -203,7 +215,7 @@ export function modelOAuthRoutes(deps: AppDeps): Hono<AppEnv> {
// such flow and what keeps the authorize/exchange endpoints out of client control.
app.post("/start", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const body = await readJson(c);
const provider = requireString(body, "provider", { minLen: 1, maxLen: 64 });
const mode = parseMode(body.mode);
@@ -233,7 +245,7 @@ export function modelOAuthRoutes(deps: AppDeps): Hono<AppEnv> {
// callback this one IS reached by the App's own signed-in tab.
app.post("/:flowId/code", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const flowId = c.req.param("flowId") ?? "";
if (!FLOW_ID_RE.test(flowId)) {
throw new HttpError(
@@ -263,7 +275,7 @@ export function modelOAuthRoutes(deps: AppDeps): Hono<AppEnv> {
// written under the owner's own session (see the service's `deposit` and `poll`).
app.get("/:flowId", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const flowId = c.req.param("flowId") ?? "";
if (!FLOW_ID_RE.test(flowId)) {
throw new HttpError(
diff --git a/packages/server/src/http/routes/models.ts b/packages/server/src/http/routes/models.ts
index 1c99e66e..ff202cac 100644
--- a/packages/server/src/http/routes/models.ts
+++ b/packages/server/src/http/routes/models.ts
@@ -22,7 +22,23 @@ import type {
import type { AppEnv } from "../../auth/middleware.js";
import { badRequest, readJson, requireString, requireValidId } from "../validate.js";
import { isHttpUrl } from "../../services/protocol-detect.js";
-import type { AppDeps } from "../../app.js";
+import type { SessionsRepo } from "../../db/repos/sessions.js";
+import type { ChannelHub } from "../../runtime/channel.js";
+import type { SessionManager } from "../../runtime/session-manager.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+import type { Machines } from "../../machines/service.js";
+import type { ProjectConfigService } from "../../services/project-config-service.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface ModelsRouteDeps {
+ /** The machines this Project uses receive a credential change too (machines/service.ts). */
+ machines: Machines;
+ channels: ChannelHub;
+ manager: SessionManager;
+ projectConfigService: ProjectConfigService;
+ access: ProjectAccess;
+ sessionsRepo: SessionsRepo;
+}
/**
* Live unlock for auth-dead composers: after a models/credential update, publish
@@ -31,7 +47,7 @@ import type { AppDeps } from "../../app.js";
* response's `updatedAt` when it next loads). Shared with the key-minting routes, which
* change the same credentials by a different path.
*/
-export function publishCredentialsUpdated(deps: AppDeps, projectId: string): void {
+export function publishCredentialsUpdated(deps: ModelsRouteDeps, projectId: string): void {
const event: ServerEvent = { type: "credentials_updated" };
for (const row of deps.sessionsRepo.listByProject(projectId)) {
deps.channels.peek(row.sessionId)?.publish(event, "server_event");
@@ -52,7 +68,7 @@ export function publishCredentialsUpdated(deps: AppDeps, projectId: string): voi
* reach them or their Sessions keep failing on the old one — or start on the wrong default.
* Not awaited: the person editing is not the one who should wait for a set of ssh tunnels.
*/
-export function modelConfigChanged(deps: AppDeps, projectId: string): void {
+export function modelConfigChanged(deps: ModelsRouteDeps, projectId: string): void {
deps.manager.invalidateProjectRuntimes(projectId);
publishCredentialsUpdated(deps, projectId);
void deps.machines.syncModelsEverywhere(projectId);
@@ -181,19 +197,19 @@ function parseModelsUpdate(body: Record<string, unknown>): ModelsUpdateRequest {
return req;
}
-export function modelsRoutes(deps: AppDeps): Hono<AppEnv> {
+export function modelsRoutes(deps: ModelsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
// Defensive id validation.
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
return c.json(await deps.projectConfigService.getModels(projectId));
});
app.put("/", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const req = parseModelsUpdate(await readJson(c));
const res = await deps.projectConfigService.updateModels(projectId, req);
modelConfigChanged(deps, projectId);
@@ -210,7 +226,7 @@ export function modelsRoutes(deps: AppDeps): Hono<AppEnv> {
// is part of what the sync carries.
app.put("/default", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const body = await readJson(c);
const ref: ModelRefDto = {
provider: requireString(body, "provider", { minLen: 1, maxLen: 64 }),
@@ -227,7 +243,7 @@ export function modelsRoutes(deps: AppDeps): Hono<AppEnv> {
// (adding a custom model), everything is taken from the request body.
app.post("/test", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const body = await readJson(c);
const req: ModelTestRequest = {
provider: requireString(body, "provider", { minLen: 1, maxLen: 64 }),
@@ -279,7 +295,7 @@ export function modelsRoutes(deps: AppDeps): Hono<AppEnv> {
// enum plus an HTTP status, where /test surfaces the upstream message verbatim.
app.post("/detect", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const body = await readJson(c);
const req: ModelProtocolDetectRequest = {
baseUrl: requireString(body, "baseUrl", { minLen: 1, maxLen: 2000 }),
@@ -310,7 +326,7 @@ export function modelsRoutes(deps: AppDeps): Hono<AppEnv> {
// reason) and the key travels only in request headers upstream.
app.post("/list", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const body = await readJson(c);
const req: EndpointModelListRequest = {
baseUrl: requireString(body, "baseUrl", { minLen: 1, maxLen: 2000 }),
@@ -331,7 +347,7 @@ export function modelsRoutes(deps: AppDeps): Hono<AppEnv> {
*/
app.post("/detect-vision", async (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const body = await readJson(c);
const req: ModelVisionDetectRequest = {
provider: requireString(body, "provider", { minLen: 1, maxLen: 64 }),
diff --git a/packages/server/src/http/routes/plugins.ts b/packages/server/src/http/routes/plugins.ts
index 9b95dbfd..1e626cb7 100644
--- a/packages/server/src/http/routes/plugins.ts
+++ b/packages/server/src/http/routes/plugins.ts
@@ -22,7 +22,21 @@ import type {
PluginLibraryResponse,
} from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
-import type { AppDeps } from "../../app.js";
+import type { ServerConfig } from "../../config.js";
+import type { Config } from "../../hmr/capabilities.js";
+import type { AgentConfigService } from "../../services/agent-config-service.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+import { Sessions as ManagerIface, SessionsModule } from "../../runtime/session-manager.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import { agentHooksRoutes } from "./hooks.js";
+
+/** What these route groups reach — bound by their component below. */
+export interface PluginsRouteDeps {
+ config: ServerConfig;
+ access: ProjectAccess;
+ agentConfigService: AgentConfigService;
+ manager: ManagerIface;
+}
import { HttpError } from "../errors.js";
import { badRequest, optionalStringArray, readJson, requireValidId } from "../validate.js";
import {
@@ -63,13 +77,13 @@ export function pluginLibraryRoutes(): Hono<AppEnv> {
}
/** /api/projects/:p/agents/:a/plugins: install is a Project-member operation. */
-export function agentPluginsRoutes(deps: AppDeps): Hono<AppEnv> {
+export function agentPluginsRoutes(deps: PluginsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.post("/", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
await deps.agentConfigService.requireExists(projectId, agentId);
const names = optionalStringArray(await readJson(c), "names") ?? [];
if (names.length === 0) throw badRequest("names must be a non-empty array.");
@@ -98,3 +112,44 @@ export function agentPluginsRoutes(deps: AppDeps): Hono<AppEnv> {
return app;
}
+
+/** The plugin library and the Agent-scoped install/uninstall groups, as one route component. */
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ { id: "PluginRoutes.library", prefix: "/api/plugins", auth: "user", order: 70 },
+ {
+ id: "PluginRoutes.agent-plugins",
+ prefix: "/api/projects/:projectId/agents/:agentId/plugins",
+ auth: "user",
+ order: 222,
+ },
+ {
+ id: "PluginRoutes.agent-hooks",
+ prefix: "/api/projects/:projectId/agents/:agentId/hooks",
+ auth: "user",
+ order: 224,
+ },
+ ],
+ },
+})
+export class PluginRoutes {
+ @Use() private readonly config!: Config;
+ @Use() private readonly access!: ProjectAccess;
+ @Use() private readonly agentConfig!: AgentConfigService;
+ @Use(SessionsModule) private readonly manager!: ManagerIface;
+ @Bind("PluginRoutes.library") libraryRoutes!: Hono<AppEnv>;
+ @Bind("PluginRoutes.agent-plugins") pluginRoutes!: Hono<AppEnv>;
+ @Bind("PluginRoutes.agent-hooks") hookRoutes!: Hono<AppEnv>;
+ setup() {
+ const deps = {
+ config: this.config,
+ access: this.access,
+ agentConfigService: this.agentConfig,
+ manager: this.manager,
+ };
+ this.libraryRoutes = pluginLibraryRoutes();
+ this.pluginRoutes = agentPluginsRoutes(deps);
+ this.hookRoutes = agentHooksRoutes(deps);
+ }
+}
diff --git a/packages/server/src/http/routes/preview.ts b/packages/server/src/http/routes/preview.ts
index b6c5858c..92b4ec85 100644
--- a/packages/server/src/http/routes/preview.ts
+++ b/packages/server/src/http/routes/preview.ts
@@ -15,9 +15,16 @@
*/
import { Hono } from "hono";
import type { SessionsRepo } from "../../db/repos/sessions.js";
-import type { WorkspaceFilesService } from "../../services/workspace-files-service.js";
+import { WorkspaceFilesService } from "../../services/workspace-files-service.js";
import type { PreviewTokenSigner } from "../../services/preview-token.js";
-import { hostOnly, requestAuthority } from "../../services/preview-token.js";
+import {
+ hostOnly,
+ requestAuthority,
+ createPreviewTokenSigner,
+} from "../../services/preview-token.js";
+import { Interface, Bind, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";
+import type { AppEnv } from "../../auth/middleware.js";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
export interface PreviewDeps {
sessionsRepo: SessionsRepo;
@@ -83,3 +90,40 @@ export function previewRoutes(deps: PreviewDeps) {
return app;
}
+
+export abstract class WorkspaceFiles extends Interface<
+ Pick<WorkspaceFilesService, "list" | "read" | "write" | "statExisting">
+>() {}
+export abstract class PreviewTokens extends Interface<
+ Pick<PreviewTokenSigner, "sign" | "verify">
+>() {}
+
+@Module({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "workspace.preview",
+ prefix: "/preview",
+ auth: "none",
+ order: 900,
+ },
+ ],
+ },
+})
+export class WorkspaceModule {
+ @Use() private readonly sessionsRepo!: SessionsRepo;
+ @Provide() workspaceFiles!: WorkspaceFiles;
+ @Provide() previewTokens!: PreviewTokens;
+ @Bind("workspace.preview") previewRoutes!: ReturnType<typeof previewRoutes>;
+ setup() {
+ const workspaceFiles = new WorkspaceFilesService();
+ const previewTokens = createPreviewTokenSigner();
+ this.workspaceFiles = workspaceFiles;
+ this.previewTokens = previewTokens;
+ this.previewRoutes = previewRoutes({
+ previewTokens,
+ sessionsRepo: this.sessionsRepo,
+ workspaceFiles,
+ });
+ }
+}
diff --git a/packages/server/src/http/routes/projects.ts b/packages/server/src/http/routes/projects.ts
index 2bf8aeb7..9082dbe0 100644
--- a/packages/server/src/http/routes/projects.ts
+++ b/packages/server/src/http/routes/projects.ts
@@ -15,9 +15,18 @@ import {
requireString,
requireValidId,
} from "../validate.js";
-import type { AppDeps } from "../../app.js";
+import type { ProjectService } from "../../services/project-service.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Desktop } from "../../hmr/capabilities.js";
+import type { DesktopService } from "../../services/desktop-service.js";
+import { membersRoutes } from "./members.js";
-export function projectsRoutes(deps: AppDeps): Hono<AppEnv> {
+/** What this route group reaches — bound by its module (src/modules). */
+export interface ProjectsRouteDeps {
+ projectService: ProjectService;
+}
+
+export function projectsRoutes(deps: ProjectsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
@@ -54,3 +63,35 @@ export function projectsRoutes(deps: AppDeps): Hono<AppEnv> {
return app;
}
+
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "project-admin.projects",
+ prefix: "/api/projects",
+ auth: "user",
+ order: 80,
+ },
+ {
+ id: "project-admin.members",
+ prefix: "/api/projects/:projectId/members",
+ auth: "user",
+ order: 90,
+ },
+ ],
+ },
+})
+export class ProjectAdminRoutes {
+ @Use() private readonly projectService!: ProjectService;
+ @Use() private readonly desktop!: Desktop;
+ @Bind("project-admin.projects") projectsRoutes!: Hono<AppEnv>;
+ @Bind("project-admin.members") membersRoutes!: Hono<AppEnv>;
+ setup() {
+ this.projectsRoutes = projectsRoutes({ projectService: this.projectService });
+ this.membersRoutes = membersRoutes({
+ projectService: this.projectService,
+ desktop: this.desktop.current() as DesktopService | null,
+ });
+ }
+}
diff --git a/packages/server/src/http/routes/schedules.ts b/packages/server/src/http/routes/schedules.ts
index 23a90689..9c5240a2 100644
--- a/packages/server/src/http/routes/schedules.ts
+++ b/packages/server/src/http/routes/schedules.ts
@@ -12,7 +12,22 @@ import { Hono } from "hono";
import { isValidId } from "@prismshadow/penguin-core";
import type { ScheduleItem, ScheduleStatus, SchedulesResponse } from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
-import type { AppDeps } from "../../app.js";
+import type { ServerConfig } from "../../config.js";
+import type { SchedulesRepo, ScheduleStateRow } from "../../db/repos/schedules.js";
+import type { Scheduler } from "../../runtime/scheduler.js";
+import type { AgentConfigService } from "../../services/agent-config-service.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+import type { ProjectConfigService } from "../../services/project-config-service.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface SchedulesRouteDeps {
+ agentConfigService: AgentConfigService;
+ config: ServerConfig;
+ projectConfigService: ProjectConfigService;
+ access: ProjectAccess;
+ scheduler: Scheduler;
+ schedulesRepo: SchedulesRepo;
+}
import { HttpError } from "../errors.js";
import {
badRequest,
@@ -28,7 +43,6 @@ import {
parseScheduleFile,
slotInWindow,
} from "../../runtime/schedule-file.js";
-import type { ScheduleStateRow } from "../../db/repos/schedules.js";
import {
deleteScheduleFile,
readScheduleFile,
@@ -36,6 +50,8 @@ import {
validateScheduleModelRef,
writeScheduleFile,
} from "../../runtime/schedule-store.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Config } from "../../hmr/capabilities.js";
/** Validate and shape the POST/PUT request body into file fields (semantic validation is left to parseScheduleFile). */
function parseUpsertBody(body: Record<string, unknown>): {
@@ -133,13 +149,13 @@ function requireScheduleName(raw: string | undefined): string {
return raw;
}
-export function scheduleRoutes(deps: AppDeps): Hono<AppEnv> {
+export function scheduleRoutes(deps: SchedulesRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
await deps.agentConfigService.requireExists(projectId, agentId);
const { entries, invalid } = await deps.scheduler.listAgent(projectId, agentId);
const nowMs = Date.now();
@@ -153,7 +169,7 @@ export function scheduleRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
await deps.agentConfigService.requireExists(projectId, agentId);
const body = await readJson(c);
const name = requireScheduleName(requireString(body, "name", { minLen: 1, maxLen: 100 }));
@@ -170,7 +186,7 @@ export function scheduleRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/template-placeholder", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const view = await deps.agentConfigService.insertTemplatePlaceholder(
projectId,
agentId,
@@ -182,7 +198,7 @@ export function scheduleRoutes(deps: AppDeps): Hono<AppEnv> {
app.get("/:name", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const name = requireScheduleName(c.req.param("name"));
const item = await readItem(deps, projectId, agentId, name);
return c.json(item);
@@ -191,7 +207,7 @@ export function scheduleRoutes(deps: AppDeps): Hono<AppEnv> {
app.put("/:name", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const name = requireScheduleName(c.req.param("name"));
if (!(await readScheduleFile(deps.config.root, projectId, agentId, name))) {
throw new HttpError(404, "schedule_not_found", `Schedule does not exist: ${name}`);
@@ -204,7 +220,7 @@ export function scheduleRoutes(deps: AppDeps): Hono<AppEnv> {
app.delete("/:name", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const name = requireScheduleName(c.req.param("name"));
const removed = await deleteScheduleFile(deps.config.root, projectId, agentId, name);
if (!removed)
@@ -218,7 +234,7 @@ export function scheduleRoutes(deps: AppDeps): Hono<AppEnv> {
/** Write + register creator + reconcile immediately (API changes take effect right away). */
async function upsert(
- deps: AppDeps,
+ deps: SchedulesRouteDeps,
userId: string,
projectId: string,
agentId: string,
@@ -247,7 +263,7 @@ async function upsert(
}
async function readItem(
- deps: AppDeps,
+ deps: SchedulesRouteDeps,
projectId: string,
agentId: string,
name: string,
@@ -259,3 +275,35 @@ async function readItem(
if (bad) throw badRequest(`Invalid schedule file: ${bad.error}`);
throw new HttpError(404, "schedule_not_found", `Schedule does not exist: ${name}`);
}
+
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "SchedulerRoutes.routes",
+ prefix: "/api/projects/:projectId/agents/:agentId/schedules",
+ auth: "user",
+ order: 200,
+ },
+ ],
+ },
+})
+export class SchedulerRoutes {
+ @Use() private readonly config!: Config;
+ @Use() private readonly agentConfig!: AgentConfigService;
+ @Use() private readonly projectConfig!: ProjectConfigService;
+ @Use() private readonly access!: ProjectAccess;
+ @Use() private readonly scheduler!: Scheduler;
+ @Use() private readonly schedulesRepo!: SchedulesRepo;
+ @Bind("SchedulerRoutes.routes") routes!: Hono<AppEnv>;
+ setup() {
+ this.routes = scheduleRoutes({
+ agentConfigService: this.agentConfig,
+ config: this.config,
+ projectConfigService: this.projectConfig,
+ access: this.access,
+ scheduler: this.scheduler,
+ schedulesRepo: this.schedulesRepo,
+ });
+ }
+}
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index e2d27dd0..bb78ef70 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -42,10 +42,10 @@ import type {
} from "../../api/types.js";
import { compactionThresholdFor } from "../../services/context-breakdown.js";
import { decodeCursor } from "../../services/message-window.js";
-import type { MessagesPageRequest } from "../../services/trace-service.js";
+import type { MessagesPageRequest, TraceService } from "../../services/trace-service.js";
import { PREVIEW_TOKEN_TTL_MS, resolvePreviewTarget } from "../../services/preview-token.js";
import type { AppEnv } from "../../auth/middleware.js";
-import type { SessionRow } from "../../db/repos/sessions.js";
+import type { SessionRow, SessionsRepo } from "../../db/repos/sessions.js";
import { assertWorkspaceAllowed } from "../../services/workspace-guard.js";
import { isGoalOutcome } from "../../runtime/goal-events.js";
import { HttpError } from "../errors.js";
@@ -63,7 +63,37 @@ import {
requireString,
requireValidId,
} from "../validate.js";
-import type { AppDeps } from "../../app.js";
+import type { ServerConfig } from "../../config.js";
+import type { ServerSettingsRepo } from "../../db/repos/server-settings.js";
+import type { ChannelHub } from "../../runtime/channel.js";
+import type { MessagingBridge } from "../../runtime/messaging/bridge.js";
+import type { SessionManager, RecallStore } from "../../runtime/session-manager.js";
+import type { SessionSources } from "../../runtime/session-sources.js";
+import type { AgentConfigService } from "../../services/agent-config-service.js";
+import type { PreviewTokenSigner } from "../../services/preview-token.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+import type { Machines } from "../../machines/service.js";
+import type { ProjectConfigService } from "../../services/project-config-service.js";
+import type { SessionService } from "../../services/session-service.js";
+import type { WorkspaceFilesService } from "../../services/workspace-files-service.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface SessionsRouteDeps {
+ agentConfigService: AgentConfigService;
+ channels: ChannelHub;
+ config: ServerConfig;
+ manager: SessionManager;
+ messaging: MessagingBridge;
+ previewTokens: PreviewTokenSigner;
+ projectConfigService: ProjectConfigService;
+ access: ProjectAccess;
+ serverSettingsRepo: ServerSettingsRepo;
+ sessionService: SessionService;
+ sessionSources: SessionSources;
+ sessionsRepo: SessionsRepo;
+ traceService: TraceService;
+ workspaceFiles: WorkspaceFilesService;
+}
import { MAX_UPLOAD_BYTES } from "../../services/workspace-files-service.js";
import {
assertAttachmentBudget,
@@ -79,7 +109,30 @@ import {
toAttachmentLimits,
} from "../../services/attachment-limits.js";
import type { AttachmentLimits } from "../../services/attachment-limits.js";
-import type { RecallStore } from "../../runtime/session-manager.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
+import { Channels, Config, RuntimeModule } from "../../hmr/capabilities.js";
+import {
+ Sessions as ManagerIface,
+ SessionServiceIface,
+ SessionsModule,
+} from "../../runtime/session-manager.js";
+import { Messaging, MessagingModule } from "../../runtime/messaging/bridge.js";
+import { WorkspaceModule, PreviewTokens } from "./preview.js";
+import { agentsRoutes } from "./agents.js";
+import { agentConfigRoutes } from "./agent-config.js";
+import { vaultRoutes } from "./vault.js";
+import { modelsRoutes } from "./models.js";
+import { modelOAuthCallbackRoutes, modelOAuthRoutes } from "./model-oauth.js";
+import { chatDefaultsRoutes } from "./chat-defaults.js";
+import { commandPolicyRoutes } from "./command-policy.js";
+import { usageRoutes } from "./usage.js";
+import type { AgentService } from "../../services/agent-service.js";
+import type { SchedulesRepo } from "../../db/repos/schedules.js";
+import type { ModelOAuthService } from "../../services/model-oauth-service.js";
+import type { TraceIndexService } from "../../services/trace-index.js";
+import type { ErrorsRepo } from "../../db/repos/errors.js";
+import type { UsageService } from "../../services/usage-service.js";
/** Max title length for manual renames: looser than the auto-generated 30-char limit, to accommodate users' own organizing conventions. */
const SESSION_TITLE_MAX = 120;
@@ -168,7 +221,10 @@ function messagesPageQuery(c: Context): MessagesPageRequest | null {
* Fail-soft: this is one mark on a gauge, and an Agent deleted out from under a still-indexed
* Session (or a config that will not parse) must not take the whole composition down with it.
*/
-async function sessionCompactionThreshold(deps: AppDeps, row: SessionRow): Promise<number | null> {
+async function sessionCompactionThreshold(
+ deps: SessionsRouteDeps,
+ row: SessionRow,
+): Promise<number | null> {
try {
const [agent, project] = await Promise.all([
deps.agentConfigService.getConfig(row.projectId, row.agentId),
@@ -419,7 +475,7 @@ function parseGoalField(body: Record<string, unknown>): { budget: number } | nul
}
/** Agent-level entry: /api/projects/:p/agents/:a/sessions. */
-export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {
+export function agentSessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
// Serves every row straight from the DB, whichever client created it (legacy CLI-direct
@@ -428,7 +484,7 @@ export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {
// Id validity is checked before any path is constructed: guards against agentId path traversal across Projects.
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
await deps.agentConfigService.requireExists(projectId, agentId);
// Optional paging (absent = full list, the pre-paging contract): the sidebar requests
// limit+1 and shows limit, detecting "has more" without a response-envelope change.
@@ -466,7 +522,7 @@ export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
await deps.agentConfigService.requireExists(projectId, agentId);
const body = await readJson(c);
const modelId = optionalString(body, "modelId", { minLen: 1, label: "modelId" });
@@ -509,7 +565,7 @@ export function agentSessionsRoutes(deps: AppDeps): Hono<AppEnv> {
}
/** Session-level entry point: /api/sessions/:sessionId/*. */
-export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
+export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
/** Look up ownership and check access (404 if the index has no such Session, or access is denied — never leaking existence). */
@@ -524,7 +580,7 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
);
}
try {
- deps.projectService.requireProjectAccess(c.var.user.userId, row.projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, row.projectId);
} catch {
throw new HttpError(
404,
@@ -1473,3 +1529,183 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
return app;
}
+
+/**
+ * The HTTP surface that drives the session runtime — every route group that reaches the
+ * SessionManager, plus the Project-level groups that share its access checks. Routes only:
+ * this module provides nothing, it binds.
+ */
+
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "session-api.model-oauth-callback",
+ prefix: "/api/projects/:projectId/model-oauth/callback",
+ auth: "none",
+ order: 6,
+ },
+ {
+ id: "session-api.models",
+ prefix: "/api/projects/:projectId/models",
+ auth: "user",
+ order: 100,
+ },
+ {
+ id: "session-api.model-oauth",
+ prefix: "/api/projects/:projectId/model-oauth",
+ auth: "user",
+ order: 110,
+ },
+ {
+ id: "session-api.chat-defaults",
+ prefix: "/api/projects/:projectId/chat-defaults",
+ auth: "user",
+ order: 120,
+ },
+ {
+ id: "session-api.command-policy",
+ prefix: "/api/projects/:projectId/command-policy",
+ auth: "user",
+ order: 130,
+ },
+ {
+ id: "session-api.agents",
+ prefix: "/api/projects/:projectId/agents",
+ auth: "user",
+ order: 140,
+ },
+ {
+ id: "session-api.agent-config",
+ prefix: "/api/projects/:projectId/agents/:agentId/config",
+ auth: "user",
+ order: 170,
+ },
+ {
+ id: "session-api.vault",
+ prefix: "/api/projects/:projectId/agents/:agentId/vault",
+ auth: "user",
+ order: 180,
+ },
+ {
+ id: "session-api.agent-sessions",
+ prefix: "/api/projects/:projectId/agents/:agentId/sessions",
+ auth: "user",
+ order: 250,
+ },
+ {
+ id: "session-api.usage",
+ prefix: "/api/projects/:projectId/usage",
+ auth: "user",
+ order: 260,
+ },
+ {
+ id: "session-api.sessions",
+ prefix: "/api/sessions",
+ auth: "user",
+ order: 270,
+ },
+ ],
+ },
+})
+export class SessionApiRoutes {
+ @Use(RuntimeModule) private readonly config!: Config;
+ @Use(RuntimeModule) private readonly channels!: Channels;
+ @Use(SessionsModule) private readonly manager!: ManagerIface;
+ @Use(SessionsModule) private readonly sessionService!: SessionServiceIface;
+ @Use() private readonly agentConfig!: AgentConfigService;
+ @Use() private readonly agents!: AgentService;
+ @Use(MessagingModule) private readonly messaging!: Messaging;
+ @Use() private readonly schedulesRepo!: SchedulesRepo;
+ @Use() private readonly access!: ProjectAccess;
+ @Use() private readonly machines!: Machines;
+ @Use() private readonly projectConfig!: ProjectConfigService;
+ @Use() private readonly modelOAuth!: ModelOAuthService;
+ @Use() private readonly traceIndex!: TraceIndexService;
+ @Use() private readonly traces!: TraceService;
+ @Use() private readonly workspaceFiles!: WorkspaceFilesService;
+ @Use(WorkspaceModule) private readonly previewTokens!: PreviewTokens;
+ @Use() private readonly settings!: ServerSettingsRepo;
+ @Use() private readonly sessionsRepo!: SessionsRepo;
+ @Use() private readonly sources!: SessionSources;
+ @Use() private readonly errorsRepo!: ErrorsRepo;
+ @Use() private readonly usage!: UsageService;
+ @Bind("session-api.model-oauth-callback") modelOauthCallbackRoutes!: Hono<AppEnv>;
+ @Bind("session-api.models") modelsRoutes!: Hono<AppEnv>;
+ @Bind("session-api.model-oauth") modelOauthRoutes!: Hono<AppEnv>;
+ @Bind("session-api.chat-defaults") chatDefaultsRoutes!: Hono<AppEnv>;
+ @Bind("session-api.command-policy") commandPolicyRoutes!: Hono<AppEnv>;
+ @Bind("session-api.agents") agentsRoutes!: Hono<AppEnv>;
+ @Bind("session-api.agent-config") agentConfigRoutes!: Hono<AppEnv>;
+ @Bind("session-api.vault") vaultRoutes!: Hono<AppEnv>;
+ @Bind("session-api.agent-sessions") agentSessionsRoutes!: Hono<AppEnv>;
+ @Bind("session-api.usage") usageRoutes!: Hono<AppEnv>;
+ @Bind("session-api.sessions") sessionsRoutes!: Hono<AppEnv>;
+ setup() {
+ const manager = this.manager as SessionManager;
+ const sessionService = this.sessionService as SessionService;
+ const agentConfigService = this.agentConfig;
+ const access = this.access;
+ const projectConfigService = this.projectConfig;
+ const sessionsRepo = this.sessionsRepo;
+ const channels = this.channels as ChannelHub;
+ const sessionsDeps = {
+ agentConfigService,
+ channels,
+ config: this.config,
+ manager,
+ messaging: this.messaging as MessagingBridge,
+ previewTokens: this.previewTokens as PreviewTokenSigner,
+ projectConfigService,
+ access,
+ serverSettingsRepo: this.settings,
+ sessionService,
+ sessionSources: this.sources,
+ sessionsRepo,
+ traceService: this.traces,
+ workspaceFiles: this.workspaceFiles,
+ };
+ const modelOAuthDeps = {
+ config: this.config,
+ manager,
+ modelOAuth: this.modelOAuth,
+ access,
+ machines: this.machines,
+ channels,
+ projectConfigService,
+ sessionsRepo,
+ };
+ this.modelOauthCallbackRoutes = modelOAuthCallbackRoutes(modelOAuthDeps);
+ this.modelsRoutes = modelsRoutes({
+ machines: this.machines,
+ channels,
+ manager,
+ projectConfigService,
+ access,
+ sessionsRepo,
+ });
+ this.modelOauthRoutes = modelOAuthRoutes(modelOAuthDeps);
+ this.chatDefaultsRoutes = chatDefaultsRoutes({
+ agentConfigService,
+ projectConfigService,
+ access,
+ });
+ this.commandPolicyRoutes = commandPolicyRoutes({ projectConfigService, access });
+ this.agentsRoutes = agentsRoutes({
+ agentConfigService,
+ agentService: this.agents,
+ errorsRepo: this.errorsRepo,
+ manager,
+ access,
+ schedulesRepo: this.schedulesRepo,
+ sessionService,
+ sessionsRepo,
+ traceIndex: this.traceIndex,
+ });
+ this.agentConfigRoutes = agentConfigRoutes({ agentConfigService, manager, access });
+ this.vaultRoutes = vaultRoutes({ agentConfigService, manager, access });
+ this.agentSessionsRoutes = agentSessionsRoutes(sessionsDeps);
+ this.usageRoutes = usageRoutes({ access, usageService: this.usage });
+ this.sessionsRoutes = sessionsRoutes(sessionsDeps);
+ }
+}
diff --git a/packages/server/src/http/routes/skills.ts b/packages/server/src/http/routes/skills.ts
index 6a97235c..c5408e53 100644
--- a/packages/server/src/http/routes/skills.ts
+++ b/packages/server/src/http/routes/skills.ts
@@ -26,7 +26,16 @@ import {
} from "@prismshadow/penguin-core";
import type { AgentSkillsResponse } from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
-import type { AppDeps } from "../../app.js";
+import type { ServerConfig } from "../../config.js";
+import type { AgentConfigService } from "../../services/agent-config-service.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface SkillsRouteDeps {
+ agentConfigService: AgentConfigService;
+ config: ServerConfig;
+ access: ProjectAccess;
+}
import { HttpError } from "../errors.js";
import { badRequest, readJson, requireString, requireValidId } from "../validate.js";
import { toSkillItem } from "../../services/plugin-library.js";
@@ -37,6 +46,8 @@ import {
skillTooLarge,
unzipBounded,
} from "../../services/skill-import-limits.js";
+import { Bind, Component } from "@prismshadow/penguin-core/kernel";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
/** Decoded zip cap: aligned with the Agent snapshot import (stays within the 20MB body limit after base64). Shared with the hooks archive routes. */
export const MAX_ARCHIVE_BYTES = 14 * 1024 * 1024;
@@ -168,7 +179,7 @@ function explicitSkillVersion(skillMd: string): string | null {
}
/** /api/projects/:p/agents/:a/skills: read, import/export and uninstall are all Project-member operations. */
-export function agentSkillsRoutes(deps: AppDeps): Hono<AppEnv> {
+export function agentSkillsRoutes(deps: SkillsRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
const listResponse = async (
@@ -182,7 +193,7 @@ export function agentSkillsRoutes(deps: AppDeps): Hono<AppEnv> {
// Defensive id validation happens before any path construction: prevents path traversal for cross-Project privilege escalation.
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
await deps.agentConfigService.requireExists(projectId, agentId);
return c.json(await listResponse(projectId, agentId));
});
@@ -193,7 +204,7 @@ export function agentSkillsRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/template-placeholder", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const view = await deps.agentConfigService.insertTemplatePlaceholder(
projectId,
agentId,
@@ -208,7 +219,7 @@ export function agentSkillsRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/archive", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
await deps.agentConfigService.requireExists(projectId, agentId);
const body = await readJson(c);
const dataBase64 = requireString(body, "dataBase64", { minLen: 1, maxLen: 20 * 1024 * 1024 });
@@ -248,7 +259,7 @@ export function agentSkillsRoutes(deps: AppDeps): Hono<AppEnv> {
app.get("/:name/archive", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const name = requireValidId(c, "name");
const dir = path.join(skillsDir(deps.config.root, projectId, agentId), name);
// Installed-check uses the same criterion as listInstalledSkills: skills/<name>/SKILL.md exists.
@@ -276,7 +287,7 @@ export function agentSkillsRoutes(deps: AppDeps): Hono<AppEnv> {
app.delete("/:name", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const name = requireValidId(c, "name");
// Installed-check uses the same criterion as listInstalledSkills: skills/<name>/SKILL.md exists.
const file = path.join(skillsDir(deps.config.root, projectId, agentId), name, "SKILL.md");
diff --git a/packages/server/src/http/routes/usage.ts b/packages/server/src/http/routes/usage.ts
index 665a61b4..26de7c37 100644
--- a/packages/server/src/http/routes/usage.ts
+++ b/packages/server/src/http/routes/usage.ts
@@ -23,7 +23,14 @@ import type {
} from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
import { badRequest, optionalDateParam, paginationQuery, requireValidId } from "../validate.js";
-import type { AppDeps } from "../../app.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+import type { UsageService } from "../../services/usage-service.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface UsageRouteDeps {
+ access: ProjectAccess;
+ usageService: UsageService;
+}
const GROUP_BYS: readonly UsageGroupBy[] = ["date", "agent", "model", "session"];
@@ -60,13 +67,13 @@ function tsWindowQuery(c: Context<AppEnv>): { fromTs?: string; toTs?: string } {
return { ...(fromTs !== undefined ? { fromTs } : {}), ...(toTs !== undefined ? { toTs } : {}) };
}
-export function usageRoutes(deps: AppDeps): Hono<AppEnv> {
+export function usageRoutes(deps: UsageRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
// Defensive id validation.
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const groupByRaw = c.req.query("groupBy") ?? "date";
if (!(GROUP_BYS as readonly string[]).includes(groupByRaw)) {
throw badRequest(`groupBy must be one of ${GROUP_BYS.join(" / ")}.`);
@@ -107,7 +114,7 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {
// than a reason to widen the models response with telemetry.
app.get("/model-totals", (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
return c.json(deps.usageService.modelTotals(projectId));
});
@@ -118,7 +125,7 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {
// narrowing the summary above does not do.
app.get("/errors", (c) => {
const projectId = requireValidId(c, "projectId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
const { offset, limit } = paginationQuery(c);
const from = optionalDateParam(c.req.query("from"), "from");
const to = optionalDateParam(c.req.query("to"), "to");
@@ -162,7 +169,7 @@ export function usageRoutes(deps: AppDeps): Hono<AppEnv> {
// Owner only, the rule Agent deletion applies to error rows already (it cascade-deletes
// them): membership is enough to READ the panel, but these rows are the Project's shared
// history and one member emptying them takes them from everyone.
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const from = optionalDateParam(c.req.query("from"), "from");
const to = optionalDateParam(c.req.query("to"), "to");
// Both bounds are required here, unlike on the two reads: a missing bound reads as
diff --git a/packages/server/src/http/routes/vault.ts b/packages/server/src/http/routes/vault.ts
index 02cece25..b7a4033b 100644
--- a/packages/server/src/http/routes/vault.ts
+++ b/packages/server/src/http/routes/vault.ts
@@ -9,7 +9,16 @@ import { Hono } from "hono";
import type { VaultEntryUpdate, VaultUpdateRequest } from "../../api/types.js";
import type { AppEnv } from "../../auth/middleware.js";
import { badRequest, readJson, requireString, requireValidId } from "../validate.js";
-import type { AppDeps } from "../../app.js";
+import type { SessionManager } from "../../runtime/session-manager.js";
+import type { AgentConfigService } from "../../services/agent-config-service.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface VaultRouteDeps {
+ agentConfigService: AgentConfigService;
+ manager: SessionManager;
+ access: ProjectAccess;
+}
/** Validate the PUT request body and shape it into a VaultUpdateRequest (semantic checks like key-name rules live in the service layer). */
function parseVaultUpdate(body: Record<string, unknown>): VaultUpdateRequest {
@@ -33,21 +42,21 @@ function parseVaultUpdate(body: Record<string, unknown>): VaultUpdateRequest {
return { entries };
}
-export function vaultRoutes(deps: AppDeps): Hono<AppEnv> {
+export function vaultRoutes(deps: VaultRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
// Defensive id validation happens before any path construction: prevents agentId path traversal for cross-Project privilege escalation.
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectAccess(c.var.user.userId, projectId);
+ deps.access.requireProjectAccess(c.var.user.userId, projectId);
return c.json(await deps.agentConfigService.getVault(projectId, agentId));
});
app.put("/", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const req = parseVaultUpdate(await readJson(c));
const res = await deps.agentConfigService.updateVault(projectId, agentId, req);
// No runtime invalidation: like every Agent State change, the new values reach a
@@ -62,7 +71,7 @@ export function vaultRoutes(deps: AppDeps): Hono<AppEnv> {
app.post("/template-placeholder", async (c) => {
const projectId = requireValidId(c, "projectId");
const agentId = requireValidId(c, "agentId");
- deps.projectService.requireProjectOwner(c.var.user.userId, projectId);
+ deps.access.requireProjectOwner(c.var.user.userId, projectId);
const view = await deps.agentConfigService.insertTemplatePlaceholder(
projectId,
agentId,
diff --git a/packages/server/src/http/routes/version.ts b/packages/server/src/http/routes/version.ts
index bbcd27ba..f192eea6 100644
--- a/packages/server/src/http/routes/version.ts
+++ b/packages/server/src/http/routes/version.ts
@@ -25,7 +25,20 @@ import type { Context } from "hono";
import type { RestartResponse, UpdateJobStatus, VersionResponse } from "../../api/types.js";
import { HttpError } from "../errors.js";
import type { AppEnv } from "../../auth/middleware.js";
-import type { AppDeps } from "../../app.js";
+import type { ServerConfig } from "../../config.js";
+import type { UpdateCheckService } from "../../services/update-check-service.js";
+import type { UpdateJobService } from "../../services/update-job.js";
+import type { Lifecycle } from "../../hmr/capabilities.js";
+
+/** What this route group reaches — bound by its module (src/modules). */
+export interface VersionRouteDeps {
+ config: ServerConfig;
+ updateCheck: UpdateCheckService;
+ /** The admin self-update run in the background (`penguin update --yes`), with its progress for the update modal. */
+ updateJob: UpdateJobService;
+ /** Whether a supervisor relaunches this process, and the restart trigger the update flow pulls. */
+ lifecycle: Lifecycle;
+}
// The classifier lives with the job now; re-exported so its unit tests keep their import.
export { classifyUpdateRun } from "../../services/update-job.js";
@@ -39,7 +52,7 @@ function requireAdmin(c: Context<AppEnv>): void {
}
}
-export function versionRoutes(deps: AppDeps): Hono<AppEnv> {
+export function versionRoutes(deps: VersionRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
app.get("/", async (c) => {
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 11cb564a..aa462a4b 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -20,7 +20,11 @@ import type { Server as HttpServer } from "node:http";
import { config as loadDotenv } from "dotenv";
import { serve } from "@hono/node-server";
import { SERVER_RESTART_EXIT_CODE } from "@prismshadow/penguin-core";
-import { bootAppDeps, createRuntimeApp, type AppDeps } from "./app.js";
+import { bootAppDeps, createRuntimeApp } from "./app.js";
+import type { ServerBoot } from "./app.js";
+import type { AuthService } from "./auth/service.js";
+import type { ServerSettingsRepo } from "./db/repos/server-settings.js";
+import type { ErrorRecorder } from "./runtime/error-recorder.js";
import { ADMIN_USER_ID } from "./auth/service.js";
import { resolveServerConfig, type ServerConfig } from "./config.js";
import { clearInitialAdminPassword, renderFirstLoginNotice } from "./initial-password.js";
@@ -69,7 +73,7 @@ class PenguinServer {
/** Assigned by loadPlugins(); published to the platform tree by buildDeps(). */
private plugins!: PluginHost;
/** Assigned by buildDeps(); the merged runtime + business view (see app.ts). */
- private deps!: AppDeps;
+ private deps!: ServerBoot;
/** Assigned by buildApp(). */
private app!: ReturnType<typeof createRuntimeApp>;
/** Assigned by listen(). */
@@ -80,6 +84,11 @@ class PenguinServer {
private shuttingDown = false;
+ /** The current App's auth service — resolved per call, since a hot swap replaces the tree. */
+ private auth(): AuthService {
+ return this.deps.tree.api<AuthService>("AuthService", "AuthService");
+ }
+
/** `.env` may itself define HTTP_PROXY, so it is loaded before the dispatcher reads one. */
loadEnv(): void {
loadDotenv({ quiet: true });
@@ -130,14 +139,13 @@ class PenguinServer {
async loadPlugins(): Promise<void> {
this.plugins = new PluginHost();
const result = await loadPlugins(this.config.root);
- for (const { specifier, plugin } of result.loaded) {
- // use() runs the plugin'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.
+ for (const entry of result.loaded) {
+ // Only held here — the platform boots the modules inside its own tree, per App. A
+ // module name clash is a LOAD failure, isolated per entry like an import failure.
try {
- await this.plugins.use(plugin);
+ this.plugins.use(entry);
} catch (err) {
- result.failed.set(specifier, err instanceof Error ? err.message : String(err));
+ result.failed.set(entry.specifier, err instanceof Error ? err.message : String(err));
}
}
for (const [specifier, reason] of result.failed) {
@@ -165,9 +173,13 @@ class PenguinServer {
* handlers).
*/
applyPersistedProxy(): void {
+ const settings = this.deps.tree.api<ServerSettingsRepo>(
+ "ServerSettingsRepo",
+ "ServerSettingsRepo",
+ );
applyProxySettings({
- proxyForApp: this.deps.serverSettingsRepo.getProxyForApp(),
- proxyUrl: this.deps.serverSettingsRepo.getProxyUrl(),
+ proxyForApp: settings.getProxyForApp(),
+ proxyUrl: settings.getProxyUrl(),
});
}
@@ -194,12 +206,12 @@ class PenguinServer {
* plaintext must not keep holding it (see initial-password.ts).
*/
async seedAdmin(): Promise<void> {
- await this.deps.authService.seedAdmin();
+ await this.auth().seedAdmin();
clearInitialAdminPassword(this.config.root);
if (this.config.desktopToken !== null) return;
- if (!this.deps.authService.adminPasswordIsInitial()) return;
+ if (!this.auth().adminPasswordIsInitial()) return;
const pinned = this.config.seedAdminPassword;
- if (pinned !== null && (await this.deps.authService.adminPasswordIs(pinned))) return;
+ if (pinned !== null && (await this.auth().adminPasswordIs(pinned))) return;
this.pendingFirstLoginNotice = true;
}
@@ -251,7 +263,9 @@ class PenguinServer {
// 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" });
+ this.deps.tree
+ .api<ErrorRecorder>("ErrorRecorder", "ErrorRecorder")
+ .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
@@ -263,7 +277,9 @@ class PenguinServer {
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" });
+ this.deps.tree
+ .api<ErrorRecorder>("ErrorRecorder", "ErrorRecorder")
+ .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 +
@@ -310,7 +326,7 @@ class PenguinServer {
if (this.pendingFirstLoginNotice) {
// Minting here rather than at seed time is what keeps "exists" and "was printed" the
// same thing for a setup session: the modes that decline to print never ask for one.
- const link = this.deps.authService.mintFirstLogin();
+ const link = this.auth().mintFirstLogin();
if (link !== null) {
const token = encodeURIComponent(link);
console.log(
@@ -364,7 +380,7 @@ class PenguinServer {
private terminalWebSocketDeps() {
return {
hmr: this.deps.hmr,
- authService: this.deps.authService,
+ authService: this.auth(),
log: (line: string) => console.log(line),
};
}
diff --git a/packages/server/src/machines/service.ts b/packages/server/src/machines/service.ts
index 899dfc6a..1988cf99 100644
--- a/packages/server/src/machines/service.ts
+++ b/packages/server/src/machines/service.ts
@@ -56,7 +56,18 @@ import { syncModelsToMachine } from "./models-sync.js";
import type { LocalModels } from "./models-sync.js";
import { machineApi } from "./machine-api.js";
import { startRemoteServer, stopRemoteServer } from "./server-control.js";
-import type { MachineRow, MachinesRepo } from "../db/repos/machines.js";
+import type { MachineRow } from "../db/repos/machines.js";
+import { Interface, Bind, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";
+import type { AppEnv } from "../auth/middleware.js";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
+import { Config, Hmr, Overrides, RuntimeModule, Db } from "../hmr/capabilities.js";
+import { machinesRoutes } from "../http/routes/machines.js";
+import { machinesProxy } from "./proxy.js";
+import { HttpError } from "../http/errors.js";
+import type { ProjectAccess } from "../services/project-access.js";
+import { Hono } from "hono";
+import { MachinesRepo } from "../db/repos/machines.js";
+import type { DatabaseSync } from "node:sqlite";
/** Why an install was refused before any ssh ran. */
type InstallRefusal = "busy" | "unknown-machine" | "no-image" | "self";
@@ -1119,3 +1130,82 @@ export class MachinesService {
);
}
}
+
+export abstract class Machines extends Interface<
+ Pick<
+ MachinesService,
+ "list" | "imageVersion" | "job" | "startInstall" | "start" | "syncModelsEverywhere"
+ >
+>() {}
+
+@Module({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "MachinesModule.routes",
+ prefix: "/api/projects/:projectId/machines",
+ auth: "user",
+ order: 50,
+ },
+ {
+ id: "MachinesModule.server-proxy",
+ // The manifest is data: the literal, not machines/proxy.ts's SERVER_PROXY_PREFIX,
+ // which the generator reads statically and cannot follow.
+ prefix: "/server/",
+ auth: "user",
+ order: 51,
+ },
+ ],
+ },
+})
+export class MachinesModule {
+ @Use(RuntimeModule) private readonly config!: Config;
+ @Use(RuntimeModule) private readonly db!: Db;
+ @Use(RuntimeModule) private readonly hmr!: Hmr;
+ @Use(RuntimeModule) private readonly overrides!: Overrides;
+ @Use() private readonly access!: ProjectAccess;
+ @Provide() machines!: Machines;
+ @Bind("MachinesModule.routes") routes!: Hono<AppEnv>;
+ @Bind("MachinesModule.server-proxy") serverProxyRoutes!: Hono<AppEnv>;
+ setup({ effect }: ClassCtx) {
+ // This machine's own id is minted on the first boot of this data root and stable ever
+ // after — every stored reference to this machine, here and on the machines it reaches,
+ // points at it. A test that supplies its own service mints none.
+ const machines =
+ this.overrides.value().machines ??
+ (() => {
+ const repo = new MachinesRepo(this.db as unknown as DatabaseSync);
+ return new MachinesService(this.config.root, repo.ownId(), repo, {}, () =>
+ this.hmr.assetsDir(),
+ );
+ })();
+ this.machines = machines;
+ this.routes = machinesRoutes({ machines, access: this.access });
+ this.serverProxyRoutes = serverProxyApp(machines);
+ // Every ssh session THIS generation opened closes with it; the successor's setup
+ // re-holds each one the install record says was held.
+ effect(() => machines.stop());
+ }
+}
+
+/**
+ * `/server/<machineId>/api/…` — a connected machine's API, forwarded over the connection held
+ * to it and addressed by the machine's OWN id. Admins only: the request is made over there as
+ * that machine's admin, with a session this server minted over the ssh access that installed
+ * it, so this server's admin session is the one credential involved.
+ */
+function serverProxyApp(machines: MachinesService): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+ const proxy = machinesProxy(
+ (machineId) => machines.proxyTarget(machineId),
+ (machineId, outcome) => machines.noteApiSeen(machineId, outcome),
+ );
+ app.all("*", async (c) => {
+ if (!c.var.user.isAdmin) {
+ throw new HttpError(403, "admin_required", "Only an admin can reach a machine's API.");
+ }
+ const answer = await proxy(c.req.raw);
+ return answer ?? c.notFound();
+ });
+ return app;
+}
diff --git a/packages/server/src/machines/upgrade.ts b/packages/server/src/machines/upgrade.ts
index fc0b4d9c..19916457 100644
--- a/packages/server/src/machines/upgrade.ts
+++ b/packages/server/src/machines/upgrade.ts
@@ -16,7 +16,7 @@ import http from "node:http";
import path from "node:path";
import zlib from "node:zlib";
import { machineApi } from "./machine-api.js";
-import { MATERIALIZED } from "../hmr/host.js";
+import { MATERIALIZED } from "../hmr/manifest.js";
/** Long enough for 8 MB over a slow link, plus the unpack, boot and commit on the far side. */
const APPLY_TIMEOUT_MS = 10 * 60_000;
diff --git a/packages/server/src/platform.ts b/packages/server/src/platform.ts
new file mode 100644
index 00000000..e3a0d3b1
--- /dev/null
+++ b/packages/server/src/platform.ts
@@ -0,0 +1,164 @@
+import { Component, Module, moduleDefOf, Use } from "@prismshadow/penguin-core/kernel";
+import type { ManifestTable, ModuleDef } from "@prismshadow/penguin-core/kernel";
+import table from "./ifaces.json" with { type: "json" };
+import type { RuntimeCapabilities } from "./hmr/capabilities.js";
+import { RuntimeModule } from "./hmr/capabilities.js";
+import { UsersRepo } from "./db/repos/users.js";
+import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";
+import { ServerSettingsRepo } from "./db/repos/server-settings.js";
+import { UiPrefsRepo } from "./db/repos/ui-prefs.js";
+import { SessionsRepo } from "./db/repos/sessions.js";
+import { ProjectsRepo } from "./db/repos/projects.js";
+import { MembersRepo } from "./db/repos/members.js";
+import { AgentsRepo } from "./db/repos/agents.js";
+import { UsageRepo } from "./db/repos/usage.js";
+import { SchedulesRepo } from "./db/repos/schedules.js";
+import { TraceIndexRepo } from "./db/repos/trace-index.js";
+import { MessagingBindingsRepo } from "./db/repos/messaging-bindings.js";
+import { ErrorsRepo } from "./db/repos/errors.js";
+import { SessionSources } from "./runtime/session-sources.js";
+import { ErrorRecorder } from "./runtime/error-recorder.js";
+import { UsageRecorder } from "./runtime/usage-recorder.js";
+import { UsageService } from "./services/usage-service.js";
+import { ProjectConfigService } from "./services/project-config-service.js";
+import { ModelOAuthService } from "./services/model-oauth-service.js";
+import { TraceIndexService } from "./services/trace-index.js";
+import { TraceService } from "./services/trace-service.js";
+import { WorkspaceFilesService } from "./services/workspace-files-service.js";
+import { ProjectAccess } from "./services/project-access.js";
+import { ProjectService } from "./services/project-service.js";
+import { AuthService } from "./auth/service.js";
+import { AdminService } from "./services/admin-service.js";
+import { Scheduler } from "./runtime/scheduler.js";
+import { AgentConfigService } from "./services/agent-config-service.js";
+import { SnapshotService } from "./services/snapshot-service.js";
+import { AgentRoutes } from "./services/agent-routes.js";
+import { AgentService } from "./services/agent-service.js";
+import { MemoryService } from "./services/memory-service.js";
+import { BenchmarkService } from "./services/benchmark-service.js";
+import { ProjectsRoutes } from "./http/routes/dirs.js";
+import { WorkspaceModule } from "./http/routes/preview.js";
+import { SandboxModule } from "./sandbox/service.js";
+import { SessionServiceIface, SessionsModule } from "./runtime/session-manager.js";
+import { SchedulerRoutes } from "./http/routes/schedules.js";
+import { MessagingModule } from "./runtime/messaging/bridge.js";
+import { MachinesModule } from "./machines/service.js";
+import { ProjectAdminRoutes } from "./http/routes/projects.js";
+import { AdminRoutes } from "./http/routes/admin.js";
+import { MeRoutes } from "./http/routes/me.js";
+import { VersionModule } from "./services/update-check-service.js";
+import { InstallRoutes } from "./http/routes/install.js";
+import { EventsRoutes } from "./http/routes/events.js";
+import { PluginRoutes } from "./http/routes/plugins.js";
+import { TerminalModule } from "./terminal/manager.js";
+import { SessionApiRoutes } from "./http/routes/sessions.js";
+import { HttpModule } from "./http/app.js";
+import { WebModule } from "./http/routes/contributions.js";
+
+/**
+ * The platform's module tree: the root module and its children, in one place.
+ *
+ * The root provides nothing and requires nothing itself; it exists so the children have a
+ * scope to see each other in, and its create() — which runs LAST, after every child — does
+ * the App-wide steps that need the whole tree up (the trace
+ * adoption sweep, the machine sweeps). Everything else a module used to reach through
+ * `AppDeps` it now names in its manifest.
+ */
+
+/**
+ * The App-wide steps that need the whole business tree up, as a component of its own:
+ * requiring what it sweeps puts it after those nodes in dependency order, and typed by
+ * their classes — nothing reaches into a sibling by name.
+ */
+@Component()
+export class Startup {
+ @Use() private readonly scheduler!: Scheduler;
+ @Use(SessionsModule) private readonly sessionService!: SessionServiceIface;
+ @Use() private readonly errors!: ErrorRecorder;
+
+ async setup() {
+ // Schedule scheduler: startup reconciliation (missed, don't backfill) + periodic scan.
+ await this.scheduler.start();
+ // Startup adoption sweep: fold Trace-only Sessions into the index. Fire-and-forget —
+ // a broken trace shard must not block the boot.
+ void this.sessionService.adoptUnmanagedTraceSessions().catch((err: unknown) => {
+ this.errors.record({ source: "process", err, code: "trace_adoption_failed" });
+ });
+ }
+}
+
+/** The root: provides nothing and requires nothing; it exists so the children have a scope to see each other in. */
+@Module({
+ children: [
+ RuntimeModule,
+ // Stores
+ UsersRepo,
+ AuthSessionsRepo,
+ ServerSettingsRepo,
+ UiPrefsRepo,
+ SessionsRepo,
+ ProjectsRepo,
+ MembersRepo,
+ AgentsRepo,
+ UsageRepo,
+ SchedulesRepo,
+ TraceIndexRepo,
+ MessagingBindingsRepo,
+ ErrorsRepo,
+ SessionSources,
+ // Services
+ ErrorRecorder,
+ UsageRecorder,
+ UsageService,
+ ProjectConfigService,
+ ModelOAuthService,
+ TraceIndexService,
+ TraceService,
+ WorkspaceFilesService,
+ ProjectAccess,
+ ProjectService,
+ AuthService,
+ AdminService,
+ Scheduler,
+ AgentConfigService,
+ SnapshotService,
+ AgentService,
+ MemoryService,
+ BenchmarkService,
+ AgentRoutes,
+ // Runtimes and route groups
+ WorkspaceModule,
+ SandboxModule,
+ SessionsModule,
+ MessagingModule,
+ MachinesModule,
+ ProjectsRoutes,
+ SchedulerRoutes,
+ ProjectAdminRoutes,
+ AdminRoutes,
+ MeRoutes,
+ VersionModule,
+ InstallRoutes,
+ EventsRoutes,
+ PluginRoutes,
+ TerminalModule,
+ SessionApiRoutes,
+ WebModule,
+ HttpModule,
+ Startup,
+ ],
+})
+export class PlatformModule {}
+
+/** The platform tree as the booter takes it: the runtime adapter pre-built over the claimed capabilities, plugin modules appended under the root. */
+export function platformDef(
+ caps: RuntimeCapabilities,
+ adoptable: (group: string) => boolean,
+ plugins: ModuleDef[] = [],
+): ModuleDef {
+ return moduleDefOf(PlatformModule, {
+ manifests: table.modules as ManifestTable,
+ instances: new Map([[RuntimeModule, new RuntimeModule(caps, adoptable)]]),
+ extra: plugins,
+ });
+}
diff --git a/packages/server/src/plugin/host.ts b/packages/server/src/plugin/host.ts
index 91f74feb..1ff43f76 100644
--- a/packages/server/src/plugin/host.ts
+++ b/packages/server/src/plugin/host.ts
@@ -1,105 +1,59 @@
/**
- * The plugin host: it owns activation, event delivery and disposal. Kept out of
- * ./index.ts so the published `@prismshadow/penguin-server/plugin` subpath stays types
- * only — a plugin package cannot take a runtime dependency on the harness even by
- * accident, which is what keeps it a self-contained library.
+ * The plugin host: the plugins this process loaded, as module definitions the
+ * platform boots as children of its tree. Kept out of ./index.ts so the published
+ * `@prismshadow/penguin-server/plugin` subpath stays types only.
*/
-import type { Resources } from "@prismshadow/penguin-core/kernel";
-import type { Disposable, Plugin, PluginEvents } from "@prismshadow/penguin-core/plugin";
+import type { IfaceTable, ModuleDef, Resources } from "@prismshadow/penguin-core/kernel";
-interface ActivatedPlugin {
- handlers: { [E in keyof PluginEvents]?: Array<(payload: PluginEvents[E]) => void> };
- disposables: Disposable[];
+/** One loaded plugin: the package, its modules with manifests paired to code, and its generated table. */
+export interface LoadedPlugin {
+ specifier: string;
+ modules: ModuleDef[];
+ /** The interfaces and types the package's `ifaces.json` carries; absent for a module built in code. */
+ ifaces?: IfaceTable;
}
-/** One host per server process; activation order is delivery order. */
+/** One host per server process; load order is the order the modules join the tree. */
export class PluginHost {
- private readonly plugins: ActivatedPlugin[] = [];
+ private readonly plugins: LoadedPlugin[] = [];
- /**
- * Runs `activate` (awaiting it when async), then seals its subscription window.
- *
- * TRANSACTIONAL: a plugin 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(plugin: Plugin): Promise<void> {
- const entry: ActivatedPlugin = { handlers: {}, disposables: [] };
- let sealed = false;
- try {
- await plugin.activate({
- on<E extends keyof PluginEvents>(event: E, handler: (payload: PluginEvents[E]) => void) {
- if (sealed) {
- throw new Error(
- `plugin 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: PluginEvents[E]) => void>;
- list.push(handler);
- },
- disposables: entry.disposables,
- });
- } catch (err) {
- sealed = true;
- await runDisposables(entry.disposables);
- throw err;
+ /** Registers a plugin; a module name already taken by an earlier plugin is refused. */
+ use(plugin: LoadedPlugin): void {
+ const taken = new Set(this.modules().map((m) => m.manifest.name));
+ for (const m of plugin.modules) {
+ if (taken.has(m.manifest.name)) {
+ throw new Error(
+ `plugin '${plugin.specifier}': module '${m.manifest.name}' is already loaded by another plugin`,
+ );
+ }
}
- sealed = true;
- Object.freeze(entry.disposables);
- this.plugins.push(entry);
+ this.plugins.push(plugin);
}
- emit<E extends keyof PluginEvents>(event: E, payload: PluginEvents[E]): void {
- for (const plugin of this.plugins) {
- for (const handler of plugin.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(
- `plugin handler for '${event}' returned a promise — event handlers must be ` +
- `synchronous (do async work in activate, or start it without awaiting)`,
- );
- }
- }
- }
+ /** Every plugin module, in load order — what the platform adds to its tree. */
+ modules(): readonly ModuleDef[] {
+ return this.plugins.flatMap((e) => e.modules);
}
/**
- * 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.
+ * The host's table with every plugin's folded in — what the tree is checked against. On
+ * a key both carry (a plugin's table copies the host interfaces it compiled against) the
+ * host's entry stands: it is what is provided, and what a hand-written manifest was
+ * always looked up in.
*/
- async dispose(): Promise<void> {
- const plugins = this.plugins.splice(0);
- await runDisposables(plugins.flatMap((plugin) => [...plugin.disposables]));
+ ifaces(host: IfaceTable): IfaceTable {
+ const ifaces = { ...host.ifaces };
+ const types = { ...host.types };
+ for (const plugin of this.plugins) {
+ if (plugin.ifaces === undefined) continue;
+ for (const [key, decl] of Object.entries(plugin.ifaces.ifaces)) ifaces[key] ??= decl;
+ for (const [key, decl] of Object.entries(plugin.ifaces.types)) types[key] ??= decl;
+ }
+ return { ifaces, types };
}
-}
-/** Concurrent, failure-isolated teardown — see {@link PluginHost.dispose}. */
-async function runDisposables(disposables: readonly Disposable[]): Promise<void> {
- await Promise.all(
- disposables.map(async (disposable) => {
- try {
- await disposable.dispose();
- } catch (err) {
- console.warn(
- `[plugins] disposer failed: ${err instanceof Error ? err.message : String(err)}`,
- );
- }
- }),
- );
+ /** Nothing to release at process exit: modules dispose with the App that created them. */
+ dispose(): void {}
}
/** Registry key the runtime publishes its loaded host under. */
diff --git a/packages/server/src/plugin/index.ts b/packages/server/src/plugin/index.ts
index eec27358..1deb2173 100644
--- a/packages/server/src/plugin/index.ts
+++ b/packages/server/src/plugin/index.ts
@@ -1,30 +1,20 @@
/**
- * What this harness offers a plugin BEYOND the contract — the
- * `@prismshadow/penguin-server/plugin` subpath.
+ * The harness's plugin surface — the `@prismshadow/penguin-server/plugin` subpath.
*
- * The contract is `@prismshadow/penguin-core/plugin` and is CLOSED: this module does not
- * reopen it by declaration merging. Augmenting it would put `terminals` into the contract
- * itself, so a plugin type-checking against core would compile against a member only
- * THIS embedder supplies, with nothing at the core layer able to say so.
- *
- * What the harness offers beyond the contract is named here instead, on an interface that
- * EXTENDS it. Values of that type still satisfy the contract, so the seam is unchanged;
- * what changes is that a plugin wanting `terminals` writes the cast itself
- * (`ctx as HarnessContext`) and thereby states, at the point of use, that it depends on
- * running inside this harness rather than on any embedder.
- *
- * Nor does this module re-export the contract. A plugin imports the contract from core
- * and this subpath only for what its name promises, so a package's import sites say which
- * of the two it actually needs: a sandbox backend, written against the sandbox vocabulary
- * and nothing else, names core alone and does not depend on this package at all.
- */
-import type { PenguinContext } from "@prismshadow/penguin-core/plugin";
-import type { TerminalManager } from "../terminal/manager.js";
-
-/**
- * The instance view this harness actually hands to `"create"` handlers: the contract plus
- * the members only it owns. A plugin reaching `terminals` casts to this deliberately.
+ * The contract is `@prismshadow/penguin-core/plugin` (a plugin is a set of
+ * modules) and this module does not re-export it: a plugin imports the contract from
+ * core and this subpath only for what its name promises, so a package's import sites say
+ * which of the two it needs — a sandbox backend, written against the sandbox vocabulary
+ * and nothing else, names core alone. What the harness adds is the set of INTERFACES an
+ * plugin module may require — a component class (`AgentService`, whose public surface
+ * is its contract) or an abstract interface class (`extends Interface<…>()`) declared
+ * beside its owner — reachable as `<module>#<Export>` in a manifest's `requires`. Types only.
*/
-export interface HarnessContext extends PenguinContext {
- terminals: TerminalManager;
-}
+export type { Sandbox, SandboxSlots } from "../sandbox/service.js";
+export type { Terminals } from "../terminal/manager.js";
+export type { Sessions, SessionServiceIface } from "../runtime/session-manager.js";
+export type { AgentService } from "../services/agent-service.js";
+export type { AgentConfigService } from "../services/agent-config-service.js";
+export type { Messaging, MessagingSlots } from "../runtime/messaging/bridge.js";
+export type { Http, HttpSlots } from "../http/app.js";
+export type { WebShell, WebShellSlots } from "../http/routes/contributions.js";
diff --git a/packages/server/src/plugin/loader.ts b/packages/server/src/plugin/loader.ts
index 0593ab9e..d07fdf08 100644
--- a/packages/server/src/plugin/loader.ts
+++ b/packages/server/src/plugin/loader.ts
@@ -9,28 +9,29 @@
* its own, so anchoring at the bundle would find nothing.
*
* Failure is per-entry and non-fatal: an unresolvable or malformed plugin is reported
- * and skipped, leaving its capability unavailable rather than failing the boot.
+ * and skipped, leaving its capability unavailable rather than failing the boot. A
+ * plugin is a set of modules (core plugin/index.ts): decorated classes, named by the
+ * default export, whose manifests the package's generated `ifaces.json` carries.
*/
import fs from "node:fs/promises";
import { createRequire } from "node:module";
import path from "node:path";
import { pathToFileURL } from "node:url";
+import type { IfaceTable, ManifestTable, ModuleDef } from "@prismshadow/penguin-core/kernel";
+import { moduleDefOf, parseManifest } from "@prismshadow/penguin-core/kernel";
import type { Plugin } from "@prismshadow/penguin-core/plugin";
+import type { LoadedPlugin } from "./host.js";
/** The config file's name inside the data root. */
export const PLUGINS_FILE = "plugins.json";
-export interface LoadedPlugin {
- specifier: string;
- plugin: Plugin;
-}
+export type { LoadedPlugin } from "./host.js";
export interface PluginLoadResult {
loaded: LoadedPlugin[];
/** specifier → why it was skipped. */
failed: Map<string, string>;
}
-
/**
* An ABSENT file means "no plugins" — the default deployment shape, not an error. Any
* other outcome is: a file that exists but cannot be read (a permission, a directory in
@@ -64,30 +65,87 @@ export async function readPluginList(root: string): Promise<string[]> {
}
/** Resolved against the installation rather than the bundle's location. */
-async function importPlugin(specifier: string): Promise<unknown> {
+async function importPlugin(specifier: string): Promise<{ module: unknown; file: string | null }> {
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);
+ return { module: await import(pathToFileURL(resolved).href), file: resolved };
} catch {
// Fall through: a dev checkout resolves the specifier directly.
}
}
- return await import(specifier);
+ return { module: await import(specifier), file: null };
+}
+
+/** The generated table a plugin package ships beside its package.json. */
+export const IFACES_FILE = "ifaces.json";
+
+/**
+ * The package's generated table (`ifaces.json` beside its `package.json`, the nearest one
+ * above the resolved entry file): the manifest of every decorated class, the signature of
+ * every interface they name. A package is a plugin by being listed; the table is its
+ * MODULE payload, and a package without one ships no modules (`manifests` empty). Null
+ * only when no `package.json` is above the file at all.
+ */
+async function readPackageTable(
+ file: string | null,
+): Promise<{ where: string; ifaces: IfaceTable; manifests: ManifestTable } | null> {
+ if (file === null) return null;
+ let dir = path.dirname(file);
+ for (;;) {
+ const where = path.join(dir, "package.json");
+ try {
+ await fs.access(where);
+ const tableFile = path.join(dir, IFACES_FILE);
+ let text: string;
+ try {
+ text = await fs.readFile(tableFile, "utf8");
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
+ return { where, ifaces: { ifaces: {}, types: {} }, manifests: {} };
+ }
+ const table = JSON.parse(text) as {
+ ifaces?: unknown;
+ types?: unknown;
+ modules?: unknown;
+ };
+ const isRecord = (v: unknown) => typeof v === "object" && v !== null && !Array.isArray(v);
+ if (!isRecord(table.ifaces) || !isRecord(table.types) || !isRecord(table.modules)) {
+ throw new Error(`${tableFile}: expected { ifaces, types, modules } (gen-ifaces output)`);
+ }
+ const manifests: Record<string, ModuleDef["manifest"]> = {};
+ for (const [name, doc] of Object.entries(table.modules as Record<string, unknown>)) {
+ manifests[name] = parseManifest(doc, `${tableFile}#modules.${name}`);
+ }
+ return {
+ where,
+ ifaces: { ifaces: table.ifaces, types: table.types } as IfaceTable,
+ manifests,
+ };
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) return null;
+ dir = parent;
+ }
}
-/** A plugin module's contract is one named export: `activate(ctx)`. */
+/** The package's default export as a Plugin, or null when it is not one. */
function asPlugin(module: unknown): Plugin | null {
- const activate = (module as { activate?: unknown }).activate;
- return typeof activate === "function" ? { activate: activate as Plugin["activate"] } : null;
+ const def = (module as { default?: unknown }).default;
+ const modules = (def as { modules?: unknown } | null)?.modules;
+ return Array.isArray(modules) && modules.every((m) => typeof m === "function")
+ ? (def as Plugin)
+ : null;
}
/**
* Loads every configured plugin.
*
* 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
+ * specifier, no table, 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
@@ -100,12 +158,39 @@ export async function loadPlugins(root: string): Promise<PluginLoadResult> {
const loaded: LoadedPlugin[] = [];
for (const specifier of specifiers) {
try {
- const plugin = asPlugin(await importPlugin(specifier));
+ const { module, file } = await importPlugin(specifier);
+ const read = await readPackageTable(file);
+ if (read === null) {
+ failed.set(specifier, `no package.json above ${file}`);
+ continue;
+ }
+ const plugin = asPlugin(module);
if (plugin === null) {
- failed.set(specifier, "module does not export an activate(ctx) function");
+ failed.set(
+ specifier,
+ "the default export is not a Plugin ({ modules: [<@Component or @Module class>, …] })",
+ );
continue;
}
- loaded.push({ specifier, plugin });
+ if (plugin.modules.length > 0 && Object.keys(read.manifests).length === 0) {
+ // Classes named, no table: the package was not built (gen-ifaces runs in its build).
+ throw new Error(
+ `the default export names module classes, but ${path.join(path.dirname(read.where), IFACES_FILE)} is missing — build the package`,
+ );
+ }
+ const modules: ModuleDef[] = [];
+ const seen = new Set<string>();
+ for (const cls of plugin.modules) {
+ // The class is checked against its generated manifest here (a stale table is a
+ // named error); the manifest is checked against the tree at boot.
+ const def = moduleDefOf(cls, { manifests: read.manifests });
+ if (seen.has(def.manifest.name)) {
+ throw new Error(`the default export lists module '${def.manifest.name}' twice`);
+ }
+ seen.add(def.manifest.name);
+ modules.push(def);
+ }
+ loaded.push({ specifier, modules, ifaces: read.ifaces });
} catch (err) {
failed.set(specifier, err instanceof Error ? err.message : String(err));
}
diff --git a/packages/server/src/plugin/workflow.ts b/packages/server/src/plugin/workflow.ts
deleted file mode 100644
index de7506f5..00000000
--- a/packages/server/src/plugin/workflow.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * Building the workflow instance view. The types are the SDK's contract
- * (`@prismshadow/penguin-core/plugin`); this is the harness's implementation of it.
- */
-import type {
- WorkflowFactory,
- WorkflowInstance,
- WorkflowInstances,
-} from "@prismshadow/penguin-core/plugin";
-
-/**
- * The Map handed to plugins 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 plugins.json ordering, and a plugin 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/reset-admin-password.ts b/packages/server/src/reset-admin-password.ts
index f5245647..311c4c52 100644
--- a/packages/server/src/reset-admin-password.ts
+++ b/packages/server/src/reset-admin-password.ts
@@ -16,6 +16,7 @@ import { AuthSessionsRepo } from "./db/repos/auth-sessions.js";
import { clearInitialAdminPassword } from "./initial-password.js";
import { liveServerLock } from "./lock.js";
import type { ServerLock } from "./lock.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
export type ResetAdminPasswordResult =
/** Refused: a live server owns this data root (stop it first — web.db is single-writer). */
@@ -39,12 +40,12 @@ export async function resetAdminPassword(
if (!fs.existsSync(dbPath)) return { outcome: "no_database", dbPath };
const db = openDatabase(dbPath);
try {
- const users = new UsersRepo(db);
+ const users = wire(UsersRepo, { db: db });
if (users.findById(ADMIN_USER_ID) === null) return { outcome: "no_admin" };
// Discarded unread: a value nobody holds cannot be typed, phished, or left in a buffer.
const password = generateInitialAdminPassword();
users.updatePassword(ADMIN_USER_ID, await hashPassword(password), true);
- new AuthSessionsRepo(db).deleteByUser(ADMIN_USER_ID);
+ wire(AuthSessionsRepo, { db: db }).deleteByUser(ADMIN_USER_ID);
clearInitialAdminPassword(root);
return { outcome: "reset" };
} finally {
diff --git a/packages/server/src/runtime/error-recorder.ts b/packages/server/src/runtime/error-recorder.ts
index 0d3ff932..e682fc88 100644
--- a/packages/server/src/runtime/error-recorder.ts
+++ b/packages/server/src/runtime/error-recorder.ts
@@ -54,6 +54,8 @@
import { formatLocalDate } from "../internal/dates.js";
import { HttpError } from "../http/errors.js";
import type { ErrorsRepo } from "../db/repos/errors.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Overrides } from "../hmr/capabilities.js";
/** Capture-site source (maps one-to-one to error_records.source). */
export type ErrorSource =
@@ -106,14 +108,18 @@ function messageOf(err: unknown): string {
return raw.length > MESSAGE_MAX ? raw.slice(0, MESSAGE_MAX) : raw;
}
+@Component()
export class ErrorRecorder {
/** Dedup table: `source \0 code \0 projectId` → timestamp of the last **persist** (see file header). */
private readonly lastSeen = new Map<string, number>();
- constructor(
- private readonly errors: ErrorsRepo,
- private readonly now: () => Date = () => new Date(),
- ) {}
+ @Use() private readonly errors!: ErrorsRepo;
+ @Use() private readonly overrides!: Overrides;
+ private now: () => Date = () => new Date();
+
+ setup(): void {
+ this.now = this.overrides.value().now ?? this.now;
+ }
/** Record an error (synchronous, fails silently; same-window duplicates are dropped outright, see file header). */
record(args: ErrorRecordArgs): void {
diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.ts
index 51b9a947..adacd987 100644
--- a/packages/server/src/runtime/messaging/bridge.ts
+++ b/packages/server/src/runtime/messaging/bridge.ts
@@ -77,13 +77,13 @@ import type {
MessagingBindingRow,
MessagingBindingsRepo,
} from "../../db/repos/messaging-bindings.js";
-import { INLINE_IMAGE_MAX_BYTES } from "../../services/attachment-limits.js";
+import { INLINE_IMAGE_MAX_BYTES, toAttachmentLimits } from "../../services/attachment-limits.js";
import type { AttachmentLimits } from "../../services/attachment-limits.js";
import { attachFilesToInput, removeAttachments } from "../../services/task-attachments.js";
import type { AttachedFiles, TaskAttachment } from "../../services/task-attachments.js";
import type { ChannelEvent, ChannelHub } from "../channel.js";
-import type { ErrorSink } from "../error-recorder.js";
-import { recallStoreOf } from "../session-manager.js";
+import type { ErrorSink, ErrorRecorder } from "../error-recorder.js";
+import { recallStoreOf, SessionsModule } from "../session-manager.js";
import type { RecallStore } from "../session-manager.js";
import type {
MessagingChannelConnector,
@@ -97,6 +97,23 @@ import { messagingErrorKind } from "./error-kind.js";
import { chunkMarkdown } from "./markdown.js";
import { MessagingMediaTooLargeError, MessagingPermissionError, isImageFileName } from "./media.js";
import { replyFileMentions } from "./reply-files.js";
+import { Interface, Bind, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";
+import type { Slot, ClassCtx } from "@prismshadow/penguin-core/kernel";
+import { QQScanService, createQQScanTransport } from "./qq-scan.js";
+import type { AppEnv } from "../../auth/middleware.js";
+import { Hono } from "hono";
+import { Channels, Config, Log, Overrides, RuntimeModule } from "../../hmr/capabilities.js";
+import { WorkspaceModule } from "../../http/routes/preview.js";
+import { FeishuMessaging } from "./feishu-connector.js";
+import { TelegramMessaging } from "./telegram-connector.js";
+import { QqMessaging } from "./qq-connector.js";
+import { WechatMessaging } from "./wechat-connector.js";
+import { WeChatScanService, createWeChatScanTransport } from "./wechat-scan.js";
+import type { SessionsRepo } from "../../db/repos/sessions.js";
+import type { WorkspaceFilesService } from "../../services/workspace-files-service.js";
+import type { ProjectAccess } from "../../services/project-access.js";
+import { sessionMessagingRoutes } from "../../http/routes/messaging.js";
+import type { ServerSettingsRepo } from "../../db/repos/server-settings.js";
/**
* Max characters per outbound text message, shared by every channel: it must sit under
@@ -554,7 +571,7 @@ function inboundRecallStore(
}
/** Minimal dependency on SessionManager (eases test doubles; mirrors ScheduleTaskRunner). */
-export interface MessagingTaskRunner {
+export interface MessagingTaskRunnerShape {
statusOf(sessionId: string): string;
startTask(
sessionId: string,
@@ -1845,3 +1862,108 @@ export class MessagingBridge {
return new Promise((resolve) => setTimeout(resolve, this.lineDelayMs));
}
}
+
+/** What the bridge needs of the session runtime — declared at the consumer. */
+export abstract class MessagingTaskRunner extends Interface<MessagingTaskRunnerShape>() {}
+
+/** The chat-channel bridge: bindings, delivery, status. */
+export abstract class Messaging extends Interface<
+ Pick<
+ MessagingBridge,
+ | "start"
+ | "stop"
+ | "sync"
+ | "unbind"
+ | "unbindSession"
+ | "statusOf"
+ | "testCredentials"
+ | "sendTestMessage"
+ >
+>() {}
+
+export abstract class QQScan extends Interface<
+ Pick<QQScanService, "start" | "poll" | "cancel" | "cancelSession">
+>() {}
+
+export interface MessagingSlots {
+ /** A channel connector: which channel it speaks (static), and the connector (code). */
+ connectors: Slot<{ channel: "feishu" | "telegram" | "qq" | "wechat" }, MessagingChannelConnector>;
+}
+
+@Module({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "messaging.session-routes",
+ prefix: "/api/sessions",
+ auth: "user",
+ order: 280,
+ },
+ ],
+ },
+ children: [FeishuMessaging, TelegramMessaging, QqMessaging, WechatMessaging],
+})
+export class MessagingModule {
+ @Use(RuntimeModule) private readonly config!: Config;
+ @Use(RuntimeModule) private readonly channels!: Channels;
+ @Use(RuntimeModule) private readonly overrides!: Overrides;
+ @Use(RuntimeModule) private readonly log!: Log;
+ @Use() private readonly messagingRepo!: MessagingBindingsRepo;
+ @Use() private readonly sessionsRepo!: SessionsRepo;
+ @Use() private readonly workspaceFiles!: WorkspaceFilesService;
+ @Use() private readonly settings!: ServerSettingsRepo;
+ @Use(SessionsModule) private readonly runner!: MessagingTaskRunner;
+ @Use() private readonly errors!: ErrorRecorder;
+ @Use() private readonly access!: ProjectAccess;
+ @Provide() messaging!: Messaging;
+ @Provide() qqScan!: QQScan;
+ @Bind("messaging.session-routes") sessionRoutesRoutes!: Hono<AppEnv>;
+ async setup({ contributions, effect }: ClassCtx) {
+ const overrides = this.overrides.value();
+ const messagingRepo = this.messagingRepo;
+ const sessionsRepo = this.sessionsRepo;
+ const messaging = new MessagingBridge({
+ repo: messagingRepo,
+ sessions: sessionsRepo,
+ files: this.workspaceFiles,
+ root: this.config.root,
+ attachmentLimits: () => toAttachmentLimits(this.settings.getAttachmentLimitsMb()),
+ channels: this.channels as ChannelHub,
+ runner: this.runner,
+ // Every connector arrives as a contribution — the built-in three from the child
+ // modules, and any other through the same slot.
+ connectors: (contributions.connectors ?? []).map((c) => c.code as MessagingChannelConnector),
+ errors: this.errors,
+ log: (line) => this.log.line(line),
+ ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),
+ ...(overrides.messagingLineDelayMs !== undefined
+ ? { lineDelayMs: overrides.messagingLineDelayMs }
+ : {}),
+ ...(overrides.messagingInboundImageBudgetBytes !== undefined
+ ? { inboundImageBudgetBytes: overrides.messagingInboundImageBudgetBytes }
+ : {}),
+ });
+ const qqScan = new QQScanService(overrides.qqScanTransport ?? createQQScanTransport(), {
+ ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),
+ });
+ // Same shape as the QQ one: what it holds is the handle that collects a bot token
+ // rather than a key that decrypts a secret, and is equally not worth persisting.
+ const wechatScan = new WeChatScanService(
+ overrides.wechatScanTransport ?? createWeChatScanTransport(),
+ { ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}) },
+ );
+ // Connect every enabled binding; only active while this App is.
+ await messaging.start();
+ effect(() => messaging.stop());
+ this.messaging = messaging;
+ this.qqScan = qqScan;
+ this.sessionRoutesRoutes = sessionMessagingRoutes({
+ messaging,
+ messagingRepo,
+ access: this.access,
+ qqScan,
+ wechatScan,
+ sessionsRepo,
+ });
+ }
+}
diff --git a/packages/server/src/runtime/messaging/feishu-connector.ts b/packages/server/src/runtime/messaging/feishu-connector.ts
index 09f6d3b4..e0ba4204 100644
--- a/packages/server/src/runtime/messaging/feishu-connector.ts
+++ b/packages/server/src/runtime/messaging/feishu-connector.ts
@@ -19,7 +19,10 @@ import type {
} from "./connector.js";
import { feishuCardOf } from "./feishu-card.js";
import type { FeishuApiClient, FeishuCredentials, FeishuMention, FeishuSdk } from "./feishu-sdk.js";
-import { FeishuApiError } from "./feishu-sdk.js";
+import { FeishuApiError, createLarkSdk } from "./feishu-sdk.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
+import { Overrides, RuntimeModule } from "../../hmr/capabilities.js";
/** Default Feishu open-platform domain (Lark tenants override it in the form). */
export const FEISHU_DEFAULT_DOMAIN = "https://open.feishu.cn";
@@ -311,3 +314,23 @@ export class FeishuConnector implements MessagingChannelConnector {
});
}
}
+
+/** The feishu connector, contributed to messaging.connectors like any third-party one would be. */
+@Component({
+ contributes: {
+ "MessagingModule.connectors": [
+ {
+ id: "messaging-feishu.connector",
+ channel: "feishu",
+ },
+ ],
+ },
+})
+export class FeishuMessaging {
+ @Use(RuntimeModule) private readonly overrides!: Overrides;
+ @Bind("messaging-feishu.connector") connector!: MessagingChannelConnector;
+ setup() {
+ const overrides = this.overrides.value();
+ this.connector = new FeishuConnector(overrides.feishuSdk ?? createLarkSdk());
+ }
+}
diff --git a/packages/server/src/runtime/messaging/qq-connector.ts b/packages/server/src/runtime/messaging/qq-connector.ts
index 9aaba2ce..010b35cb 100644
--- a/packages/server/src/runtime/messaging/qq-connector.ts
+++ b/packages/server/src/runtime/messaging/qq-connector.ts
@@ -89,8 +89,11 @@ import type {
QQInboundEvent,
QQTransport,
} from "./qq-api.js";
-import { QQ_BODY_INDEPENDENT_SEND_CODES, QQApiError } from "./qq-api.js";
+import { QQ_BODY_INDEPENDENT_SEND_CODES, QQApiError, createQQTransport } from "./qq-api.js";
import { qqMarkdownOf } from "./qq-markdown.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
+import { Overrides, RuntimeModule } from "../../hmr/capabilities.js";
/** The QQ binding's stored config document (`messaging_bindings.config_json`). */
export interface QQBindingConfig extends Record<string, unknown> {
@@ -629,3 +632,26 @@ export class QQConnector implements MessagingChannelConnector {
return result;
}
}
+
+/** The qq connector, contributed to messaging.connectors like any third-party one would be. */
+@Component({
+ contributes: {
+ "MessagingModule.connectors": [
+ {
+ id: "messaging-qq.connector",
+ channel: "qq",
+ },
+ ],
+ },
+})
+export class QqMessaging {
+ @Use(RuntimeModule) private readonly overrides!: Overrides;
+ @Bind("messaging-qq.connector") connector!: MessagingChannelConnector;
+ setup() {
+ const overrides = this.overrides.value();
+ this.connector = new QQConnector(overrides.qqTransport ?? createQQTransport(), {
+ ...(overrides.qqTailFlushMs !== undefined ? { tailFlushMs: overrides.qqTailFlushMs } : {}),
+ ...(overrides.now ? { now: () => overrides.now!().getTime() } : {}),
+ });
+ }
+}
diff --git a/packages/server/src/runtime/messaging/telegram-connector.ts b/packages/server/src/runtime/messaging/telegram-connector.ts
index b67acfb4..4ee96c13 100644
--- a/packages/server/src/runtime/messaging/telegram-connector.ts
+++ b/packages/server/src/runtime/messaging/telegram-connector.ts
@@ -58,7 +58,14 @@ import type {
TelegramTransport,
TelegramUpdate,
} from "./telegram-api.js";
-import { TELEGRAM_MAX_DOWNLOAD_BYTES, TelegramApiError } from "./telegram-api.js";
+import {
+ TELEGRAM_MAX_DOWNLOAD_BYTES,
+ TelegramApiError,
+ createTelegramTransport,
+} from "./telegram-api.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
+import { Overrides, RuntimeModule } from "../../hmr/capabilities.js";
/** The Telegram binding's stored config document (`messaging_bindings.config_json`). */
export interface TelegramBindingConfig extends Record<string, unknown> {
@@ -579,3 +586,26 @@ export class TelegramConnector implements MessagingChannelConnector {
}
}
}
+
+/** The telegram connector, contributed to messaging.connectors like any third-party one would be. */
+@Component({
+ contributes: {
+ "MessagingModule.connectors": [
+ {
+ id: "messaging-telegram.connector",
+ channel: "telegram",
+ },
+ ],
+ },
+})
+export class TelegramMessaging {
+ @Use(RuntimeModule) private readonly overrides!: Overrides;
+ @Bind("messaging-telegram.connector") connector!: MessagingChannelConnector;
+ setup() {
+ const overrides = this.overrides.value();
+ this.connector = new TelegramConnector(
+ overrides.telegramTransport ?? createTelegramTransport(),
+ overrides.telegramRetryDelayMs ? { retryDelayMs: overrides.telegramRetryDelayMs } : {},
+ );
+ }
+}
diff --git a/packages/server/src/runtime/messaging/wechat-connector.ts b/packages/server/src/runtime/messaging/wechat-connector.ts
index f70a485f..d37480dd 100644
--- a/packages/server/src/runtime/messaging/wechat-connector.ts
+++ b/packages/server/src/runtime/messaging/wechat-connector.ts
@@ -95,7 +95,9 @@ import type {
WeChatInboundEvent,
WeChatTransport,
} from "./wechat-api.js";
-import { WECHAT_API_BASE } from "./wechat-api.js";
+import { WECHAT_API_BASE, createWeChatTransport } from "./wechat-api.js";
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import { Overrides, RuntimeModule } from "../../hmr/capabilities.js";
/** The WeChat binding's stored config document (`messaging_bindings.config_json`). */
export interface WeChatBindingConfig extends Record<string, unknown> {
@@ -410,3 +412,26 @@ export class WeChatConnector implements MessagingChannelConnector {
});
}
}
+
+/** The wechat connector, contributed to messaging.connectors like any third-party one would be. */
+@Component({
+ contributes: {
+ "MessagingModule.connectors": [
+ {
+ id: "messaging-wechat.connector",
+ channel: "wechat",
+ },
+ ],
+ },
+})
+export class WechatMessaging {
+ @Use(RuntimeModule) private readonly overrides!: Overrides;
+ @Bind("messaging-wechat.connector") connector!: MessagingChannelConnector;
+ setup() {
+ const overrides = this.overrides.value();
+ this.connector = new WeChatConnector(
+ overrides.wechatTransport ?? createWeChatTransport(),
+ overrides.wechatRetryDelayMs ? { retryDelayMs: overrides.wechatRetryDelayMs } : {},
+ );
+ }
+}
diff --git a/packages/server/src/runtime/scheduler.ts b/packages/server/src/runtime/scheduler.ts
index b889e764..e6be0722 100644
--- a/packages/server/src/runtime/scheduler.ts
+++ b/packages/server/src/runtime/scheduler.ts
@@ -26,18 +26,23 @@ import type { ProjectsRepo } from "../db/repos/projects.js";
import type { SchedulesRepo, ScheduleStateRow } from "../db/repos/schedules.js";
import type { SessionsRepo } from "../db/repos/sessions.js";
import { cacheable, statMtime } from "../internal/mtime-gate.js";
-import type { ErrorSink } from "./error-recorder.js";
+import type { ErrorSink, ErrorRecorder } from "./error-recorder.js";
import type { ScheduleDefinition } from "./schedule-file.js";
import { latestSlotAt, slotInWindow } from "./schedule-file.js";
import { ScheduleFileCache, readScheduleFile, validateScheduleModelRef } from "./schedule-store.js";
import type { ScheduleConfigSource } from "./schedule-store.js";
import type { ScheduleServerEvent } from "../api/types.js";
+import { Component, Interface, Use } from "@prismshadow/penguin-core/kernel";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
+import type { Channels, Config, Overrides } from "../hmr/capabilities.js";
+import type { ProjectConfigService } from "../services/project-config-service.js";
+import { userChannelKey } from "../http/routes/events.js";
/** Reconcile and fire-check interval (min period is 5m, so 30s granularity is plenty). */
const TICK_INTERVAL_MS = 30_000;
/** Minimal dependency the scheduler needs from SessionManager (eases test doubles). */
-export interface ScheduleTaskRunner {
+export interface ScheduleTaskRunnerShape {
statusOf(sessionId: string): string;
startTask(
sessionId: string,
@@ -46,7 +51,7 @@ export interface ScheduleTaskRunner {
}
/** Minimal dependency the scheduler needs from SessionService: new-Session mode (model ref passed through as a pair). */
-export interface ScheduleSessionCreator {
+export interface ScheduleSessionCreatorShape {
createSession(args: {
projectId: string;
agentId: string;
@@ -57,6 +62,10 @@ export interface ScheduleSessionCreator {
}): Promise<{ sessionId: string }>;
}
+/** What the scheduler needs of the session runtime — declared here, at the consumer (Go style). */
+export abstract class ScheduleSessionCreator extends Interface<ScheduleSessionCreatorShape>() {}
+export abstract class ScheduleTaskRunner extends Interface<ScheduleTaskRunnerShape>() {}
+
/**
* Trigger input = a `[scheduled_task]` origin block (task name and fire time) + the prompt
* body: tells the model this was fired by a schedule; the frontend collapses the origin block
@@ -65,22 +74,6 @@ export interface ScheduleSessionCreator {
*/
export const scheduledMessage = buildScheduledMessage;
-export interface SchedulerDeps {
- root: string;
- repo: SchedulesRepo;
- projects: ProjectsRepo;
- sessions: SessionsRepo;
- runner: ScheduleTaskRunner;
- sessionCreator: ScheduleSessionCreator;
- /** Project-config source for model-ref validation (ProjectConfigService's mtime-cached reads). */
- projectConfig: ScheduleConfigSource;
- errors: ErrorSink;
- /** Fire and send are notified over the user-level event stream (app layer binds userChannelKey). */
- notify: (userId: string, event: ScheduleServerEvent) => void;
- now?: () => number;
- intervalMs?: number;
-}
-
/** A queued fire (at most one per task). */
interface PendingFire {
projectId: string;
@@ -96,22 +89,47 @@ export interface ScheduleEntryView {
queued: boolean;
}
+@Component()
export class Scheduler {
- private readonly now: () => number;
- private readonly intervalMs: number;
+ private now: () => number = () => Date.now();
+ private intervalMs: number = TICK_INTERVAL_MS;
private timer: ReturnType<typeof setInterval> | null = null;
/** key = `${projectId}\0${agentId}\0${name}` */
private readonly pending = new Map<string, PendingFire>();
private ticking = false;
+ private filesCache: ScheduleFileCache | null = null;
/** mtime-gated schedule-file scans (public for test observability of its counters). */
- readonly files: ScheduleFileCache;
+ get files(): ScheduleFileCache {
+ return (this.filesCache ??= new ScheduleFileCache(this.root));
+ }
/** Per-Project agents-dir listing gate: dir mtime → Agent ids (creating/removing an Agent dir moves it). */
private readonly agentDirs = new Map<string, { mtimeMs: number; ids: string[] }>();
- constructor(private readonly deps: SchedulerDeps) {
- this.now = deps.now ?? (() => Date.now());
- this.intervalMs = deps.intervalMs ?? TICK_INTERVAL_MS;
- this.files = new ScheduleFileCache(deps.root);
+ @Use() private readonly config!: Config;
+ private get root(): string {
+ return this.config.root;
+ }
+ @Use() private readonly repo!: SchedulesRepo;
+ @Use() private readonly projects!: ProjectsRepo;
+ @Use() private readonly sessions!: SessionsRepo;
+ @Use() private readonly runner!: ScheduleTaskRunner;
+ @Use() private readonly sessionCreator!: ScheduleSessionCreator;
+ /** Project-config source for model-ref validation (mtime-cached reads). */
+ @Use() private readonly projectConfig!: ProjectConfigService;
+ @Use() private readonly errors!: ErrorRecorder;
+ @Use() private readonly channels!: Channels;
+ @Use() private readonly overrides!: Overrides;
+
+ setup({ effect }: ClassCtx): void {
+ const overrides = this.overrides.value();
+ if (overrides.now) this.now = () => overrides.now!().getTime();
+ // Only active while this App is; the successor's start() reconciles missed fires.
+ effect(() => this.stop());
+ }
+
+ /** Fire and send are notified over the user-level event stream. */
+ private notify(userId: string, event: ScheduleServerEvent): void {
+ this.channels.get(userChannelKey(userId)).publish(event, "server_event");
}
/** Start: run one reconcile immediately (startup semantics: no backfill), then enter the periodic tick. */
@@ -133,7 +151,7 @@ export class Scheduler {
if (this.ticking) return;
this.ticking = true;
try {
- const projects = this.deps.projects.listAll();
+ const projects = this.projects.listAll();
for (const project of projects) {
await this.reconcileProject(project.projectId, project.ownerUserId);
}
@@ -146,7 +164,7 @@ export class Scheduler {
}
await this.drainQueue();
} catch (err) {
- this.deps.errors.record({ source: "schedule", err, code: "schedule_tick_failed" });
+ this.errors.record({ source: "schedule", err, code: "schedule_tick_failed" });
} finally {
this.ticking = false;
}
@@ -154,7 +172,7 @@ export class Scheduler {
/** Immediate-effect entry after a route write: reconcile just one Agent (bypassing the mtime gate) and drain its queue. */
async reconcileAgent(projectId: string, agentId: string): Promise<void> {
- const project = this.deps.projects.findById(projectId);
+ const project = this.projects.findById(projectId);
if (!project) return;
await this.reconcileOneAgent(projectId, agentId, project.ownerUserId, { force: true });
await this.drainQueue();
@@ -165,7 +183,7 @@ export class Scheduler {
projectId: string,
agentId: string,
): Promise<{ entries: ScheduleEntryView[]; invalid: Array<{ name: string; error: string }> }> {
- const project = this.deps.projects.findById(projectId);
+ const project = this.projects.findById(projectId);
const owner = project?.ownerUserId ?? null;
const files = await this.files.list(projectId, agentId);
const entries: ScheduleEntryView[] = [];
@@ -177,7 +195,7 @@ export class Scheduler {
}
// A model ref whose (provider, model_id) pair isn't in the config is treated like a parse failure: goes to invalidFiles, not scheduled.
const refError = await validateScheduleModelRef(
- this.deps.projectConfig,
+ this.projectConfig,
projectId,
file.parsed.def,
);
@@ -203,7 +221,7 @@ export class Scheduler {
/** For routes: state cleanup after a task is deleted (the unlink moved the dir mtime, but invalidate for immediate effect anyway). */
dropEntry(projectId: string, agentId: string, name: string): void {
this.pending.delete(this.keyOf(projectId, agentId, name));
- this.deps.repo.delete(projectId, agentId, name);
+ this.repo.delete(projectId, agentId, name);
this.files.invalidate(projectId, agentId);
}
@@ -227,7 +245,7 @@ export class Scheduler {
*/
private async listAgentIds(projectId: string): Promise<string[]> {
const cached = this.agentDirs.get(projectId);
- const mtimeMs = await statMtime(agentsDir(this.deps.root, projectId));
+ const mtimeMs = await statMtime(agentsDir(this.root, projectId));
if (mtimeMs === null) {
this.agentDirs.delete(projectId);
return [];
@@ -235,7 +253,7 @@ export class Scheduler {
if (cached && cached.mtimeMs === mtimeMs) return cached.ids;
let ids: string[];
try {
- const items = await fs.readdir(agentsDir(this.deps.root, projectId), {
+ const items = await fs.readdir(agentsDir(this.root, projectId), {
withFileTypes: true,
});
ids = items.filter((d) => d.isDirectory()).map((d) => d.name);
@@ -260,7 +278,7 @@ export class Scheduler {
for (const file of files) {
if (!file.parsed.ok) {
// Skip invalid files and record an error (the recorder dedups within a short window, so storms don't spam).
- this.deps.errors.record({
+ this.errors.record({
source: "schedule",
err: new Error(`Invalid schedule file: ${file.name}.toml — ${file.parsed.error}`),
code: "schedule_invalid_file",
@@ -272,9 +290,9 @@ export class Scheduler {
// At reconcile time, check the (provider, model_id) pair names a configured model: a
// reference that doesn't is treated like an invalid file — skip scheduling and record an
// error (recorder dedups in a short window); it recovers once the file/config is fixed.
- const refError = await validateScheduleModelRef(this.deps.projectConfig, projectId, def);
+ const refError = await validateScheduleModelRef(this.projectConfig, projectId, def);
if (refError !== null) {
- this.deps.errors.record({
+ this.errors.record({
source: "schedule",
err: new Error(`Invalid schedule file: ${file.name}.toml — ${refError}`),
code: "schedule_invalid_file",
@@ -301,7 +319,7 @@ export class Scheduler {
raw: string,
): ScheduleStateRow {
const defHash = createHash("sha1").update(raw).digest("hex");
- const { row, fresh } = this.deps.repo.registerOrSync({
+ const { row, fresh } = this.repo.registerOrSync({
projectId,
agentId,
name: def.name,
@@ -315,16 +333,16 @@ export class Scheduler {
const slot = latestSlotAt(def, this.now());
if (slot === null) return row;
if (def.periodMs === undefined) {
- this.deps.repo.markMissed(projectId, agentId, def.name);
+ this.repo.markMissed(projectId, agentId, def.name);
} else {
- this.deps.repo.markSlot(projectId, agentId, def.name, slot);
+ this.repo.markSlot(projectId, agentId, def.name, slot);
}
- return this.deps.repo.find(projectId, agentId, def.name) ?? row;
+ return this.repo.find(projectId, agentId, def.name) ?? row;
}
/** Clean up run state and queue entries for deleted files (deleting a file removes the task). */
private cleanupMissing(projectId: string, agentId: string, presentNames: string[]): void {
- const removed = this.deps.repo.deleteMissing(projectId, agentId, presentNames);
+ const removed = this.repo.deleteMissing(projectId, agentId, presentNames);
for (const name of removed) this.pending.delete(this.keyOf(projectId, agentId, name));
}
@@ -342,7 +360,7 @@ export class Scheduler {
if (slot === null || !slotInWindow(def, slot)) return;
if (state.lastSlotMs !== null && slot <= state.lastSlotMs) return;
// Consume this slot: never retry the same slot whether the send then succeeds, queues, or fails (the twin rule of no-backfill).
- this.deps.repo.markSlot(projectId, agentId, def.name, slot);
+ this.repo.markSlot(projectId, agentId, def.name, slot);
await this.dispatch(projectId, agentId, def, state);
}
@@ -355,9 +373,9 @@ export class Scheduler {
): Promise<void> {
const key = this.keyOf(projectId, agentId, def.name);
if (def.sessionId !== undefined) {
- const row = this.deps.sessions.findById(def.sessionId);
+ const row = this.sessions.findById(def.sessionId);
if (!row || row.projectId !== projectId || row.agentId !== agentId) {
- this.deps.errors.record({
+ this.errors.record({
source: "schedule",
err: new Error(
`Schedule ${def.name} is bound to a Session that does not exist: ${def.sessionId}`,
@@ -365,10 +383,10 @@ export class Scheduler {
code: "schedule_session_missing",
ctx: { projectId, agentId, sessionId: def.sessionId },
});
- this.deps.repo.markInvalid(projectId, agentId, def.name, "session_missing");
+ this.repo.markInvalid(projectId, agentId, def.name, "session_missing");
return;
}
- if (this.deps.runner.statusOf(def.sessionId) !== "idle") {
+ if (this.runner.statusOf(def.sessionId) !== "idle") {
// Queue when busy: at most one per task; new slots during the wait are consumed but don't stack.
if (!this.pending.has(key)) {
this.pending.set(key, { projectId, agentId, name: def.name, sessionId: def.sessionId });
@@ -387,7 +405,7 @@ export class Scheduler {
}
// New-Session mode: each fire opens a new session (optional workspace and paired model ref; same semantics as opening a session manually).
try {
- const info = await this.deps.sessionCreator.createSession({
+ const info = await this.sessionCreator.createSession({
projectId,
agentId,
...(def.workspace !== undefined ? { workspace: def.workspace } : {}),
@@ -397,7 +415,7 @@ export class Scheduler {
});
await this.send(projectId, agentId, def, state, info.sessionId);
} catch (err) {
- this.deps.errors.record({
+ this.errors.record({
source: "schedule",
err,
code: "schedule_create_session_failed",
@@ -415,12 +433,12 @@ export class Scheduler {
): Promise<void> {
const firedAt = new Date(this.now()).toISOString();
try {
- await this.deps.runner.startTask(sessionId, [
+ await this.runner.startTask(sessionId, [
// sender "server": in the Trace this user turn was injected by the server's scheduler, not typed by a human.
userText(scheduledMessage(def.name, firedAt, def.prompt), "server"),
]);
} catch (err) {
- this.deps.errors.record({
+ this.errors.record({
source: "schedule",
err,
code: "schedule_send_failed",
@@ -428,7 +446,7 @@ export class Scheduler {
});
return;
}
- this.deps.repo.markFired(projectId, agentId, def.name, firedAt, def.periodMs === undefined);
+ this.repo.markFired(projectId, agentId, def.name, firedAt, def.periodMs === undefined);
this.notifyFor(state, {
type: "schedule_fired",
projectId,
@@ -441,23 +459,23 @@ export class Scheduler {
/** Drain the queue: send once the target Session is idle; drop if the task is disabled/deleted/invalid. */
private async drainQueue(): Promise<void> {
for (const [key, fire] of [...this.pending]) {
- const state = this.deps.repo.find(fire.projectId, fire.agentId, fire.name);
+ const state = this.repo.find(fire.projectId, fire.agentId, fire.name);
if (!state || state.invalidReason !== null) {
this.pending.delete(key);
continue;
}
- const file = await readScheduleFile(this.deps.root, fire.projectId, fire.agentId, fire.name);
+ const file = await readScheduleFile(this.root, fire.projectId, fire.agentId, fire.name);
if (!file || !file.parsed.ok || !file.parsed.def.enabled) {
this.pending.delete(key);
continue;
}
- const row = this.deps.sessions.findById(fire.sessionId);
+ const row = this.sessions.findById(fire.sessionId);
if (!row) {
this.pending.delete(key);
- this.deps.repo.markInvalid(fire.projectId, fire.agentId, fire.name, "session_missing");
+ this.repo.markInvalid(fire.projectId, fire.agentId, fire.name, "session_missing");
continue;
}
- if (this.deps.runner.statusOf(fire.sessionId) !== "idle") continue;
+ if (this.runner.statusOf(fire.sessionId) !== "idle") continue;
this.pending.delete(key);
await this.send(fire.projectId, fire.agentId, file.parsed.def, state, fire.sessionId);
}
@@ -466,6 +484,6 @@ export class Scheduler {
/** Notify the creator (falls back to the Project owner at registration; silent if still absent). */
private notifyFor(state: ScheduleStateRow, event: ScheduleServerEvent): void {
const userId = state.creatorUserId;
- if (userId) this.deps.notify(userId, event);
+ if (userId) this.notify(userId, event);
}
}
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index bdf26055..897d4c42 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -65,19 +65,37 @@ import type {
SessionStatus,
} from "../api/types.js";
import type { RecallableFile } from "../services/task-attachments.js";
+import { cliShimDir } from "../services/cli-shim.js";
import { HttpError, isMissingCredential, modelCredentialMissing } from "../http/errors.js";
import type { SessionRow, SessionsRepo } from "../db/repos/sessions.js";
import { ApprovalRegistry, makeApprove } from "./approvals.js";
import { goalOutcomeOf, goalProgressOf } from "./goal-events.js";
import type { PendingApproval } from "./approvals.js";
import type { ChannelHub } from "./channel.js";
-import type { ErrorSink } from "./error-recorder.js";
+import type { ErrorSink, ErrorRecorder } from "./error-recorder.js";
import { LiveTailTracker } from "./live-tail.js";
import { asSessionSource } from "./session-sources.js";
import type { SessionSources } from "./session-sources.js";
import { StreamErrorWatcher } from "./stream-error-watcher.js";
import type { TitleNotifier } from "./title-generator.js";
-import type { UsageContext } from "./usage-recorder.js";
+import type { UsageContext, UsageRecorder } from "./usage-recorder.js";
+import { Interface, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";
+import type { SessionService as SessionServiceImpl } from "../services/session-service.js";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
+import { AuthState, Channels, Config, Log, Overrides, RuntimeModule } from "../hmr/capabilities.js";
+import { Sandbox, SandboxModule } from "../sandbox/service.js";
+import { SessionService } from "../services/session-service.js";
+import { TitleGenerator } from "./title-generator.js";
+import { loopbackHostRoles } from "../services/preview-token.js";
+import { mergedNoProxy } from "../net/proxy.js";
+import { userChannelKey } from "../http/routes/events.js";
+import type { ProjectConfigService } from "../services/project-config-service.js";
+import type { TraceIndexService } from "../services/trace-index.js";
+import type { SandboxService } from "../sandbox/service.js";
+import type { ServerSettingsRepo } from "../db/repos/server-settings.js";
+import type { MessagingBindingsRepo } from "../db/repos/messaging-bindings.js";
+import type { MembersRepo } from "../db/repos/members.js";
+import type { ProjectsRepo } from "../db/repos/projects.js";
/**
* 409 for when there's nothing to compact: give the specific reason rather than a
@@ -2161,3 +2179,201 @@ export class SessionManager {
return next;
}
}
+
+/** The session runtime: one entry per live Session, task mutex, approvals, streaming. */
+export abstract class Sessions extends Interface<
+ Pick<
+ SessionManager,
+ | "statusOf"
+ | "pendingApprovalCount"
+ | "pendingApprovals"
+ | "pendingFollowUpCount"
+ | "pendingSteeringOf"
+ | "subagentsOf"
+ | "sendToSubagent"
+ | "abortSubagentRun"
+ | "pendingFollowUpsOf"
+ | "liveFragments"
+ | "pendingInputs"
+ | "pendingBootstrap"
+ | "activeCountForAgent"
+ | "invalidateAgentRuntimes"
+ | "invalidateProjectRuntimes"
+ | "assertCanAcceptTask"
+ | "startTask"
+ | "startGoal"
+ | "startCompact"
+ | "decideApproval"
+ | "steer"
+ | "recallSteering"
+ | "recallFollowUp"
+ | "retryNow"
+ | "abortTask"
+ | "listProcesses"
+ | "probeProcessServices"
+ | "killProcess"
+ | "removeProcess"
+ | "abortProject"
+ | "beginAgentDeletion"
+ | "endAgentDeletion"
+ | "beginSessionDeletion"
+ | "endSessionDeletion"
+ | "atIdleBoundary"
+ | "shutdown"
+ | "sweepIdle"
+ >
+>() {}
+
+export abstract class SessionServiceIface extends Interface<
+ Pick<
+ SessionServiceImpl,
+ | "toInfo"
+ | "hasTrace"
+ | "listSessions"
+ | "sessionStats"
+ | "createSession"
+ | "latestTracePath"
+ | "adoptUnmanagedTraceSessions"
+ >
+>() {}
+
+/** The per-spawn policies every Session's command environment is built with. */
+export abstract class SessionEnv extends Interface<{
+ proxyEnv(): ProxyEnvPolicy | null;
+ controlEnv(ctx: ControlEnvContext): Record<string, string>;
+ /** The directories at the FRONT of every command's PATH: the harness's own CLI shim (see CreateAgentOptions.pathPrepend). */
+ pathPrepend(): string[];
+ confineSpawn(): SpawnConfiner | null;
+}>() {}
+
+@Module()
+export class SessionsModule {
+ @Use(RuntimeModule) private readonly config!: Config;
+ @Use(RuntimeModule) private readonly channels!: Channels;
+ @Use(RuntimeModule) private readonly authState!: AuthState;
+ @Use(RuntimeModule) private readonly overrides!: Overrides;
+ @Use(RuntimeModule) private readonly log!: Log;
+ @Use() private readonly settings!: ServerSettingsRepo;
+ @Use() private readonly sessionsRepo!: SessionsRepo;
+ @Use() private readonly sources!: SessionSources;
+ @Use() private readonly recorder!: UsageRecorder;
+ @Use() private readonly errors!: ErrorRecorder;
+ @Use() private readonly projectConfig!: ProjectConfigService;
+ @Use() private readonly traceIndex!: TraceIndexService;
+ @Use(SandboxModule) private readonly sandbox!: Sandbox;
+ @Use() private readonly projectsRepo!: ProjectsRepo;
+ @Use() private readonly membersRepo!: MembersRepo;
+ @Use() private readonly messagingRepo!: MessagingBindingsRepo;
+ @Provide() manager!: Sessions;
+ @Provide() sessionService!: SessionServiceIface;
+ @Provide() env!: SessionEnv;
+ setup() {
+ const { config, settings, authState } = this;
+ const overrides = this.overrides.value();
+ const log = (line: string) => this.log.line(line);
+ const channels = this.channels as ChannelHub;
+ const sessionsRepo = this.sessionsRepo;
+ const sources = this.sources;
+ const recorder = this.recorder;
+ const errors = this.errors;
+ const projectConfig = this.projectConfig;
+ const sandbox = this.sandbox as SandboxService;
+
+ // Which commands run confined, under which policy, by which backend is policy — the
+ // sandbox module's; core only carries the spawn seam, reached through this getter.
+ const env: SessionEnv = {
+ proxyEnv: (): ProxyEnvPolicy | null => {
+ if (!settings.getProxyForAgent()) return { mode: "strip" };
+ const url = settings.getProxyUrl();
+ return url === null ? null : { mode: "inject", url, noProxy: mergedNoProxy() };
+ },
+ controlEnv: (ctx: ControlEnvContext): Record<string, string> => {
+ const host =
+ config.host === "0.0.0.0" || config.host === "::"
+ ? "127.0.0.1"
+ : (loopbackHostRoles(config.host)?.app ?? config.host);
+ const token = authState.apiToken;
+ return {
+ PENGUIN_API_URL: `http://${host}:${config.port}`,
+ ...(token !== null ? { PENGUIN_API_TOKEN: token } : {}),
+ PENGUIN_PROJECT_ID: ctx.projectId,
+ PENGUIN_AGENT_ID: ctx.agentId,
+ PENGUIN_SESSION_ID: ctx.sessionId,
+ };
+ },
+ // The directory core puts at the FRONT of PATH for every command an Agent runs (and for
+ // its hook scripts): the shim directory bootAppDeps wrote this harness's own `penguin`
+ // into. Derived from the config rather than passed along, so the platform half needs no
+ // new capability — and read for truth rather than for null, because a runtime older than
+ // this field publishes a config without it and wrote no shim either: no field, no
+ // directory, feature off, rather than a push declined over a PATH entry.
+ pathPrepend: (): string[] => (config.cliEntry ? [cliShimDir(config.root)] : []),
+ confineSpawn: () => sandbox.confiner(),
+ };
+
+ const notifyProjectUsers = (projectId: string, event: ServerEvent): void => {
+ const ownerUserId = this.projectsRepo.findById(projectId)?.ownerUserId;
+ if (ownerUserId === undefined) return;
+ const audience = new Set([
+ ownerUserId,
+ ...this.membersRepo.list(projectId).map((m) => m.userId),
+ ]);
+ for (const userId of audience) {
+ channels.peek(userChannelKey(userId))?.publish(event, "server_event");
+ }
+ };
+ const titles =
+ overrides.titles ??
+ new TitleGenerator({
+ sessions: sessionsRepo,
+ channels,
+ recorder,
+ errors,
+ log,
+ notifyProjectUsers,
+ });
+ const manager = new SessionManager({
+ sessions: sessionsRepo,
+ channels,
+ loader:
+ overrides.loader ??
+ createCoreSessionLoader(config.root, sources, {
+ proxyEnv: env.proxyEnv,
+ controlEnv: env.controlEnv,
+ pathPrepend: env.pathPrepend,
+ confineSpawn: env.confineSpawn,
+ }),
+ sources,
+ recorder,
+ errors,
+ titles,
+ log,
+ notifyProjectUsers,
+ ...(overrides.now ? { now: overrides.now } : {}),
+ });
+ const sessionService = new SessionService({
+ root: config.root,
+ sessions: sessionsRepo,
+ manager,
+ projectConfig,
+ sources,
+ traceIndex: this.traceIndex,
+ proxyEnv: env.proxyEnv,
+ controlEnv: env.controlEnv,
+ messagingChannel: (sessionId) => {
+ const enabled = this.messagingRepo.findEnabled(sessionId);
+ return enabled !== null &&
+ (enabled.channel === "feishu" ||
+ enabled.channel === "telegram" ||
+ enabled.channel === "qq")
+ ? enabled.channel
+ : null;
+ },
+ pathPrepend: env.pathPrepend,
+ confineSpawn: env.confineSpawn,
+ });
+ this.manager = manager;
+ this.sessionService = sessionService;
+ this.env = env;
+ }
+}
diff --git a/packages/server/src/runtime/session-sources.ts b/packages/server/src/runtime/session-sources.ts
index 21490a4e..da22c737 100644
--- a/packages/server/src/runtime/session-sources.ts
+++ b/packages/server/src/runtime/session-sources.ts
@@ -11,6 +11,7 @@
* Trace once per process lifetime.
*/
import type { SessionSource } from "../api/types.js";
+import { Component } from "@prismshadow/penguin-core/kernel";
/**
* Narrows an untrusted value (on-disk Trace JSON / forwarded meta) to a SessionSource:
@@ -21,6 +22,7 @@ export function asSessionSource(v: unknown): SessionSource | undefined {
return v === "schedule" || v === "subagent" || v === "benchmark" ? v : undefined;
}
+@Component()
export class SessionSources {
private readonly map = new Map<string, SessionSource | null>();
diff --git a/packages/server/src/runtime/usage-recorder.ts b/packages/server/src/runtime/usage-recorder.ts
index e2e03453..9218d5bb 100644
--- a/packages/server/src/runtime/usage-recorder.ts
+++ b/packages/server/src/runtime/usage-recorder.ts
@@ -17,6 +17,8 @@ import { isEventMessage, isSessionMeta } from "@prismshadow/penguin-core";
import type { OmniMessage } from "@prismshadow/penguin-core";
import { formatLocalDate } from "../internal/dates.js";
import type { UsageRepo } from "../db/repos/usage.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Overrides } from "../hmr/capabilities.js";
/** Attribution context for one record (top-level Session scope). */
export interface UsageContext {
@@ -33,14 +35,18 @@ export interface UsageContext {
/** Cap on the subagent attribution mapping: over the limit, evicts the oldest by insertion order (an evicted entry falls back to the main Session's Model attribution). */
export const ORIGIN_MODELS_MAX = 1000;
+@Component()
export class UsageRecorder {
/** Subagent model attribution mapping: origin's last session_id → paired reference (session_id is globally unique). */
private readonly originModels = new Map<string, { provider: string; modelId: string }>();
- constructor(
- private readonly usage: UsageRepo,
- private readonly now: () => Date = () => new Date(),
- ) {}
+ @Use() private readonly usage!: UsageRepo;
+ @Use() private readonly overrides!: Overrides;
+ private now: () => Date = () => new Date();
+
+ setup(): void {
+ this.now = this.overrides.value().now ?? this.now;
+ }
/** Consume one outgoing message; messages other than session_meta / token_usage are a no-op. */
async record(ctx: UsageContext, msg: OmniMessage): Promise<void> {
diff --git a/packages/server/src/sandbox/service.ts b/packages/server/src/sandbox/service.ts
index 45d095b6..9c757e05 100644
--- a/packages/server/src/sandbox/service.ts
+++ b/packages/server/src/sandbox/service.ts
@@ -20,6 +20,8 @@ import type {
SandboxSettings,
} from "@prismshadow/penguin-core/plugin";
import { providerDimensions, requestedDimensions } from "./dimensions.js";
+import { Interface, Module, Provide } from "@prismshadow/penguin-core/kernel";
+import type { Slot, ClassCtx, Json } from "@prismshadow/penguin-core/kernel";
interface MountedProvider {
name: string;
@@ -159,3 +161,52 @@ function copySettings(settings: SandboxSettings): SandboxSettings {
...(settings.maskPaths !== undefined ? { maskPaths: [...settings.maskPaths] } : {}),
};
}
+
+/** Confinement: settings, the active confiner, and which backends are mounted. */
+export abstract class Sandbox extends Interface<
+ Pick<
+ SandboxService,
+ "configure" | "currentSettings" | "parkedSettings" | "backends" | "confiner" | "whenReady"
+ >
+>() {}
+
+export interface SandboxSlots {
+ /**
+ * A backend: its static half here (name, the dimensions it implements), its code half
+ * bound by the contributor — a provider, or a promise of one for backends that probe.
+ */
+ providers: Slot<{ name: string; dimensions: SandboxDimension[] }, SandboxProviderSource>;
+}
+
+@Module({
+ context: {
+ version: 1,
+ schema: {
+ "settings?": {
+ mode: "'read-only'|'workspace-write'|'danger-full-access'",
+ "network?": "'none'",
+ "maskPaths?": "string[]",
+ },
+ },
+ },
+})
+export class SandboxModule {
+ @Provide() sandbox!: Sandbox;
+ setup({ contributions }: ClassCtx, context: Json) {
+ const providers = (contributions.providers ?? []).map(
+ (c) =>
+ [c.data.name as string, c.code as SandboxProviderSource] as [string, SandboxProviderSource],
+ );
+ const sandbox = new SandboxService(providers);
+ // Parked settings ride the swap: without this every push would construct a fresh
+ // service on defaults and silently un-confine a confining deployment.
+ const parked = (context as { settings?: SandboxSettings } | null)?.settings;
+ if (parked !== undefined) sandbox.configure(parked);
+ this.sandbox = sandbox;
+ }
+
+ park(): Json {
+ const settings = this.sandbox.parkedSettings();
+ return settings === undefined ? null : { settings };
+ }
+}
diff --git a/packages/server/src/services/admin-service.ts b/packages/server/src/services/admin-service.ts
index 889d28cf..0f1219ff 100644
--- a/packages/server/src/services/admin-service.ts
+++ b/packages/server/src/services/admin-service.ts
@@ -19,27 +19,24 @@ import type { AuthSessionsRepo } from "../db/repos/auth-sessions.js";
import type { UserRow, UsersRepo } from "../db/repos/users.js";
import { SEMANTIC_ID_RULE, USERNAME_PATTERN } from "./ids.js";
import type { ProjectService } from "./project-service.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Overrides } from "../hmr/capabilities.js";
-export interface AdminServiceDeps {
- users: UsersRepo;
- authSessions: AuthSessionsRepo;
- projects: ProjectsRepo;
- projectService: ProjectService;
- /**
- * Test double: scrypt work factor for hashes this service writes. Omitted in
- * production, where {@link SCRYPT_COST} applies.
- */
- passwordHashCost?: number;
- now?: () => Date;
-}
-
+@Component()
export class AdminService {
- private readonly now: () => Date;
- private readonly hashCost: number;
+ @Use() private readonly users!: UsersRepo;
+ @Use() private readonly authSessions!: AuthSessionsRepo;
+ @Use() private readonly projects!: ProjectsRepo;
+ @Use() private readonly projectService!: ProjectService;
+ @Use() private readonly overrides!: Overrides;
+ private now: () => Date = () => new Date();
+ /** scrypt work factor for hashes this service writes; a test double lowers it. */
+ private hashCost: number = SCRYPT_COST;
- constructor(private readonly deps: AdminServiceDeps) {
- this.now = deps.now ?? (() => new Date());
- this.hashCost = deps.passwordHashCost ?? SCRYPT_COST;
+ setup(): void {
+ const overrides = this.overrides.value();
+ this.now = overrides.now ?? this.now;
+ this.hashCost = overrides.passwordHashCost ?? SCRYPT_COST;
}
/**
@@ -48,7 +45,7 @@ export class AdminService {
* would answer a table that only shows the nickname with megabytes.
*/
listUsers(): UserInfo[] {
- return this.deps.users.list().map((row) => {
+ return this.users.list().map((row) => {
const { avatar: _avatar, ...info } = toUserInfo(row);
return info;
});
@@ -65,7 +62,7 @@ export class AdminService {
if (password.length < MIN_PASSWORD_LENGTH) {
throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
}
- if (this.deps.users.findById(userId)) {
+ if (this.users.findById(userId)) {
throw new HttpError(409, "user_exists", `User already exists: ${userId}.`);
}
const user: UserRow = {
@@ -77,12 +74,12 @@ export class AdminService {
avatar: null,
createdAt: this.now().toISOString(),
};
- this.deps.users.insert(user);
+ this.users.insert(user);
try {
- await this.deps.projectService.provisionInitialProject(user, false);
+ await this.projectService.provisionInitialProject(user, false);
} catch (err) {
// Compensation: roll back the user row if default Project creation fails (e.g. proj-<username> already taken).
- this.deps.users.delete(user.userId);
+ this.users.delete(user.userId);
throw err;
}
return toUserInfo(user);
@@ -96,34 +93,34 @@ export class AdminService {
* Every other user gets the flag, to be prompted to change the password their admin picked.
*/
async resetPassword(userId: string, password: string): Promise<void> {
- if (!this.deps.users.findById(userId)) {
+ if (!this.users.findById(userId)) {
throw new HttpError(404, "user_not_found", `User does not exist: ${userId}.`);
}
if (password.length < MIN_PASSWORD_LENGTH) {
throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
}
const isSelfAdminReset = userId === ADMIN_USER_ID;
- this.deps.users.updatePassword(
+ this.users.updatePassword(
userId,
await hashPassword(password, this.hashCost),
!isSelfAdminReset,
);
// Force re-login: delete every session row for this user.
- this.deps.authSessions.deleteByUser(userId);
+ this.authSessions.deleteByUser(userId);
}
/** Delete user: the built-in admin cannot be deleted; owned Projects (including data directories) are deleted along with it. */
async deleteUser(userId: string): Promise<void> {
- const target = this.deps.users.findById(userId);
+ const target = this.users.findById(userId);
if (!target) {
throw new HttpError(404, "user_not_found", `User does not exist: ${userId}.`);
}
if (target.isAdmin) {
throw new HttpError(409, "cannot_delete_admin", "The built-in admin cannot be deleted.");
}
- for (const project of this.deps.projects.listByOwner(userId)) {
- await this.deps.projectService.destroyProject(project.projectId);
+ for (const project of this.projects.listByOwner(userId)) {
+ await this.projectService.destroyProject(project.projectId);
}
- this.deps.users.delete(userId); // project_members / ui_prefs cascade-deleted
+ this.users.delete(userId); // project_members / ui_prefs cascade-deleted
}
}
diff --git a/packages/server/src/services/agent-config-service.ts b/packages/server/src/services/agent-config-service.ts
index f7579fe8..f4ee87f1 100644
--- a/packages/server/src/services/agent-config-service.ts
+++ b/packages/server/src/services/agent-config-service.ts
@@ -68,6 +68,8 @@ import {
optionalString,
} from "../http/validate.js";
import { maskApiKey } from "./project-config-service.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Config } from "../hmr/capabilities.js";
const COMPACTION_MODES = ["summarize", "discard"] as const;
@@ -84,8 +86,12 @@ export interface AgentConfigView {
stateDir: string;
}
+@Component()
export class AgentConfigService {
- constructor(private readonly root: string) {}
+ @Use() private readonly config!: Config;
+ private get root(): string {
+ return this.config.root;
+ }
/** Whether the Agent exists (determined by the presence of system_config.yaml, matching the CLI's convention). */
async exists(projectId: string, agentId: string): Promise<boolean> {
diff --git a/packages/server/src/services/agent-routes.ts b/packages/server/src/services/agent-routes.ts
new file mode 100644
index 00000000..da87bef8
--- /dev/null
+++ b/packages/server/src/services/agent-routes.ts
@@ -0,0 +1,88 @@
+import { Bind, Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { AppEnv } from "../auth/middleware.js";
+import type { Hono } from "hono";
+import type { Config } from "../hmr/capabilities.js";
+import type { ProjectAccess } from "./project-access.js";
+import type { AgentConfigService } from "./agent-config-service.js";
+import type { MemoryService } from "./memory-service.js";
+import type { SnapshotService } from "./snapshot-service.js";
+import type { BenchmarkService } from "./benchmark-service.js";
+import type { TraceService } from "./trace-service.js";
+import { memoryRoutes } from "../http/routes/memory.js";
+import { benchmarksRoutes } from "../http/routes/benchmarks.js";
+import { agentSkillsRoutes } from "../http/routes/skills.js";
+import { agentTransferRoutes } from "../http/routes/agent-transfer.js";
+import { agentTracesRoutes } from "../http/routes/agent-traces.js";
+
+/**
+ * The Agent-scoped route groups: memory, skills, transfer, traces — and benchmarks, which
+ * are Project-level peers of an Agent but read through the same services.
+ */
+@Component({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "agents.benchmarks",
+ prefix: "/api/projects/:projectId/benchmarks",
+ auth: "user",
+ order: 165,
+ },
+ {
+ id: "agents.memory",
+ prefix: "/api/projects/:projectId/agents/:agentId/memory",
+ auth: "user",
+ order: 190,
+ },
+ {
+ id: "agents.skills",
+ prefix: "/api/projects/:projectId/agents/:agentId/skills",
+ auth: "user",
+ order: 220,
+ },
+ {
+ id: "agents.transfer",
+ prefix: "/api/projects/:projectId/agents/:agentId",
+ auth: "user",
+ order: 230,
+ },
+ {
+ id: "agents.traces",
+ prefix: "/api/projects/:projectId/agents/:agentId/traces",
+ auth: "user",
+ order: 240,
+ },
+ ],
+ },
+})
+export class AgentRoutes {
+ @Use() private readonly config!: Config;
+ @Use() private readonly access!: ProjectAccess;
+ @Use() private readonly agentConfig!: AgentConfigService;
+ @Use() private readonly memory!: MemoryService;
+ @Use() private readonly snapshots!: SnapshotService;
+ @Use() private readonly benchmarks!: BenchmarkService;
+ @Use() private readonly traces!: TraceService;
+ @Bind("agents.memory") memoryRoutes!: Hono<AppEnv>;
+ @Bind("agents.benchmarks") benchmarksRoutes!: Hono<AppEnv>;
+ @Bind("agents.skills") skillsRoutes!: Hono<AppEnv>;
+ @Bind("agents.transfer") transferRoutes!: Hono<AppEnv>;
+ @Bind("agents.traces") tracesRoutes!: Hono<AppEnv>;
+
+ setup() {
+ const access = this.access;
+ const agentConfigService = this.agentConfig;
+ this.memoryRoutes = memoryRoutes({ memoryService: this.memory, access });
+ this.benchmarksRoutes = benchmarksRoutes({ benchmarks: this.benchmarks, access });
+ this.skillsRoutes = agentSkillsRoutes({ agentConfigService, config: this.config, access });
+ this.transferRoutes = agentTransferRoutes({
+ agentConfigService,
+ access,
+ snapshots: this.snapshots,
+ });
+ this.tracesRoutes = agentTracesRoutes({
+ agentConfigService,
+ access,
+ traceService: this.traces,
+ });
+ }
+}
diff --git a/packages/server/src/services/agent-service.ts b/packages/server/src/services/agent-service.ts
index 7caf1949..8a0372ba 100644
--- a/packages/server/src/services/agent-service.ts
+++ b/packages/server/src/services/agent-service.ts
@@ -41,6 +41,8 @@ import { isTopicFileName } from "./memory-service.js";
import type { PluginUpdateRef } from "../api/types.js";
import { resolveLibraryPlugins } from "./plugin-library.js";
import { resolveDirectorySkills } from "./directory-skills.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Config } from "../hmr/capabilities.js";
/**
* How much of a SKILL.md is read to answer "which version is installed" (see `installedSkills`).
@@ -91,13 +93,15 @@ export interface AgentListItem {
memoryCount: number;
}
+@Component()
export class AgentService {
- constructor(
- private readonly root: string,
- private readonly agents: AgentsRepo,
- private readonly agentConfig: AgentConfigService,
- private readonly snapshots: SnapshotService,
- ) {}
+ @Use() private readonly config!: Config;
+ private get root(): string {
+ return this.config.root;
+ }
+ @Use() private readonly agents!: AgentsRepo;
+ @Use() private readonly agentConfig!: AgentConfigService;
+ @Use() private readonly snapshots!: SnapshotService;
/** Union of DB index ∪ directory scan; unmanaged directory Agents are backfilled into the DB. */
async listAgents(projectId: string): Promise<AgentListItem[]> {
diff --git a/packages/server/src/services/benchmark-service.ts b/packages/server/src/services/benchmark-service.ts
index c571192a..fcd45209 100644
--- a/packages/server/src/services/benchmark-service.ts
+++ b/packages/server/src/services/benchmark-service.ts
@@ -40,6 +40,8 @@ import type {
WorkspaceFilesService,
} from "./workspace-files-service.js";
import { HttpError } from "../http/errors.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Config } from "../hmr/capabilities.js";
const STATEMENT_TITLE_READ_BYTES = 64 * 1024;
@@ -220,11 +222,13 @@ function toEvaluation(v: unknown): BenchmarkEvaluation | null {
};
}
+@Component()
export class BenchmarkService {
- constructor(
- private readonly root: string,
- private readonly workspaceFiles: WorkspaceFilesService,
- ) {}
+ @Use() private readonly config!: Config;
+ private get root(): string {
+ return this.config.root;
+ }
+ @Use() private readonly workspaceFiles!: WorkspaceFilesService;
async list(projectId: string): Promise<BenchmarksResponse> {
const dir = benchmarksDir(this.root, projectId);
diff --git a/packages/server/src/services/memory-service.ts b/packages/server/src/services/memory-service.ts
index e8dc9cef..7ad25133 100644
--- a/packages/server/src/services/memory-service.ts
+++ b/packages/server/src/services/memory-service.ts
@@ -52,6 +52,8 @@ import type {
import { HttpError } from "../http/errors.js";
import { badRequest } from "../http/validate.js";
import type { AgentConfigService } from "./agent-config-service.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Config } from "../hmr/capabilities.js";
/** Scope directory names: what core's key generator produces (a safe base may start with `_`), plus the leeway of a hand-made directory. Excludes `.`/`..` and any separator, so the name can never climb out of `memory/`. */
const SCOPE_KEY_PATTERN = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
@@ -207,11 +209,13 @@ function parseTransferDocument(payload: unknown): {
return { index, files };
}
+@Component()
export class MemoryService {
- constructor(
- private readonly root: string,
- private readonly agentConfigService: AgentConfigService,
- ) {}
+ @Use() private readonly config!: Config;
+ private get root(): string {
+ return this.config.root;
+ }
+ @Use() private readonly agentConfigService!: AgentConfigService;
/** The tab's landing payload: the Agent-level switch and one entry per scope directory. */
async overview(projectId: string, agentId: string): Promise<MemoryOverviewResponse> {
diff --git a/packages/server/src/services/model-oauth-service.ts b/packages/server/src/services/model-oauth-service.ts
index 98c6ab0c..092728c1 100644
--- a/packages/server/src/services/model-oauth-service.ts
+++ b/packages/server/src/services/model-oauth-service.ts
@@ -28,6 +28,8 @@ import { APP_URL, providerInfo } from "@prismshadow/penguin-core/model-catalog";
import type { ModelProviderOAuth } from "@prismshadow/penguin-core/model-catalog";
import { HttpError } from "../http/errors.js";
import { badRequest } from "../http/validate.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { ProjectConfigService } from "./project-config-service.js";
/** How the user gets the authorization code back to the harness. */
export type ModelOAuthMode = "callback" | "manual";
@@ -201,24 +203,15 @@ export type ApplyGroupKey = (
apiKey: string,
) => Promise<number>;
-export interface ModelOAuthDeps {
- applyGroupKey: ApplyGroupKey;
- /** Injected so tests never reach the network. */
- fetchImpl?: typeof fetch;
- now?: () => number;
-}
-
+@Component()
export class ModelOAuthService {
private readonly flows = new Map<string, Flow>();
- private readonly applyGroupKey: ApplyGroupKey;
- private readonly fetchImpl: typeof fetch;
- private readonly now: () => number;
-
- constructor(deps: ModelOAuthDeps) {
- this.applyGroupKey = deps.applyGroupKey;
- this.fetchImpl = deps.fetchImpl ?? ((...args) => fetch(...args));
- this.now = deps.now ?? (() => Date.now());
- }
+ @Use() private readonly projectConfig!: ProjectConfigService;
+ private applyGroupKey: ApplyGroupKey = (projectId, provider, apiKey) =>
+ this.projectConfig.setGroupApiKey(projectId, provider, apiKey);
+ /** Replaced in tests so they never reach the network. */
+ private fetchImpl: typeof fetch = (...args) => fetch(...args);
+ private now: () => number = () => Date.now();
/**
* Open a flow for one provider group and return the page to send the user to.
diff --git a/packages/server/src/services/project-access.ts b/packages/server/src/services/project-access.ts
new file mode 100644
index 00000000..500d748c
--- /dev/null
+++ b/packages/server/src/services/project-access.ts
@@ -0,0 +1,87 @@
+/**
+ * Who may see a Project: the owner / member decision, in ONE place.
+ *
+ * Split from ProjectService so that access control sits below everything that runs a
+ * Session: nearly every route checks access first, and the session runtime is what
+ * project LIFECYCLE (delete, destroy) depends on — the two cannot live in one module
+ * without a cycle. Lifecycle stays in ProjectService and delegates its checks here.
+ */
+import type { ProjectRole, ProjectSummary } from "../api/types.js";
+import { HttpError } from "../http/errors.js";
+import type { MembersRepo } from "../db/repos/members.js";
+import type { ProjectRow, ProjectsRepo } from "../db/repos/projects.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { ProjectConfigService } from "./project-config-service.js";
+
+@Component()
+export class ProjectAccess {
+ @Use() private readonly projects!: ProjectsRepo;
+ @Use() private readonly members!: MembersRepo;
+ /** Display names come from each project's own config file. */
+ @Use() private readonly projectConfig!: ProjectConfigService;
+
+ /**
+ * The sole implementation of the owner / member check: the row with a role when
+ * accessible, otherwise null. Every other member here is a wrapper around it.
+ */
+ find(userId: string, projectId: string): (ProjectRow & { role: ProjectRole }) | null {
+ const row = this.projects.findById(projectId);
+ if (!row) return null;
+ if (row.ownerUserId === userId) return { ...row, role: "owner" };
+ if (this.members.isMember(projectId, userId)) return { ...row, role: "member" };
+ return null;
+ }
+
+ /** Accessible by owner or member; otherwise 404 (does not leak Project existence). */
+ requireProjectAccess(userId: string, projectId: string): ProjectRow & { role: ProjectRole } {
+ const row = this.find(userId, projectId);
+ if (!row) {
+ throw new HttpError(
+ 404,
+ "project_not_found",
+ "Project does not exist or you do not have access.",
+ );
+ }
+ return row;
+ }
+
+ /** The non-throwing form, for error attribution — where another 404 would only break error handling. */
+ canAccess(userId: string, projectId: string): boolean {
+ return this.find(userId, projectId) !== null;
+ }
+
+ /** Owner only: 403 when known accessible as a member; 404 when not accessible. */
+ requireProjectOwner(userId: string, projectId: string): ProjectRow {
+ const row = this.requireProjectAccess(userId, projectId);
+ if (row.role !== "owner") {
+ throw new HttpError(
+ 403,
+ "owner_required",
+ "Only the Project owner can perform this operation.",
+ );
+ }
+ return row;
+ }
+
+ /** Every project_id the user may reach (owned + granted). */
+ accessibleProjectIds(userId: string): string[] {
+ return this.projects.listAccessible(userId).map((p) => p.projectId);
+ }
+
+ /** Owned + granted Projects with their display names. */
+ async listProjects(userId: string): Promise<ProjectSummary[]> {
+ const rows = this.projects.listAccessible(userId);
+ return Promise.all(
+ rows.map(async (row) => {
+ const name = await this.projectConfig.getName(row.projectId);
+ return {
+ projectId: row.projectId,
+ ...(name !== undefined ? { name } : {}),
+ role: row.role,
+ ownerUserId: row.ownerUserId,
+ createdAt: row.createdAt,
+ };
+ }),
+ );
+ }
+}
diff --git a/packages/server/src/services/project-config-service.ts b/packages/server/src/services/project-config-service.ts
index 42fc31e8..5d9a4b7a 100644
--- a/packages/server/src/services/project-config-service.ts
+++ b/packages/server/src/services/project-config-service.ts
@@ -83,6 +83,8 @@ import {
classifyVisionProbeError,
} from "./vision-detect.js";
import type { PricingRates, TieredRates } from "./usage-service.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Config } from "../hmr/capabilities.js";
type RawTable = Record<string, unknown>;
@@ -254,6 +256,7 @@ const LIST_MODELS_TIMEOUT_MS = 20_000;
const SPEED_PROBE_PROMPT =
"Count from 1 to 50 as a comma-separated list, and nothing else. Do not think or explain.\n<think></think>";
+@Component()
export class ProjectConfigService {
/**
* Parsed-table cache, one entry per Project, keyed by the config file's mtime as
@@ -264,7 +267,10 @@ export class ProjectConfigService {
*/
private readonly cache = new Map<string, { mtimeMs: number; table: RawTable }>();
- constructor(private readonly root: string) {}
+ @Use() private readonly config!: Config;
+ private get root(): string {
+ return this.config.root;
+ }
private filePath(projectId: string): string {
return projectConfigPath(this.root, projectId);
diff --git a/packages/server/src/services/project-service.ts b/packages/server/src/services/project-service.ts
index 2c585ce9..3eabf637 100644
--- a/packages/server/src/services/project-service.ts
+++ b/packages/server/src/services/project-service.ts
@@ -29,8 +29,11 @@ import {
SEMANTIC_ID_PATTERN,
SEMANTIC_ID_RULE,
} from "./ids.js";
+import type { ProjectAccess } from "./project-access.js";
import type { ProjectConfigService } from "./project-config-service.js";
import type { TraceIndexService } from "./trace-index.js";
+import { Component, Use, Interface } from "@prismshadow/penguin-core/kernel";
+import type { Config } from "../hmr/capabilities.js";
/** Fallback timeout for waiting on runs to settle before deleting a Project. */
const ABORT_SETTLE_TIMEOUT_MS = 5000;
@@ -44,103 +47,47 @@ async function dirExists(path: string): Promise<boolean> {
}
}
-export interface ProjectServiceDeps {
- root: string;
- users: UsersRepo;
- projects: ProjectsRepo;
- members: MembersRepo;
- agents: AgentsRepo;
- sessions: SessionsRepo;
- usage: UsageRepo;
- errors: ErrorsRepo;
- schedules: SchedulesRepo;
- projectConfig: ProjectConfigService;
- manager: SessionManager;
- /** Trace-index cleanup on Project destruction (rows describe files removed with the Project dir). */
- traceIndex: TraceIndexService;
-}
-
+@Component()
export class ProjectService {
- constructor(private readonly deps: ProjectServiceDeps) {}
-
- // —— Authorization rules (single implementation point) ——
-
- /**
- * The **sole** implementation of the owner / member check: returns the row with
- * a role if accessible, otherwise null. `requireProjectAccess` below (throws 404)
- * and `canAccess` (returns boolean) are both just wrappers around it — there's
- * only one copy of the decision rule, since writing it twice would eventually
- * drift out of sync.
- */
- private resolveAccess(
- userId: string,
- projectId: string,
- ): (ProjectRow & { role: ProjectRole }) | null {
- const row = this.deps.projects.findById(projectId);
- if (!row) return null;
- if (row.ownerUserId === userId) return { ...row, role: "owner" };
- if (this.deps.members.isMember(projectId, userId)) return { ...row, role: "member" };
- return null;
+ @Use() private readonly config!: Config;
+ private get root(): string {
+ return this.config.root;
}
+ @Use() private readonly access!: ProjectAccess;
+ @Use() private readonly users!: UsersRepo;
+ @Use() private readonly projects!: ProjectsRepo;
+ @Use() private readonly members!: MembersRepo;
+ @Use() private readonly agents!: AgentsRepo;
+ @Use() private readonly sessions!: SessionsRepo;
+ @Use() private readonly usage!: UsageRepo;
+ @Use() private readonly errors!: ErrorsRepo;
+ @Use() private readonly schedules!: SchedulesRepo;
+ @Use() private readonly projectConfig!: ProjectConfigService;
+ /** What destroying a Project needs of the session runtime — declared at the consumer. */
+ @Use() private readonly manager!: ProjectRuns;
+ /** Trace-index cleanup on Project destruction (rows describe files removed with the Project dir). */
+ @Use() private readonly traceIndex!: TraceIndexService;
- /** Accessible by owner or member; otherwise 404 (does not leak Project existence). */
+ // Access control lives in ProjectAccess (services/project-access.ts); these delegate so
+ // in-package callers keep one entry point.
requireProjectAccess(userId: string, projectId: string): ProjectRow & { role: ProjectRole } {
- const row = this.resolveAccess(userId, projectId);
- if (!row) {
- throw new HttpError(
- 404,
- "project_not_found",
- "Project does not exist or you do not have access.",
- );
- }
- return row;
+ return this.access.requireProjectAccess(userId, projectId);
}
- /**
- * The non-throwing version of the same check: used for **error attribution**
- * (app.onError) — that runs on the error-handling path, where throwing another
- * 404 would only break error handling; whether access is granted shouldn't be
- * expressed as an exception there anyway.
- */
canAccess(userId: string, projectId: string): boolean {
- return this.resolveAccess(userId, projectId) !== null;
+ return this.access.canAccess(userId, projectId);
}
- /** Owner only: 403 when known accessible as a member; 404 when not accessible. */
requireProjectOwner(userId: string, projectId: string): ProjectRow {
- const row = this.requireProjectAccess(userId, projectId);
- if (row.role !== "owner") {
- throw new HttpError(
- 403,
- "owner_required",
- "Only the Project owner can perform this operation.",
- );
- }
- return row;
+ return this.access.requireProjectOwner(userId, projectId);
}
- /** List of project_ids accessible to the current user (owned + granted access) (used by workspace-guard). */
accessibleProjectIds(userId: string): string[] {
- return this.deps.projects.listAccessible(userId).map((p) => p.projectId);
+ return this.access.accessibleProjectIds(userId);
}
- // —— Project lifecycle ——
-
- /** List of owned + granted-access Projects; display names are read from each project_config.toml. */
- async listProjects(userId: string): Promise<ProjectSummary[]> {
- const rows = this.deps.projects.listAccessible(userId);
- return Promise.all(
- rows.map(async (row) => {
- const name = await this.deps.projectConfig.getName(row.projectId);
- return {
- projectId: row.projectId,
- ...(name !== undefined ? { name } : {}),
- role: row.role,
- ownerUserId: row.ownerUserId,
- createdAt: row.createdAt,
- };
- }),
- );
+ listProjects(userId: string): Promise<ProjectSummary[]> {
+ return this.access.listProjects(userId);
}
/**
@@ -175,8 +122,8 @@ export class ProjectService {
}
}
if (
- this.deps.projects.findById(projectId) !== null ||
- (await dirExists(projectDir(this.deps.root, projectId)))
+ this.projects.findById(projectId) !== null ||
+ (await dirExists(projectDir(this.root, projectId)))
) {
throw new HttpError(409, "project_exists", `Project id is already taken: ${projectId}.`);
}
@@ -187,7 +134,7 @@ export class ProjectService {
// conflict is mapped to 409 with **no cleanup** — the directory belongs to the
// winner, and cleaning up here would wrongly delete the other side's data.
try {
- this.deps.projects.insert({ projectId, ownerUserId: owner.userId, createdAt });
+ this.projects.insert({ projectId, ownerUserId: owner.userId, createdAt });
} catch (err) {
if (err instanceof Error && err.message.includes("UNIQUE")) {
throw new HttpError(409, "project_exists", `Project id is already taken: ${projectId}.`);
@@ -199,13 +146,13 @@ export class ProjectService {
// (a typical scenario: signup failure rolled back the user row, but the
// <username>-default_project directory was left behind).
try {
- await fs.mkdir(projectDir(this.deps.root, projectId), { recursive: true });
- await this.deps.projectConfig.writeInitialConfig(projectId, displayName);
+ await fs.mkdir(projectDir(this.root, projectId), { recursive: true });
+ await this.projectConfig.writeInitialConfig(projectId, displayName);
await this.provisionBuiltinAgents(projectId);
} catch (err) {
- this.deps.projects.delete(projectId);
+ this.projects.delete(projectId);
await fs
- .rm(projectDir(this.deps.root, projectId), { recursive: true, force: true })
+ .rm(projectDir(this.root, projectId), { recursive: true, force: true })
.catch(() => {});
throw err;
}
@@ -237,8 +184,8 @@ export class ProjectService {
// models and the default model are backfilled instead (only when there are no
// models at all; a default_project already configured via the CLI is left
// as-is).
- await this.deps.projectConfig.ensurePresetModels(projectId);
- this.deps.projects.insert({
+ await this.projectConfig.ensurePresetModels(projectId);
+ this.projects.insert({
projectId,
ownerUserId: user.userId,
createdAt: new Date().toISOString(),
@@ -253,7 +200,7 @@ export class ProjectService {
*/
async renameProject(userId: string, projectId: string, name: string): Promise<ProjectSummary> {
const row = this.requireProjectOwner(userId, projectId);
- await this.deps.projectConfig.setName(projectId, name);
+ await this.projectConfig.setName(projectId, name);
// requireProjectOwner already established the role; it returns the plain row.
return {
projectId,
@@ -281,7 +228,7 @@ export class ProjectService {
"default_project is shared with the CLI and cannot be deleted from the web.",
);
}
- if (this.deps.projects.listAccessible(userId).length <= 1) {
+ if (this.projects.listAccessible(userId).length <= 1) {
throw new HttpError(
409,
"cannot_delete_last_project",
@@ -299,21 +246,21 @@ export class ProjectService {
* directory, to avoid the Trace writer recreating the directory after deletion.
*/
async destroyProject(projectId: string): Promise<void> {
- const runnings = this.deps.manager.abortProject(projectId);
+ const runnings = this.manager.abortProject(projectId);
if (runnings.length > 0) {
await Promise.race([
Promise.allSettled(runnings).then(() => undefined),
new Promise<void>((resolve) => setTimeout(resolve, ABORT_SETTLE_TIMEOUT_MS).unref?.()),
]);
}
- this.deps.projects.delete(projectId); // project_members and machine_project cascade-deleted
- this.deps.agents.deleteByProject(projectId);
- this.deps.sessions.deleteByProject(projectId);
- this.deps.usage.deleteByProject(projectId);
- this.deps.errors.deleteByProject(projectId);
- this.deps.schedules.deleteByProject(projectId);
- this.deps.traceIndex.removeProject(projectId);
- await fs.rm(projectDir(this.deps.root, projectId), { recursive: true, force: true });
+ this.projects.delete(projectId); // project_members and machine_project cascade-deleted
+ this.agents.deleteByProject(projectId);
+ this.sessions.deleteByProject(projectId);
+ this.usage.deleteByProject(projectId);
+ this.errors.deleteByProject(projectId);
+ this.schedules.deleteByProject(projectId);
+ this.traceIndex.removeProject(projectId);
+ await fs.rm(projectDir(this.root, projectId), { recursive: true, force: true });
}
// —— Member authorization ——
@@ -321,7 +268,7 @@ export class ProjectService {
/** Member list: owner (role=owner) + members. */
listMembers(userId: string, projectId: string): MemberInfo[] {
const project = this.requireProjectAccess(userId, projectId);
- const members = this.deps.members.list(projectId);
+ const members = this.members.list(projectId);
return [
{ userId: project.ownerUserId, role: "owner", createdAt: project.createdAt },
...members.map((m) => ({
@@ -335,7 +282,7 @@ export class ProjectService {
/** Grant member access (owner): invites by username; 404 if the user doesn't exist, 409 for the owner themself or an existing member. */
addMember(userId: string, projectId: string, targetUserId: string): MemberInfo {
const project = this.requireProjectOwner(userId, projectId);
- const target = this.deps.users.findById(targetUserId);
+ const target = this.users.findById(targetUserId);
if (!target) {
throw new HttpError(404, "user_not_found", `User does not exist: ${targetUserId}.`);
}
@@ -346,7 +293,7 @@ export class ProjectService {
"The owner does not need to grant access to themselves.",
);
}
- if (this.deps.members.isMember(projectId, target.userId)) {
+ if (this.members.isMember(projectId, target.userId)) {
throw new HttpError(
409,
"already_member",
@@ -354,17 +301,17 @@ export class ProjectService {
);
}
const createdAt = new Date().toISOString();
- this.deps.members.insert({ projectId, userId: target.userId, createdAt });
+ this.members.insert({ projectId, userId: target.userId, createdAt });
return { userId: target.userId, role: "member", createdAt };
}
/** Revoke member access (owner). */
removeMember(userId: string, projectId: string, targetUserId: string): void {
this.requireProjectOwner(userId, projectId);
- if (!this.deps.members.isMember(projectId, targetUserId)) {
+ if (!this.members.isMember(projectId, targetUserId)) {
throw new HttpError(404, "member_not_found", `This Project has no member: ${targetUserId}.`);
}
- this.deps.members.delete(projectId, targetUserId);
+ this.members.delete(projectId, targetUserId);
}
/**
@@ -376,10 +323,10 @@ export class ProjectService {
* guarantee.
*/
private async provisionBuiltinAgents(projectId: string): Promise<void> {
- const agentIds = await provisionProjectAgents({ root: this.deps.root, projectId });
+ const agentIds = await provisionProjectAgents({ root: this.root, projectId });
const base = Date.now();
agentIds.forEach((agentId, i) => {
- this.deps.agents.insertOrIgnore({
+ this.agents.insertOrIgnore({
projectId,
agentId,
createdAt: new Date(base + i).toISOString(),
@@ -387,3 +334,8 @@ export class ProjectService {
});
}
}
+
+/** What destroying a Project needs of the session runtime — declared at the consumer. */
+export abstract class ProjectRuns extends Interface<{
+ abortProject(projectId: string): Promise<void>[];
+}>() {}
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index e983880c..5a1d0a06 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -79,7 +79,7 @@ export interface SessionServiceDeps {
* means the field is never set.
*/
messagingChannel?: (sessionId: string) => MessagingChannel | null;
- /** Spawn-confinement getter (see app.ts): claimed from the platform's registered resource, forwarded into core beside proxyEnv. */
+ /** Spawn-confinement getter (the sandbox module's), forwarded into core beside proxyEnv. */
confineSpawn?: () => SpawnConfiner | null;
}
diff --git a/packages/server/src/services/snapshot-service.ts b/packages/server/src/services/snapshot-service.ts
index b7cc824d..f16217cf 100644
--- a/packages/server/src/services/snapshot-service.ts
+++ b/packages/server/src/services/snapshot-service.ts
@@ -25,6 +25,8 @@ import {
} from "@prismshadow/penguin-core";
import { HttpError } from "../http/errors.js";
import { badRequest } from "../http/validate.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Config } from "../hmr/capabilities.js";
/** Vault file name inside a snapshot/import package (used for archive filtering). */
const VAULT_BASENAME = ".vault.toml";
@@ -33,8 +35,12 @@ function isVaultEntry(entryPath: string): boolean {
return path.posix.basename(entryPath.replaceAll("\\", "/")) === VAULT_BASENAME;
}
+@Component()
export class SnapshotService {
- constructor(private readonly root: string) {}
+ @Use() private readonly config!: Config;
+ private get root(): string {
+ return this.config.root;
+ }
/** Current Agent State version number (missing field treated as 1); throws 404 if the Agent doesn't exist. */
async currentVersion(projectId: string, agentId: string): Promise<number> {
diff --git a/packages/server/src/services/trace-index.ts b/packages/server/src/services/trace-index.ts
index 2737a18f..b92515ec 100644
--- a/packages/server/src/services/trace-index.ts
+++ b/packages/server/src/services/trace-index.ts
@@ -48,6 +48,8 @@ import { readTraceHead } from "../internal/trace-head.js";
import { asSessionSource } from "../runtime/session-sources.js";
import type { SessionSources } from "../runtime/session-sources.js";
import { fallbackTitle } from "../runtime/title-generator.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Config } from "../hmr/capabilities.js";
const TRACE_FILE_RE = /^(.+)_(\d{3})\.jsonl$/;
@@ -112,6 +114,7 @@ interface SeenDirs {
dates: Map<string, number>;
}
+@Component()
export class TraceIndexService {
private readonly seen = new Map<string, SeenDirs>();
private readonly inflight = new Map<string, Promise<void>>();
@@ -122,12 +125,13 @@ export class TraceIndexService {
*/
readonly counters = { gateStats: 0, dirScans: 0, headReads: 0 };
- constructor(
- private readonly root: string,
- readonly repo: TraceIndexRepo,
- /** Shared origin registry: registration-time classification publishes into it (single source of truth for `source`). */
- private readonly sources?: SessionSources,
- ) {}
+ @Use() private readonly config!: Config;
+ private get root(): string {
+ return this.config.root;
+ }
+ @Use() readonly repo!: TraceIndexRepo;
+ /** Shared origin registry: registration-time classification publishes into it (single source of truth for `source`). */
+ @Use() private readonly sources?: SessionSources;
/**
* Brings one Agent's index in step with disk. Hot path: one root stat, then the
diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.ts
index 3793cf5f..df06f727 100644
--- a/packages/server/src/services/trace-service.ts
+++ b/packages/server/src/services/trace-service.ts
@@ -50,13 +50,14 @@ import type {
TraceToolSpan,
UsageTrendPointInTrace,
} from "../api/types.js";
-import type { SessionRow } from "../db/repos/sessions.js";
+import type { SessionRow, SessionsRepo } from "../db/repos/sessions.js";
import type { TraceFileRow, TraceSessionRow } from "../db/repos/trace-index.js";
import { HttpError } from "../http/errors.js";
import { formatLocalDate } from "../internal/dates.js";
import type { SessionSources } from "../runtime/session-sources.js";
import { ratesAt, requestCostUsd } from "./usage-service.js";
import type { PricingLookup, TieredRates } from "./usage-service.js";
+import type { ProjectConfigService } from "./project-config-service.js";
import {
cloneScanState,
deserializePrefix,
@@ -76,6 +77,8 @@ import type {
import { buildContextBreakdown, emptyContextBreakdown } from "./context-breakdown.js";
import { sessionIdCreatedAt } from "./session-service.js";
import { TraceIndexService, traceFilePath } from "./trace-index.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Config } from "../hmr/capabilities.js";
const TRACE_FILE_RE = /^(.+)_(\d{3})\.jsonl$/;
@@ -242,38 +245,38 @@ export interface TraceSessionIndex {
}
/** TraceService wiring (the trace-file index is required: every listing/locating path serves from it — no directory walks). */
-export interface TraceServiceDeps {
- index: TraceIndexService;
- /** Optional (narrow tests may omit): DB rows supplying titles / archived / workspace / client. */
- sessions?: TraceSessionIndex;
- /** Optional (narrow tests may omit): the shared in-process Session-origin registry (single source of truth for `source`). */
- sources?: SessionSources;
- /**
- * Optional (narrow tests may omit): the Project's current price for a paired reference —
- * the same lookup the cost center prices `usage_records` with, so the analysis' per-turn
- * cost and the toolbar's figure come from one price table. Absent, the analysis carries no
- * cost at all.
- */
- lookupPricing?: PricingLookup;
- /**
- * Test observability: called with the path of every Trace shard this service reads
- * from disk (windowed-read tests assert an old-window request never touches the
- * newest shard and vice versa). Production wiring omits it.
- */
- observeShardRead?: (path: string) => void;
-}
-
/** One Session's classification result (see classify): its sidebar category + Workspace path ("" = unknown). */
interface TraceSessionFacts {
category: SessionCategory;
workspace: string;
}
+@Component()
export class TraceService {
- constructor(
- private readonly root: string,
- private readonly deps: TraceServiceDeps,
- ) {}
+ @Use() private readonly config!: Config;
+ private get root(): string {
+ return this.config.root;
+ }
+ @Use() private readonly index!: TraceIndexService;
+ /** DB rows supplying titles / archived / workspace / client (narrow tests may omit). */
+ @Use() private readonly sessions?: SessionsRepo;
+ /** The shared in-process Session-origin registry, single source of truth for `source` (narrow tests may omit). */
+ @Use() private readonly sources?: SessionSources;
+ @Use() private readonly projectConfig?: ProjectConfigService;
+ /**
+ * The Project's current price for a paired reference — the same lookup the cost center
+ * prices `usage_records` with, so the analysis' per-turn cost and the toolbar's figure come
+ * from one price table. Narrow tests wire their own or none; without a price the analysis
+ * carries no cost at all.
+ */
+ private lookupPricing: PricingLookup = async (projectId, provider, modelId) =>
+ this.projectConfig?.getPricing(projectId, provider, modelId);
+ /**
+ * Test observability: called with the path of every Trace shard this service reads
+ * from disk (windowed-read tests assert an old-window request never touches the
+ * newest shard and vice versa). Production wiring leaves it unset.
+ */
+ observeShardRead?: (path: string) => void;
/**
* All of this Session's Trace files (sorted by index ascending), served from the
@@ -288,11 +291,11 @@ export class TraceService {
agentId: string,
sessionId: string,
): Promise<LocatedFile[]> {
- await this.deps.index.reconcileAgent(projectId, agentId);
- let rows = this.deps.index.repo.listFilesBySession(projectId, agentId, sessionId);
+ await this.index.reconcileAgent(projectId, agentId);
+ let rows = this.index.repo.listFilesBySession(projectId, agentId, sessionId);
if (rows.length === 0) {
- await this.deps.index.reconcileAgent(projectId, agentId, { force: true });
- rows = this.deps.index.repo.listFilesBySession(projectId, agentId, sessionId);
+ await this.index.reconcileAgent(projectId, agentId, { force: true });
+ rows = this.index.repo.listFilesBySession(projectId, agentId, sessionId);
}
return rows.map((r) => ({
path: traceFilePath(this.root, r),
@@ -304,7 +307,7 @@ export class TraceService {
/** All shard reads funnel through here (deps.observeShardRead is the windowed-read tests' proof of which files were touched). */
private async readShard(path: string): Promise<OmniMessage[]> {
- this.deps.observeShardRead?.(path);
+ this.observeShardRead?.(path);
return readTraceTolerant(path);
}
@@ -314,7 +317,7 @@ export class TraceService {
for (const file of files) {
await fs.rm(file.path, { force: true });
}
- this.deps.index.removeSession(projectId, agentId, sessionId);
+ this.index.removeSession(projectId, agentId, sessionId);
}
/**
@@ -365,11 +368,11 @@ export class TraceService {
childSid: string,
ctx: { projectScanned: boolean },
): Promise<string | null> {
- const hit = this.deps.index.repo.findAgentBySession(projectId, childSid);
+ const hit = this.index.repo.findAgentBySession(projectId, childSid);
if (hit !== null || ctx.projectScanned) return hit;
ctx.projectScanned = true;
- await this.deps.index.reconcileProject(projectId, { force: true });
- return this.deps.index.repo.findAgentBySession(projectId, childSid);
+ await this.index.reconcileProject(projectId, { force: true });
+ return this.index.repo.findAgentBySession(projectId, childSid);
}
/** A child session's concatenated raw shard messages, memoized per request; null = no Trace located. */
@@ -493,7 +496,7 @@ export class TraceService {
for (let j = 0; j <= upto; j++) {
const file = files[j]!;
const cached = deserializePrefix(
- this.deps.index.repo.getPageStats(projectId, agentId, sessionId, file.index),
+ this.index.repo.getPageStats(projectId, agentId, sessionId, file.index),
);
if (cached !== null) {
states.push(cached);
@@ -507,7 +510,7 @@ export class TraceService {
() => {},
(sid) => this.aggregateChild(projectId, sid, ctx),
);
- this.deps.index.repo.setPageStats(
+ this.index.repo.setPageStats(
projectId,
agentId,
sessionId,
@@ -774,7 +777,7 @@ export class TraceService {
const body = records.map((record) => JSON.stringify(record)).join("\n") + "\n";
await fs.writeFile(file, body, { encoding: "utf8", flag: "wx" });
written.push(file);
- this.deps.index.registerImportedFile({
+ this.index.registerImportedFile({
projectId,
agentId,
sessionId: newSessionId,
@@ -788,7 +791,7 @@ export class TraceService {
} catch (err) {
await Promise.all(written.map((file) => fs.rm(file, { force: true }).catch(() => undefined)));
await fs.rm(forkScratchpad, { recursive: true, force: true }).catch(() => undefined);
- this.deps.index.removeSession(projectId, agentId, newSessionId);
+ this.index.removeSession(projectId, agentId, newSessionId);
throw err;
}
}
@@ -862,7 +865,6 @@ export class TraceService {
projectId: string,
messages: OmniMessage[],
): Promise<{ provider: string; modelId: string; rates: TieredRates } | null> {
- if (this.deps.lookupPricing === undefined) return null;
const meta = messages.find(
(m) => isSessionMeta(m) && (m.origin === undefined || m.origin.length === 0),
);
@@ -873,7 +875,7 @@ export class TraceService {
};
if (typeof provider !== "string" || provider === "") return null;
if (typeof modelId !== "string" || modelId === "") return null;
- const rates = await this.deps.lookupPricing(projectId, provider, modelId);
+ const rates = await this.lookupPricing(projectId, provider, modelId);
return rates === undefined ? null : { provider, modelId, rates };
}
@@ -1454,8 +1456,8 @@ export class TraceService {
paging?: { offset: number; limit: number } | null,
opts: { category?: SessionCategory } = {},
): Promise<AgentTracesResponse> {
- await this.deps.index.reconcileAgent(projectId, agentId);
- const files = this.deps.index.repo.listFilesByAgent(projectId, agentId);
+ await this.index.reconcileAgent(projectId, agentId);
+ const files = this.index.repo.listFilesByAgent(projectId, agentId);
if (paging) return this.agentTracesPage(projectId, agentId, files, paging, opts);
const byDate = new Map<string, Map<string, { index: number; sizeBytes: number }[]>>();
for (const f of files) {
@@ -1494,7 +1496,7 @@ export class TraceService {
row: SessionRow | undefined,
facts: TraceSessionRow | undefined,
): TraceSessionFacts {
- const known = this.deps.sources?.get(sessionId);
+ const known = this.sources?.get(sessionId);
// Registry answer (including null = known user-created) wins — it can be fresher
// (subagent registration happens at spawn, before any reconcile); else the stored facts.
const source = known !== undefined ? known : (facts?.source ?? undefined);
@@ -1524,10 +1526,10 @@ export class TraceService {
// One indexed query per source: the Agent's DB rows (title / archived / workspace /
// client) and the registration-time facts.
const rows = new Map(
- (this.deps.sessions?.listByAgent(projectId, agentId) ?? []).map((r) => [r.sessionId, r]),
+ (this.sessions?.listByAgent(projectId, agentId) ?? []).map((r) => [r.sessionId, r]),
);
const factsBySession = new Map(
- this.deps.index.repo.listSessionsByAgent(projectId, agentId).map((r) => [r.sessionId, r]),
+ this.index.repo.listSessionsByAgent(projectId, agentId).map((r) => [r.sessionId, r]),
);
const ids = [...bySession.keys()].sort((a, b) => b.localeCompare(a));
// Classify every group once; the same result drives the category filter, the
@@ -1573,13 +1575,7 @@ export class TraceService {
try {
sizeBytes = (await fs.stat(traceFilePath(this.root, f))).size;
if (sizeBytes !== f.sizeBytes) {
- this.deps.index.repo.updateFileSize(
- projectId,
- agentId,
- sessionId,
- f.fileIndex,
- sizeBytes,
- );
+ this.index.repo.updateFileSize(projectId, agentId, sessionId, f.fileIndex, sizeBytes);
}
} catch {
/* Vanished mid-request: serve the last observed size; the next reconcile settles the rows. */
@@ -1690,7 +1686,7 @@ export class TraceService {
// the existing one, and the list folded the two into a single conversation, leaving a
// group's count one above the rows it could ever show.
if ((await this.locateAll(projectId, agentId, sessionId)).length > 0) throw duplicate();
- if (this.deps.sessions?.findById?.(sessionId)) throw duplicate();
+ if (this.sessions?.findById?.(sessionId)) throw duplicate();
const ts = Date.parse(first.timestamp);
const date = formatLocalDate(Number.isNaN(ts) ? new Date() : new Date(ts));
const index = 1;
@@ -1710,7 +1706,7 @@ export class TraceService {
}
// Write-time registration: this path knows the file's identity and already holds the
// parsed records, so the index row + session facts land synchronously (no re-read).
- this.deps.index.registerImportedFile({
+ this.index.registerImportedFile({
projectId,
agentId,
sessionId,
@@ -1739,11 +1735,11 @@ export class TraceService {
* half-formed — the Trace file itself is already written and readable either way.
*/
private indexImportedSession(projectId: string, agentId: string, sessionId: string): void {
- const sessions = this.deps.sessions;
+ const sessions = this.sessions;
if (!sessions) return;
- const facts = this.deps.index.repo.getSession(sessionId);
+ const facts = this.index.repo.getSession(sessionId);
if (!facts?.metaRead || facts.provider === null || facts.modelId === null) return;
- if (facts.source !== null) this.deps.sources?.set(sessionId, facts.source);
+ if (facts.source !== null) this.sources?.set(sessionId, facts.source);
const createdAt = sessionIdCreatedAt(sessionId) ?? facts.firstTs ?? new Date().toISOString();
sessions.insertOrIgnore?.({
sessionId,
diff --git a/packages/server/src/services/update-check-service.ts b/packages/server/src/services/update-check-service.ts
index aea3b423..642a8ffc 100644
--- a/packages/server/src/services/update-check-service.ts
+++ b/packages/server/src/services/update-check-service.ts
@@ -18,6 +18,13 @@
*/
import { BUILD_DATE, VERSION, compareVersions, normalizeVersion } from "@prismshadow/penguin-core";
import type { UpdateCheckResponse } from "../api/types.js";
+import { Interface, Bind, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";
+import type { AppEnv } from "../auth/middleware.js";
+import type { Hono } from "hono";
+import type { ClassCtx } from "@prismshadow/penguin-core/kernel";
+import { Config, Lifecycle, Overrides, RuntimeModule } from "../hmr/capabilities.js";
+import { UpdateJobService } from "./update-job.js";
+import { versionRoutes } from "../http/routes/version.js";
/** Repository the released artifacts come from (same slug as cli/update.ts's REPO_SLUG). */
const REPO_SLUG = "Prism-Shadow/penguin-harness";
@@ -139,3 +146,38 @@ export class UpdateCheckService {
};
}
}
+
+export abstract class UpdateCheck extends Interface<Pick<UpdateCheckService, "check">>() {}
+
+@Module({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "VersionModule.routes",
+ prefix: "/api/version",
+ auth: "user",
+ order: 20,
+ },
+ ],
+ },
+})
+export class VersionModule {
+ @Use(RuntimeModule) private readonly config!: Config;
+ @Use(RuntimeModule) private readonly overrides!: Overrides;
+ @Use(RuntimeModule) private readonly lifecycle!: Lifecycle;
+ @Provide() updateCheck!: UpdateCheck;
+ @Bind("VersionModule.routes") routes!: Hono<AppEnv>;
+ setup() {
+ const overrides = this.overrides.value();
+ const updateCheck =
+ overrides.updateCheck ?? new UpdateCheckService(overrides.now ? { now: overrides.now } : {});
+ this.updateCheck = updateCheck;
+ const updateJob = overrides.updateJob ?? new UpdateJobService();
+ this.routes = versionRoutes({
+ config: this.config,
+ updateCheck,
+ updateJob,
+ lifecycle: this.lifecycle,
+ });
+ }
+}
diff --git a/packages/server/src/services/usage-service.ts b/packages/server/src/services/usage-service.ts
index c691aa17..51969dd1 100644
--- a/packages/server/src/services/usage-service.ts
+++ b/packages/server/src/services/usage-service.ts
@@ -51,6 +51,9 @@ import {
localDateMinusDays,
} from "../internal/dates.js";
import { badRequest } from "../http/validate.js";
+import { Component, Use } from "@prismshadow/penguin-core/kernel";
+import type { Overrides } from "../hmr/capabilities.js";
+import type { ProjectConfigService } from "./project-config-service.js";
/**
* Number of most-recent entries kept in the error detail table. Also the page size the whole
@@ -185,13 +188,19 @@ function refKey(provider: string, modelId: string): string {
return `${provider}\0${modelId}`;
}
+@Component()
export class UsageService {
- constructor(
- private readonly usage: UsageRepo,
- private readonly errors: ErrorsRepo,
- private readonly lookupPricing: PricingLookup,
- private readonly now: () => Date = () => new Date(),
- ) {}
+ @Use() private readonly usage!: UsageRepo;
+ @Use() private readonly errors!: ErrorsRepo;
+ @Use() private readonly projectConfig!: ProjectConfigService;
+ @Use() private readonly overrides!: Overrides;
+ private lookupPricing: PricingLookup = (projectId, provider, modelId) =>
+ this.projectConfig.getPricing(projectId, provider, modelId);
+ private now: () => Date = () => new Date();
+
+ setup(): void {
+ this.now = this.overrides.value().now ?? this.now;
+ }
/**
* The catalog's time-based schedules, as the aggregations want them.
diff --git a/packages/server/src/services/workspace-files-service.ts b/packages/server/src/services/workspace-files-service.ts
index 5bdd4182..764c8945 100644
--- a/packages/server/src/services/workspace-files-service.ts
+++ b/packages/server/src/services/workspace-files-service.ts
@@ -17,6 +17,7 @@ import type {
} from "../api/types.js";
import { HttpError } from "../http/errors.js";
import { badRequest } from "../http/validate.js";
+import { Component } from "@prismshadow/penguin-core/kernel";
/** Per-file read cap (a safety limit since preview/download reads the whole file into memory). */
const MAX_READ_BYTES = 50 * 1024 * 1024;
@@ -124,6 +125,7 @@ export interface WorkspaceFileStat {
mtimeMs: number;
}
+@Component()
export class WorkspaceFilesService {
/** Canonical path (realpath) of the Workspace root; 404 if it doesn't exist. */
private async realBase(workspace: string): Promise<string> {
diff --git a/packages/server/src/terminal/manager.ts b/packages/server/src/terminal/manager.ts
index 7fd09b19..6762296e 100644
--- a/packages/server/src/terminal/manager.ts
+++ b/packages/server/src/terminal/manager.ts
@@ -12,16 +12,23 @@
* whatever it is running) alive — that is the entire point of a server-side terminal.
*/
import fsp from "node:fs/promises";
-import type { Resources } from "@prismshadow/penguin-core/kernel";
+import type { Resources, Opaque, ClassCtx, Json } from "@prismshadow/penguin-core/kernel";
import path from "node:path";
import { HttpError } from "../http/errors.js";
-import { spawnHelperHint } from "../terminal/spawn-helper.js";
+import { spawnHelperHint } from "./spawn-helper.js";
import {
TerminalSession,
expandHomePath,
type CreateTerminalSessionOptions,
type TerminalSessionInfo,
} from "./session.js";
+import { Interface, Bind, Module, Provide, Use } from "@prismshadow/penguin-core/kernel";
+import type { AppEnv } from "../auth/middleware.js";
+import type { Hono } from "hono";
+import { Hmr, ResourceGroups, RuntimeModule } from "../hmr/capabilities.js";
+import { terminalRoutes } from "./routes.js";
+import { identityFrom } from "./identity.js";
+import type { AuthService } from "../auth/service.js";
/** How long an exited session stays listable/attachable before it is disposed. */
export const EXITED_SESSION_GRACE_MS = 5 * 60 * 1000;
@@ -268,3 +275,69 @@ async function resolveCwd(input: string): Promise<string> {
function resourceId(sessionId: string): string {
return `terminal:${sessionId}`;
}
+
+/** A live pty: a host-like object (it owns a process), compared by name. */
+export type Terminal = Opaque<"TerminalSession", TerminalSession>;
+
+/** Live ptys: the spawn primitive behind /api/terminals and the terminal WebSocket. */
+export abstract class Terminals extends Interface<{
+ create(request: CreateTerminalRequest): Promise<Terminal>;
+ adopt(ids: readonly string[]): void;
+ quiesce(): void;
+ handleIds(): string[];
+ require(id: string, userId: string): Terminal;
+ get(id: string): Terminal | undefined;
+ list(userId: string): Terminal[];
+ listInfo(userId: string): TerminalSessionInfo[];
+ kill(id: string, userId: string): void;
+ disposeAll(): void;
+}>() {}
+
+/** The manager satisfies the contract; this keeps the two from drifting. */
+export type _Check = TerminalManager extends Terminals ? true : never;
+
+@Module({
+ contributes: {
+ "HttpModule.routes": [
+ {
+ id: "TerminalModule.routes",
+ prefix: "/",
+ auth: "none",
+ order: 0,
+ },
+ ],
+ },
+ context: {
+ version: 1,
+ schema: {
+ "terminals?": "string[]",
+ },
+ },
+})
+export class TerminalModule {
+ @Use(RuntimeModule) private readonly hmr!: Hmr;
+ @Use(RuntimeModule) private readonly resourceGroups!: ResourceGroups;
+ @Use() private readonly auth!: AuthService;
+ @Provide() terminals!: Terminals;
+ @Bind("TerminalModule.routes") routes!: ReturnType<typeof terminalRoutes>;
+ setup({ resources, effect }: ClassCtx, context: Json) {
+ const terminals = new TerminalManager(resources, {
+ // A pushed bundle's node-pty binaries live where the host materialized them.
+ assets: () => this.hmr.assetsDir() ?? null,
+ });
+ // Shells started before this App existed are still running in the registry: claim
+ // them back so a push is invisible to whoever was typing in one — unless their group
+ // is doomed, in which case this build cannot speak the contract behind those handles.
+ const parked = (context as { terminals?: string[] } | null)?.terminals ?? [];
+ terminals.adopt(this.resourceGroups.adoptable("TerminalModule") ? parked : []);
+ // Deliberately NOT disposing the terminals at swap: the shells are resources, and
+ // outliving a swap is the whole point. Only the reap timers stop with this App.
+ effect(() => terminals.quiesce());
+ this.terminals = terminals;
+ this.routes = terminalRoutes(terminals, identityFrom(this.auth));
+ }
+
+ park(): Json {
+ return { terminals: this.terminals.handleIds() };
+ }
+}
diff --git a/packages/server/test/auth.test.ts b/packages/server/test/auth.test.ts
index 915fe1bc..bfeb11a9 100644
--- a/packages/server/test/auth.test.ts
+++ b/packages/server/test/auth.test.ts
@@ -17,6 +17,7 @@ import {
provisionUser,
TEST_ADMIN_PASSWORD,
testConfig,
+ flattenForTests,
} from "./helpers.js";
import type { TestApp } from "./helpers.js";
@@ -202,9 +203,8 @@ describe("auth", () => {
it("seedAdmin rejects an override below the password policy before creating the account", async () => {
const root = await makeTempRoot();
- const deps = await bootAppDeps(
- { ...testConfig(root), seedAdminPassword: "x" },
- { log: () => {} },
+ const deps = flattenForTests(
+ await bootAppDeps({ ...testConfig(root), seedAdminPassword: "x" }, { log: () => {} }),
);
try {
await expect(deps.authService.seedAdmin()).rejects.toThrow(/at least 8 characters/);
diff --git a/packages/server/test/db-upgrade.test.ts b/packages/server/test/db-upgrade.test.ts
index f52d4de1..e6a6fd08 100644
--- a/packages/server/test/db-upgrade.test.ts
+++ b/packages/server/test/db-upgrade.test.ts
@@ -23,6 +23,7 @@ import { SCHEMA_SQL } from "../src/db/schema.js";
import { MessagingBindingsRepo } from "../src/db/repos/messaging-bindings.js";
import { SessionsRepo } from "../src/db/repos/sessions.js";
import type { SessionRow } from "../src/db/repos/sessions.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
const sqlite = process.getBuiltinModule("node:sqlite");
@@ -91,7 +92,7 @@ describe("openDatabase column upgrade", () => {
const db = openDatabase(dbPath);
try {
- const repo = new SessionsRepo(db);
+ const repo = wire(SessionsRepo, { db: db });
// The legacy row reads back with the grandfathered defaults: client NULL (treated as
// web — it stays in the default list) and has_trace false.
const legacy = repo.findById("session-legacy");
@@ -156,7 +157,7 @@ describe("openDatabase column upgrade", () => {
const db = openDatabase(dbPath);
try {
- const repo = new MessagingBindingsRepo(db);
+ const repo = wire(MessagingBindingsRepo, { db: db });
// The pre-existing binding survives with its credentials, its intent and its reply
// target; only the watermark is new, and it grandfathers in as null — the honest value
// for a binding whose past messages this build never saw an id for.
@@ -210,7 +211,7 @@ describe("openDatabase column upgrade", () => {
const db = openDatabase(dbPath);
try {
- const repo = new SessionsRepo(db);
+ const repo = wire(SessionsRepo, { db: db });
// The most recent request timestamp is the closest persisted proxy for last Trace
// activity. Read raw as well: mapRow would report created_at for a row the backfill
// never touched, hiding a no-op migration behind a plausible-looking value.
@@ -234,7 +235,7 @@ describe("openDatabase column upgrade", () => {
const reopened = openDatabase(dbPath);
try {
- const repo = new SessionsRepo(reopened);
+ const repo = wire(SessionsRepo, { db: reopened });
expect(repo.findById("session-used")!.lastActiveAt).toBe("2026-02-03T09:30:00.000Z");
expect(repo.findById("session-quiet")!.lastActiveAt).toBe("2026-03-01T00:00:00.000Z");
} finally {
@@ -264,7 +265,7 @@ describe("openDatabase column upgrade", () => {
expect(rawLastActive(db, "session-1")).toBeNull();
// ...and mapRow's coalesce is what keeps that invisible to callers: the safety net,
// not the mechanism (nothing else can repair a NULL once the gate has closed).
- expect(new SessionsRepo(db).findById("session-1")!.lastActiveAt).toBe(
+ expect(wire(SessionsRepo, { db: db }).findById("session-1")!.lastActiveAt).toBe(
"2026-01-01T00:00:00.000Z",
);
} finally {
@@ -289,7 +290,7 @@ describe("SessionsRepo last_active_at writes", () => {
beforeEach(() => {
db = openDatabase(":memory:");
- repo = new SessionsRepo(db);
+ repo = wire(SessionsRepo, { db: db });
});
afterEach(() => {
db.close();
@@ -395,10 +396,10 @@ describe("openDatabase table and index upgrades", () => {
)
.all(),
).toHaveLength(1);
- expect(new SessionsRepo(db).findById("session-pre-messaging")).not.toBeNull();
+ expect(wire(SessionsRepo, { db: db }).findById("session-pre-messaging")).not.toBeNull();
// And it is immediately writable — a newly created table with no rows would look
// identical to one the upgrade forgot to create until something tries to use it.
- const repo = new MessagingBindingsRepo(db);
+ const repo = wire(MessagingBindingsRepo, { db: db });
expect(
repo.upsert({
sessionId: "session-pre-messaging",
@@ -472,7 +473,7 @@ describe("openDatabase table and index upgrades", () => {
const db = openDatabase(dbPath);
try {
- const repo = new MessagingBindingsRepo(db);
+ const repo = wire(MessagingBindingsRepo, { db: db });
const row = repo.find("session-old", "feishu");
// ON, unlike every other added flag: this column's default is the CORRECTED behaviour
// rather than the previous one, so an existing binding starts rendering Markdown after
@@ -522,7 +523,7 @@ describe("openDatabase table and index upgrades", () => {
const db = openDatabase(dbPath);
try {
- const repo = new MessagingBindingsRepo(db);
+ const repo = wire(MessagingBindingsRepo, { db: db });
const row = repo.find("session-old", "telegram");
// The column arrives with a default that reproduces the behaviour the row already had —
// one message per reply — so the upgrade cannot change how an existing binding delivers.
@@ -561,7 +562,7 @@ describe("openDatabase table and index upgrades", () => {
const db = openDatabase(dbPath);
try {
- const repo = new MessagingBindingsRepo(db);
+ const repo = wire(MessagingBindingsRepo, { db: db });
const row = repo.find("session-old", "telegram");
// The default reproduces the delivery the row already had — every completed message
// mirrored as it completed — so the upgrade cannot change how a binding behaves.
@@ -653,7 +654,7 @@ describe("openDatabase table and index upgrades", () => {
).toHaveLength(1);
// The row written under the old rule survived, and a second Session may now keep the
// same account saved beside it — the write the unique index used to reject.
- const repo = new MessagingBindingsRepo(db);
+ const repo = wire(MessagingBindingsRepo, { db: db });
expect(repo.find("session-a", "telegram")?.accountId).toBe("12345");
expect(
repo.upsert({
@@ -703,7 +704,7 @@ describe("openDatabase table and index upgrades", () => {
});
const db = openDatabase(dbPath);
try {
- const repo = new MessagingBindingsRepo(db);
+ const repo = wire(MessagingBindingsRepo, { db: db });
expect(repo.find("session-a", "telegram")?.enabled).toBe(true);
expect(repo.findEnabledByAccount("telegram", "99999")?.sessionId).toBe("session-a");
} finally {
@@ -746,7 +747,7 @@ describe("openDatabase tolerates a database from a newer build", () => {
it("leaves unknown tables, columns and indexes intact across an open", () => {
const dbPath = path.join(dir, "web.db");
const current = openDatabase(dbPath);
- new SessionsRepo(current).insert({
+ wire(SessionsRepo, { db: current }).insert({
sessionId: "s1",
projectId: "p1",
agentId: "a1",
@@ -790,7 +791,7 @@ describe("openDatabase tolerates a database from a newer build", () => {
).toHaveLength(1);
// And this build still reads and writes the rows it does own, alongside the column it
// cannot see — the unknown column's DEFAULT is what keeps this insert legal.
- const repo = new SessionsRepo(reopened);
+ const repo = wire(SessionsRepo, { db: reopened });
expect(repo.findById("s1")!.lastActiveAt).toBe("2026-05-01T00:00:00.000Z");
repo.insert({
sessionId: "s2",
@@ -829,7 +830,7 @@ describe("openDatabase tolerates a database from a newer build", () => {
const opened = openDatabase(formedByNewer);
try {
expect(() =>
- new SessionsRepo(opened).insert({
+ wire(SessionsRepo, { db: opened }).insert({
sessionId: "s1",
projectId: "p1",
agentId: "a1",
@@ -859,7 +860,7 @@ describe("openDatabase tolerates a database from a newer build", () => {
}
const reopenedIndexed = openDatabase(withUniqueIndex);
try {
- const repo = new SessionsRepo(reopenedIndexed);
+ const repo = wire(SessionsRepo, { db: reopenedIndexed });
const row = {
projectId: "p1",
agentId: "a1",
diff --git a/packages/server/test/errors.test.ts b/packages/server/test/errors.test.ts
index 08d1f6b6..c13389a1 100644
--- a/packages/server/test/errors.test.ts
+++ b/packages/server/test/errors.test.ts
@@ -41,6 +41,7 @@ import { MessagingConnectionClosedError } from "../src/runtime/messaging/qq-api.
import { StreamErrorWatcher } from "../src/runtime/stream-error-watcher.js";
import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
function row(date: string, o: Partial<ErrorRecordInsert> = {}): ErrorRecordInsert {
return {
@@ -64,7 +65,7 @@ describe("errors-repo", () => {
beforeEach(() => {
db = openDatabase(":memory:");
- repo = new ErrorsRepo(db);
+ repo = wire(ErrorsRepo, { db: db });
});
afterEach(() => db.close());
@@ -223,14 +224,14 @@ describe("errors-repo", () => {
.map((r) => r.message as string);
it("row cap: evicts the oldest rows by id (checked every pruneEvery inserts)", () => {
- const capped = new ErrorsRepo(db, { maxRows: 5, pruneEvery: 2 });
+ const capped = wire(ErrorsRepo, { db: db, maxRows: 5, pruneEvery: 2 });
for (let i = 0; i < 10; i++) capped.insert(row("2026-07-06", { message: `m${i}` }));
// The 5 most recent rows within the cap are kept, older ones are evicted.
expect(messages()).toEqual(["m5", "m6", "m7", "m8", "m9"]);
});
it("eviction counts rows: id gaps left by deleteByProject never misdelete valid data", () => {
- const capped = new ErrorsRepo(db, { maxRows: 3, pruneEvery: 1 });
+ const capped = wire(ErrorsRepo, { db: db, maxRows: 3, pruneEvery: 1 });
capped.insert(row("2026-07-06", { message: "keep-1" })); // id 1
capped.insert(row("2026-07-06", { message: "keep-2" })); // id 2
capped.insert(row("2026-07-06", { projectId: "p-gone", message: "gone" })); // id 3
@@ -253,12 +254,12 @@ describe("error-recorder", () => {
beforeEach(() => {
db = openDatabase(":memory:");
- repo = new ErrorsRepo(db);
+ repo = wire(ErrorsRepo, { db: db });
});
afterEach(() => db.close());
it("HttpError → expected (keeps code and status)", () => {
- new ErrorRecorder(repo, now).record({
+ wire(ErrorRecorder, { errors: repo, now: now }).record({
source: "http",
err: new HttpError(
404,
@@ -276,7 +277,7 @@ describe("error-recorder", () => {
});
it("non-HttpError → unexpected; HTTP source converges to 500, non-HTTP status is NULL", () => {
- const rec = new ErrorRecorder(repo, now);
+ const rec = wire(ErrorRecorder, { errors: repo, now: now });
rec.record({ source: "http", err: new Error("boom") });
rec.record({
source: "session",
@@ -296,7 +297,7 @@ describe("error-recorder", () => {
});
it("non-Error throwables and overlong messages: stringified and truncated to the cap", () => {
- const rec = new ErrorRecorder(repo, now);
+ const rec = wire(ErrorRecorder, { errors: repo, now: now });
rec.record({ source: "process", err: "a string error", code: "unhandled_rejection" });
rec.record({ source: "usage", err: new Error("x".repeat(MESSAGE_MAX + 100)) });
const rows = db.prepare("SELECT message FROM error_records ORDER BY id").all();
@@ -311,12 +312,12 @@ describe("error-recorder", () => {
},
} as unknown as ErrorsRepo;
expect(() =>
- new ErrorRecorder(broken).record({ source: "http", err: new Error("x") }),
+ wire(ErrorRecorder, { errors: broken }).record({ source: "http", err: new Error("x") }),
).not.toThrow();
});
it("explicit kind wins over HttpError inference (sources self-report human need)", () => {
- const rec = new ErrorRecorder(repo, now);
+ const rec = wire(ErrorRecorder, { errors: repo, now: now });
rec.record({ source: "llm", err: "timed out", code: "llm_timeout", kind: "expected" });
rec.record({ source: "llm", err: "auth failed", code: "llm_failed", kind: "unexpected" });
const rows = db.prepare("SELECT kind, source, status FROM error_records ORDER BY id").all();
@@ -329,7 +330,7 @@ describe("error-recorder", () => {
// close, classified by messagingErrorKind, persisted under `messaging_connect_failed`.
// Both rows land — the log keeps everything — but only the one a person has to act on
// reaches the unexpected count the cost center highlights.
- const rec = new ErrorRecorder(repo, now);
+ const rec = wire(ErrorRecorder, { errors: repo, now: now });
const closed = (message: string, code: number, recovers: boolean) =>
new MessagingConnectionClosedError(message, code, recovers);
for (const err of [
@@ -362,7 +363,7 @@ describe("error-recorder", () => {
it("short-window dedup: same-kind errors persist once per window, then resume", () => {
let t = Date.parse("2026-07-06T10:00:00Z");
- const rec = new ErrorRecorder(repo, () => new Date(t));
+ const rec = wire(ErrorRecorder, { errors: repo, now: () => new Date(t) });
const boom = () =>
rec.record({
source: "http",
@@ -384,7 +385,7 @@ describe("error-recorder", () => {
});
it("dedup never crosses source / code / Project (kinds don't suppress each other)", () => {
- const rec = new ErrorRecorder(repo, now); // time frozen: everything lands in the same window
+ const rec = wire(ErrorRecorder, { errors: repo, now: now }); // time frozen: everything lands in the same window
const err = new Error("boom");
rec.record({ source: "http", err, ctx: { projectId: "p1" }, code: "c1" });
rec.record({ source: "http", err, ctx: { projectId: "p1" }, code: "c1" }); // same kind: discarded
@@ -397,7 +398,7 @@ describe("error-recorder", () => {
it("bounded dedup table: expired entries cleaned first, else wiped; works afterward", () => {
let t = Date.parse("2026-07-06T10:00:00Z");
- const rec = new ErrorRecorder(repo, () => new Date(t));
+ const rec = wire(ErrorRecorder, { errors: repo, now: () => new Date(t) });
const boom = (code: string) =>
rec.record({ source: "http", err: "boom", ctx: { projectId: "p1" }, code });
@@ -427,11 +428,12 @@ describe("stream-error-watcher (LLM / Environment errors)", () => {
beforeEach(() => {
db = openDatabase(":memory:");
- repo = new ErrorsRepo(db);
+ repo = wire(ErrorsRepo, { db: db });
});
afterEach(() => db.close());
- const watcher = () => new StreamErrorWatcher(new ErrorRecorder(repo, now), CTX);
+ const watcher = () =>
+ new StreamErrorWatcher(wire(ErrorRecorder, { errors: repo, now: now }), CTX);
const rows = () =>
db.prepare("SELECT * FROM error_records ORDER BY id").all() as Array<Record<string, unknown>>;
@@ -1167,7 +1169,7 @@ describe("HTTP onError persistence (integration)", () => {
// the rows a member can reach at offset N are the same set the summary counted, never
// another tenant's and never the unattributed ones. Seeded directly so the interleaving is
// exact — going through HTTP would collapse repeats into the recorder's dedup window.
- const repo = new ErrorsRepo(t.deps.db);
+ const repo = wire(ErrorsRepo, { db: t.deps.db });
const seed = (owner: string | null, code: string) =>
repo.insert({
ts: "2026-07-27T00:00:00.000Z",
@@ -1229,7 +1231,7 @@ describe("HTTP onError persistence (integration)", () => {
it("the paged error route narrows to one category on request, counting only that one", async () => {
// What the cost-center badge asks: one row of `unexpected`, for the count and the newest
// timestamp its dismissal is stamped against. Seeded directly, so the interleaving is exact.
- const repo = new ErrorsRepo(t.deps.db);
+ const repo = wire(ErrorsRepo, { db: t.deps.db });
const seed = (kind: string, code: string, ts: string) =>
repo.insert({
ts,
@@ -1268,7 +1270,7 @@ describe("HTTP onError persistence (integration)", () => {
/** Seeds one row straight into the table, so a batch's dates and Agents are exact. */
const seedRow = (o: Partial<ErrorRecordInsert> & { date: string; code: string }) =>
- new ErrorsRepo(t.deps.db).insert({
+ wire(ErrorsRepo, { db: t.deps.db }).insert({
ts: `${o.date}T00:00:00.000Z`,
projectId,
agentId: null,
@@ -1384,7 +1386,7 @@ describe("HTTP onError persistence (integration)", () => {
// read: the one person who can see them anywhere empties them from the panel that showed
// them, while a member's clear (whose read never lists them) never reaches them.
const adminApi = apiClient(t.app, (await loginAdmin(t.app)).cookie);
- new ErrorsRepo(t.deps.db).insert({
+ wire(ErrorsRepo, { db: t.deps.db }).insert({
ts: "2026-07-06T00:00:00.000Z",
date: "2026-07-06",
projectId: null,
@@ -1531,7 +1533,7 @@ describe("HTTP error attribution (only when the requester actually has Project a
});
it("the attribution check throws: onError survives, error lands unattributed", async () => {
- t.deps.projectService.canAccess = () => {
+ t.deps.access.canAccess = () => {
throw new Error("access check blew up");
};
const res = await ownerApi.get(`/api/projects/${projectId}/usage?groupBy=bogus`);
diff --git a/packages/server/test/goals.test.ts b/packages/server/test/goals.test.ts
index cc87a0db..be7d36a3 100644
--- a/packages/server/test/goals.test.ts
+++ b/packages/server/test/goals.test.ts
@@ -5,6 +5,7 @@
* goal hook events.
*/
import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { wire } from "@prismshadow/penguin-core/kernel";
import type { DatabaseSync } from "node:sqlite";
import {
assistantText,
@@ -71,7 +72,7 @@ describe("SessionManager.startGoal", () => {
beforeEach(() => {
db = openDatabase(":memory:");
- sessions = new SessionsRepo(db);
+ sessions = wire(SessionsRepo, { db: db });
sessions.insert(ROW);
channels = new ChannelHub();
});
diff --git a/packages/server/test/helpers.ts b/packages/server/test/helpers.ts
index 8acb4f83..9a39fcba 100644
--- a/packages/server/test/helpers.ts
+++ b/packages/server/test/helpers.ts
@@ -9,18 +9,51 @@ import path from "node:path";
import type { Hono } from "hono";
import type { OmniMessage } from "@prismshadow/penguin-core";
import { bootAppDeps, createRuntimeApp } from "../src/app.js";
-import type { AppDeps, BuildDepsOverrides } from "../src/app.js";
+import type { BuildDepsOverrides, ServerBoot } from "../src/app.js";
+import type { ModuleTree } from "@prismshadow/penguin-core/kernel";
+import type { DatabaseSync } from "node:sqlite";
+import type { HmrHost } from "../src/hmr/host.js";
+import type { ChannelHub } from "../src/runtime/channel.js";
+import type { DesktopService } from "../src/services/desktop-service.js";
+import type { AuthService } from "../src/auth/service.js";
+import type { AdminService } from "../src/services/admin-service.js";
+import type { ProjectService } from "../src/services/project-service.js";
+import type { ProjectAccess } from "../src/services/project-access.js";
+import type { ProjectConfigService } from "../src/services/project-config-service.js";
+import type { ModelOAuthService } from "../src/services/model-oauth-service.js";
+import type { AgentService } from "../src/services/agent-service.js";
+import type { AgentConfigService } from "../src/services/agent-config-service.js";
+import type { MemoryService } from "../src/services/memory-service.js";
+import type { SessionService } from "../src/services/session-service.js";
+import type { PricingLookup, UsageService } from "../src/services/usage-service.js";
+import type { UpdateCheckService } from "../src/services/update-check-service.js";
+import type { WorkspaceFilesService } from "../src/services/workspace-files-service.js";
+import type { PreviewTokenSigner } from "../src/services/preview-token.js";
+import type { BenchmarkService } from "../src/services/benchmark-service.js";
+import type { SnapshotService } from "../src/services/snapshot-service.js";
+import type { SessionsRepo } from "../src/db/repos/sessions.js";
+import type { UiPrefsRepo } from "../src/db/repos/ui-prefs.js";
+import type { ServerSettingsRepo } from "../src/db/repos/server-settings.js";
+import type { SchedulesRepo } from "../src/db/repos/schedules.js";
+import type { ErrorsRepo } from "../src/db/repos/errors.js";
+import type { MessagingBindingsRepo } from "../src/db/repos/messaging-bindings.js";
+import type { MessagingBridge } from "../src/runtime/messaging/bridge.js";
+import type { QQScanService } from "../src/runtime/messaging/qq-scan.js";
+import type { Scheduler } from "../src/runtime/scheduler.js";
+import type { SessionManager } from "../src/runtime/session-manager.js";
+import type { ErrorRecorder } from "../src/runtime/error-recorder.js";
+import type { MachinesService } from "../src/machines/service.js";
import { openDatabase } from "../src/db/database.js";
import { TraceIndexRepo } from "../src/db/repos/trace-index.js";
import { SessionSources } from "../src/runtime/session-sources.js";
import { TraceIndexService } from "../src/services/trace-index.js";
import { TraceService } from "../src/services/trace-service.js";
import type { TraceSessionIndex } from "../src/services/trace-service.js";
-import type { PricingLookup } from "../src/services/usage-service.js";
import type { AppEnv } from "../src/auth/middleware.js";
import { ADMIN_USER_ID } from "../src/auth/service.js";
import type { ServerConfig } from "../src/config.js";
import type { UserInfo } from "../src/api/types.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
export async function makeTempRoot(): Promise<string> {
return fs.mkdtemp(path.join(os.tmpdir(), "penguin-server-test-"));
@@ -65,9 +98,98 @@ export function testConfig(root: string): ServerConfig {
};
}
+/**
+ * The module tree, flattened under the names tests have always used. Production has no
+ * such object — a module names what it needs in its manifest — but a test reaches into
+ * any service directly, and this view is the one place that maps the old names.
+ */
+export interface TestDeps {
+ config: ServerConfig;
+ db: DatabaseSync;
+ hmr: HmrHost;
+ channels: ChannelHub;
+ desktop: DesktopService | null;
+ tree: ModuleTree;
+ sessionsRepo: SessionsRepo;
+ prefsRepo: UiPrefsRepo;
+ serverSettingsRepo: ServerSettingsRepo;
+ authService: AuthService;
+ adminService: AdminService;
+ projectService: ProjectService;
+ access: ProjectAccess;
+ projectConfigService: ProjectConfigService;
+ modelOAuth: ModelOAuthService;
+ agentService: AgentService;
+ agentConfigService: AgentConfigService;
+ memoryService: MemoryService;
+ sessionService: SessionService;
+ traceService: TraceService;
+ traceIndex: TraceIndexService;
+ usageService: UsageService;
+ updateCheck: UpdateCheckService;
+ workspaceFiles: WorkspaceFilesService;
+ previewTokens: PreviewTokenSigner;
+ benchmarks: BenchmarkService;
+ snapshots: SnapshotService;
+ schedulesRepo: SchedulesRepo;
+ errorsRepo: ErrorsRepo;
+ messagingRepo: MessagingBindingsRepo;
+ messaging: MessagingBridge;
+ qqScan: QQScanService;
+ scheduler: Scheduler;
+ manager: SessionManager;
+ sessionSources: SessionSources;
+ errors: ErrorRecorder;
+ machines: MachinesService;
+}
+
+export function flattenForTests(boot: ServerBoot): TestDeps {
+ const { tree } = boot;
+ const api = <T>(module: string, alias: string): T => tree.api<T>(module, alias);
+ return {
+ config: boot.config,
+ db: boot.db,
+ hmr: boot.hmr,
+ channels: boot.channels,
+ desktop: boot.desktop,
+ tree,
+ sessionsRepo: api("SessionsRepo", "SessionsRepo"),
+ prefsRepo: api("UiPrefsRepo", "UiPrefsRepo"),
+ serverSettingsRepo: api("ServerSettingsRepo", "ServerSettingsRepo"),
+ authService: api("AuthService", "AuthService"),
+ adminService: api("AdminService", "AdminService"),
+ projectService: api("ProjectService", "ProjectService"),
+ access: api("ProjectAccess", "ProjectAccess"),
+ projectConfigService: api("ProjectConfigService", "ProjectConfigService"),
+ modelOAuth: api("ModelOAuthService", "ModelOAuthService"),
+ agentService: api("AgentService", "AgentService"),
+ agentConfigService: api("AgentConfigService", "AgentConfigService"),
+ memoryService: api("MemoryService", "MemoryService"),
+ sessionService: api("SessionsModule", "sessionService"),
+ traceService: api("TraceService", "TraceService"),
+ traceIndex: api("TraceIndexService", "TraceIndexService"),
+ usageService: api("UsageService", "UsageService"),
+ updateCheck: api("VersionModule", "updateCheck"),
+ workspaceFiles: api("WorkspaceFilesService", "WorkspaceFilesService"),
+ previewTokens: api("WorkspaceModule", "previewTokens"),
+ benchmarks: api("BenchmarkService", "BenchmarkService"),
+ snapshots: api("SnapshotService", "SnapshotService"),
+ schedulesRepo: api("SchedulesRepo", "SchedulesRepo"),
+ errorsRepo: api("ErrorsRepo", "ErrorsRepo"),
+ messagingRepo: api("MessagingBindingsRepo", "MessagingBindingsRepo"),
+ messaging: api("MessagingModule", "messaging"),
+ qqScan: api("MessagingModule", "qqScan"),
+ scheduler: api("Scheduler", "Scheduler"),
+ manager: api("SessionsModule", "manager"),
+ sessionSources: api("SessionSources", "SessionSources"),
+ errors: api("ErrorRecorder", "ErrorRecorder"),
+ machines: api("MachinesModule", "machines"),
+ };
+}
+
export interface TestApp {
app: Hono<AppEnv>;
- deps: AppDeps;
+ deps: TestDeps;
root: string;
/** Initial password of the seeded admin (TEST_ADMIN_PASSWORD unless overridden via `config.seedAdminPassword`). */
adminPassword: string;
@@ -86,7 +208,7 @@ export async function createTestApp(options: TestAppOptions = {}): Promise<TestA
const root = await makeTempRoot();
if (beforeSeed) await beforeSeed(root);
const finalConfig = { ...testConfig(root), ...config };
- const deps = await bootAppDeps(finalConfig, {
+ const boot = await bootAppDeps(finalConfig, {
log: () => {},
passwordHashCost: TEST_PASSWORD_HASH_COST,
// The bridge's per-line pace is a real wait in production; every test but the one
@@ -95,11 +217,12 @@ export async function createTestApp(options: TestAppOptions = {}): Promise<TestA
...overrides,
});
// Consistent with the startup entrypoint: seed the built-in admin (owning default_project).
+ const deps = flattenForTests(boot);
await deps.authService.seedAdmin();
// The seed hashes and discards; tests know the password only because the config injects it.
// With a null override there is nothing to know, and such tests never password-login.
const adminPassword = finalConfig.seedAdminPassword ?? TEST_ADMIN_PASSWORD;
- const app = createRuntimeApp(deps);
+ const app = createRuntimeApp(boot);
return {
app,
deps,
@@ -226,14 +349,19 @@ export function makeTraceHarness(
} {
const db = openDatabase(":memory:");
const sources = opts.sources ?? new SessionSources();
- const traceIndex = new TraceIndexService(root, new TraceIndexRepo(db), sources);
+ const traceIndex = wire(TraceIndexService, {
+ config: { root },
+ repo: wire(TraceIndexRepo, { db }),
+ sources,
+ });
const shardReads: string[] = [];
- const service = new TraceService(root, {
+ const service = wire(TraceService, {
+ config: { root },
index: traceIndex,
...(opts.sessions !== undefined ? { sessions: opts.sessions } : {}),
...(opts.lookupPricing !== undefined ? { lookupPricing: opts.lookupPricing } : {}),
sources,
- observeShardRead: (p) => shardReads.push(p),
+ observeShardRead: (p: string) => shardReads.push(p),
});
return { traceIndex, service, sources, shardReads, close: () => db.close() };
}
diff --git a/packages/server/test/install-id.test.ts b/packages/server/test/install-id.test.ts
index fe157a6a..35d1fe5e 100644
--- a/packages/server/test/install-id.test.ts
+++ b/packages/server/test/install-id.test.ts
@@ -13,11 +13,7 @@ import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { InstallResponse } from "../src/api/types.js";
-import { createApp } from "../src/app.js";
-import { HotResources } from "../src/hmr/resources.js";
import { ensureInstallId, installIdPath, readInstallId } from "../src/install-id.js";
-import { TerminalManager } from "../src/terminal/manager.js";
-import { identityFrom } from "../src/terminal/identity.js";
import { createTestApp, loginAdmin, makeTempRoot } from "./helpers.js";
import type { TestApp } from "./helpers.js";
@@ -141,13 +137,12 @@ describe("GET /api/install", () => {
// (hmr/host.ts), so the route the pushed bundle asks for has to travel with the platform.
// Mounted in the runtime it would be missing from exactly the installations that received
// the new web dist by push, and the platform's own auth gate would 401 a public route.
- const platform = createApp(
- t.deps,
- new TerminalManager(new HotResources()),
- identityFrom(t.deps.authService),
+ const platform = t.deps.tree.api<{ fetch(request: Request): Promise<Response> }>(
+ "HttpModule",
+ "http",
);
- const res = await platform.request("/api/install");
+ const res = await platform.fetch(new Request("http://localhost/api/install"));
expect(res.status).toBe(200);
expect(((await res.json()) as InstallResponse).installId).toBe(readInstallId(t.root));
});
diff --git a/packages/server/test/model-oauth.test.ts b/packages/server/test/model-oauth.test.ts
index 619c941d..2d942be4 100644
--- a/packages/server/test/model-oauth.test.ts
+++ b/packages/server/test/model-oauth.test.ts
@@ -34,6 +34,7 @@ import {
import { requestOrigin } from "../src/http/routes/model-oauth.js";
import { apiClient, createTestApp, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
/** The catalog group under test; the flow exists only because this entry declares it. */
const TOKENDANCE = providerInfo("tokendance")!;
@@ -192,8 +193,8 @@ describe("flow store", () => {
clock = 1_700_000_000_000;
applied = [];
exchanged = [];
- service = new ModelOAuthService({
- applyGroupKey: async (projectId, provider, apiKey) => {
+ service = wire(ModelOAuthService, {
+ applyGroupKey: async (projectId: string, provider: string, apiKey: string) => {
applied.push({ projectId, provider, apiKey });
return 6;
},
@@ -270,7 +271,7 @@ describe("flow store", () => {
});
it("a failed exchange ends the flow and reports the mapped reason", async () => {
- service = new ModelOAuthService({
+ service = wire(ModelOAuthService, {
applyGroupKey: async () => 6,
fetchImpl: (async () => jsonResponse(403, {})) as unknown as typeof fetch,
now: () => clock,
@@ -285,7 +286,7 @@ describe("flow store", () => {
});
it("a key that cannot be stored is reported as such, not as a success", async () => {
- service = new ModelOAuthService({
+ service = wire(ModelOAuthService, {
applyGroupKey: async () => {
throw new Error("disk full");
},
diff --git a/packages/server/test/models-list.test.ts b/packages/server/test/models-list.test.ts
index d07246ff..2799e4b8 100644
--- a/packages/server/test/models-list.test.ts
+++ b/packages/server/test/models-list.test.ts
@@ -11,6 +11,7 @@ import type { EndpointModelListResponse, ProjectCreateResponse } from "../src/ap
import { ProjectConfigService } from "../src/services/project-config-service.js";
import { apiClient, createTestApp, provisionUser } from "./helpers.js";
import type { TestApp } from "./helpers.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
describe("ProjectConfigService.listEndpointModels", () => {
let root: string;
@@ -18,7 +19,7 @@ describe("ProjectConfigService.listEndpointModels", () => {
beforeEach(async () => {
root = await mkdtemp(path.join(tmpdir(), "penguin-models-list-"));
- service = new ProjectConfigService(root);
+ service = wire(ProjectConfigService, { config: { root } });
});
afterEach(async () => {
await rm(root, { recursive: true, force: true });
diff --git a/packages/server/test/models.test.ts b/packages/server/test/models.test.ts
index 51073ef2..03c89286 100644
--- a/packages/server/test/models.test.ts
+++ b/packages/server/test/models.test.ts
@@ -30,6 +30,7 @@ import type { RuntimeSession } from "../src/runtime/session-manager.js";
import type { ChannelEvent } from "../src/runtime/channel.js";
import { apiClient, createTestApp, loginAdmin, provisionUser, waitFor } from "./helpers.js";
import type { TestApp } from "./helpers.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
/** Catalog paired refs (config primary key = (provider, model_id)). */
const catalogPairs = MODEL_CATALOG.map((m) => `${m.provider}\0${m.modelId}`);
@@ -465,7 +466,7 @@ describe("default_project presets", () => {
// First have the "CLI" write a config with a single custom model, then admin seeding adopts it.
t = await createTestApp({
beforeSeed: async (root) => {
- await new ProjectConfigService(root).writeRaw("default_project", {
+ await wire(ProjectConfigService, { config: { root } }).writeRaw("default_project", {
default_model: { provider: "custom", model_id: "cli-model" },
models: [{ provider: "custom", model_id: "cli-model", context_window: 1234 }],
});
@@ -601,7 +602,7 @@ describe("model-reference rekeying and the connectivity test", () => {
// No clock is passed and none is wanted: which tier a given request ran in is decided from
// that record's own timestamp when the usage is aggregated, so the price lookup's whole job
// is to say what the two tiers are. The number on disk is the peak one either way.
- const svc = new ProjectConfigService(t.root);
+ const svc = wire(ProjectConfigService, { config: { root: t.root } });
const rates = await svc.getPricing(projectId, "deepseek", "deepseek-v4-flash");
const catalogPeak = catalogEntryFor("deepseek", "deepseek-v4-flash")!.pricing!;
expect(rates!.peak.output).toBe(catalogPeak.output);
@@ -629,7 +630,7 @@ describe("model-reference rekeying and the connectivity test", () => {
: {}),
}));
await api.put(url(), { models: entries });
- const svc = new ProjectConfigService(t.root);
+ const svc = wire(ProjectConfigService, { config: { root: t.root } });
// Nothing here knows whether 3 is a peak rate, so halving it would invent a discount: the
// two tiers collapse to the typed number and the split costs a row and changes nothing.
const typed = { cacheRead: 1, cacheWrite: 2, output: 3 };
diff --git a/packages/server/test/plugin-loader.test.ts b/packages/server/test/plugin-loader.test.ts
index 5f8db562..4b5f6eac 100644
--- a/packages/server/test/plugin-loader.test.ts
+++ b/packages/server/test/plugin-loader.test.ts
@@ -8,7 +8,8 @@ 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 { PLUGINS_FILE, loadPlugins, readPluginList } from "../src/plugin/loader.js";
+import ts from "typescript";
+import { IFACES_FILE, PLUGINS_FILE, loadPlugins, readPluginList } from "../src/plugin/loader.js";
let root: string;
@@ -66,18 +67,99 @@ describe("plugin list", () => {
});
describe("plugin loading", () => {
- it("loads a plugin module's exported activate", async () => {
- const file = await writePluginModule("ok", "export function activate() {}");
+ /**
+ * The decorators, as a plugin's bundle would carry them — here imported from this
+ * checkout's built SDK by file URL, since a package under a temp dir resolves nothing.
+ */
+ const decorators = new URL("../../core/dist/plugin/index.js", import.meta.url).href;
+
+ /** Plugin source as a plugin author writes it, lowered the way its build would lower it. */
+ function lower(source: string): string {
+ return ts.transpileModule(source, {
+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },
+ }).outputText;
+ }
+
+ /** The table the plugin's build would generate: one component, contributing one provider. */
+ const oneModule = {
+ ifaces: {
+ "@acme/penguin-plugin-thing#Thing": { name: "Thing", methods: {}, slots: {} },
+ },
+ types: {},
+ modules: {
+ Thing: {
+ name: "Thing",
+ requires: {},
+ provides: { Thing: "@acme/penguin-plugin-thing#Thing" },
+ contributes: {
+ "SandboxModule.providers": [
+ { id: "thing.provider", name: "thing", dimensions: ["fs-write"] },
+ ],
+ },
+ children: [],
+ },
+ },
+ };
+ const thingClass = `
+ import { Bind, Component } from ${JSON.stringify(decorators)};
+ @Component({ contributes: { "SandboxModule.providers": [{ id: "thing.provider", name: "thing", dimensions: ["fs-write"] }] } })
+ export class Thing {
+ @Bind("thing.provider") provider!: unknown;
+ setup() { this.provider = { confine() { throw new Error("no"); } }; }
+ }`;
+
+ /**
+ * A package on disk: its package.json, the generated table beside it, and an index.mjs
+ * default export (`null` table = a package that ships no modules, or was never built).
+ */
+ async function writePackage(name: string, table: unknown | null, index: string): Promise<string> {
+ const dir = path.join(root, "node_modules", ...name.split("/"));
+ await mkdir(dir, { recursive: true });
+ await writeFile(
+ path.join(dir, "package.json"),
+ JSON.stringify({ name, main: "./index.mjs" }),
+ "utf8",
+ );
+ if (table !== null) await writeFile(path.join(dir, IFACES_FILE), JSON.stringify(table), "utf8");
+ await writeFile(path.join(dir, "index.mjs"), lower(index), "utf8");
+ return path.join(dir, "index.mjs");
+ }
+
+ it("boots the classes the default export names, each against its manifest in the package's table", async () => {
+ const file = await writePackage(
+ "@acme/penguin-plugin-thing",
+ oneModule,
+ `${thingClass}
+ export default { modules: [Thing] };`,
+ );
await writeConfig({ plugins: [file] });
const result = await loadPlugins(root);
expect(result.failed.size).toBe(0);
expect(result.loaded).toHaveLength(1);
- expect(result.loaded[0]!.specifier).toBe(file);
- expect(typeof result.loaded[0]!.plugin.activate).toBe("function");
+ const entry = result.loaded[0]!;
+ expect(entry.specifier).toBe(file);
+ expect(entry.modules.map((m) => m.manifest.name)).toEqual(["Thing"]);
+ expect(entry.modules[0]!.manifest.contributes["SandboxModule.providers"]?.[0]?.id).toBe(
+ "thing.provider",
+ );
+ expect(entry.ifaces?.ifaces["@acme/penguin-plugin-thing#Thing"]).toBeDefined();
+ // The class is the code half: its @Bind field is the contribution's implementation.
+ const instance = await entry.modules[0]!.create(
+ { use: {}, contributions: {}, resources: {} as never, effect: () => {} },
+ {},
+ );
+ expect(typeof (instance.bind?.["thing.provider"] as { confine: unknown }).confine).toBe(
+ "function",
+ );
});
it("an unresolvable specifier is skipped with its reason, not fatal", async () => {
- const good = await writePluginModule("good", "export function activate() {}");
+ const good = await writePackage(
+ "@acme/good",
+ oneModule,
+ `${thingClass}
+ export default { modules: [Thing] };`,
+ );
await writeConfig({ plugins: ["@nope/definitely-not-installed", good] });
const result = await loadPlugins(root);
// The good one still loads: failure is per entry.
@@ -85,21 +167,60 @@ describe("plugin loading", () => {
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 writePluginModule("bad", "export default { activate() {} };");
+ it("a default export that is not a list of classes is a load failure that says so", async () => {
+ const file = await writePackage(
+ "@acme/half",
+ oneModule,
+ "export default { modules: { Thing: { create() {} } } };",
+ );
await writeConfig({ plugins: [file] });
const result = await loadPlugins(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/);
+ expect(result.failed.get(file)).toMatch(/not a Plugin/);
});
- it("a plugin that throws while loading is skipped with its error", async () => {
- const file = await writePluginModule("throws", "throw new Error('boom at import');");
+ it("a class the table does not carry is a stale build, named as such", async () => {
+ const file = await writePackage(
+ "@acme/extra",
+ oneModule,
+ `${thingClass}
+ import { Component } from ${JSON.stringify(decorators)};
+ @Component() export class Ghost {}
+ export default { modules: [Thing, Ghost] };`,
+ );
await writeConfig({ plugins: [file] });
const result = await loadPlugins(root);
- expect(result.loaded).toEqual([]);
- expect(result.failed.get(file)).toMatch(/boom at import/);
+ expect(result.failed.get(file)).toMatch(/Ghost: not in the generated manifest table/);
+ });
+
+ it("a package without a table ships no modules — a plugin is a plugin by being listed", async () => {
+ const file = await writePackage("@acme/skills-only", null, "export default { modules: [] };");
+ await writeConfig({ plugins: [file] });
+ const result = await loadPlugins(root);
+ expect(result.failed.size).toBe(0);
+ expect(result.loaded[0]!.modules).toEqual([]);
+ });
+
+ it("a package that names module classes but ships no table was never built, and says so", async () => {
+ const file = await writePackage(
+ "@acme/unbuilt",
+ null,
+ `${thingClass}
+ export default { modules: [Thing] };`,
+ );
+ await writeConfig({ plugins: [file] });
+ const result = await loadPlugins(root);
+ expect(result.failed.get(file)).toMatch(/ifaces\.json is missing — build the package/);
+ });
+
+ it("a malformed manifest in the table is a load failure naming the module", async () => {
+ const file = await writePackage(
+ "@acme/bad-table",
+ { ifaces: {}, types: {}, modules: { Thing: { contributes: {} } } },
+ "export default { modules: [] };",
+ );
+ await writeConfig({ plugins: [file] });
+ const result = await loadPlugins(root);
+ expect(result.failed.get(file)).toMatch(/ifaces\.json#modules\.Thing/);
});
});
diff --git a/packages/server/test/plugin.test.ts b/packages/server/test/plugin.test.ts
index 6ceb1488..9a876bef 100644
--- a/packages/server/test/plugin.test.ts
+++ b/packages/server/test/plugin.test.ts
@@ -1,347 +1,126 @@
/**
- * Behavior tests for the plugin 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.
+ * Plugins are modules: the host holds what the loader paired (manifest ↔ code), the
+ * platform boots them as children of its tree at EVERY App creation, and what a module
+ * contributes lands on the same slots the built-in modules use.
*/
-import { describe, expect, it, vi } from "vitest";
-import { boot, initialDoc } from "@prismshadow/penguin-core/kernel";
+import { describe, expect, it } from "vitest";
+import type { ModuleDef } from "@prismshadow/penguin-core/kernel";
+import { parseManifest, boot, initialDoc } from "@prismshadow/penguin-core/kernel";
import { HotResources } from "../src/hmr/resources.js";
-import { packagedPlatform } from "../src/hmr/platform.js";
+import { PluginHost, PLUGINS_RESOURCE_ID, pluginHostFrom } from "../src/plugin/host.js";
import { PENGUIN_FAMILY, RUNTIME_INTERFACES_RESOURCE_ID } from "../src/hmr/capabilities.js";
-import { PLUGINS_RESOURCE_ID, PluginHost, pluginHostFrom } from "../src/plugin/host.js";
-import type {
- PenguinContext,
- PenguinInterface,
- WorkflowFactory,
-} from "@prismshadow/penguin-core/plugin";
-import type { HarnessContext } from "../src/plugin/index.js";
-import { instantiateWorkflows, WorkflowFactories } from "../src/plugin/workflow.js";
+import { packagedPlatform } from "../src/hmr/platform.js";
+import type { SandboxProvider } from "@prismshadow/penguin-core/plugin";
+
+const provider = (name: string): SandboxProvider => ({
+ dimensions: ["fs-write"],
+ confine: (argv) => ({
+ argv: [name, ...argv],
+ enforcement: "full",
+ denialSignatures: [],
+ runnerFailureRules: [],
+ }),
+});
-function emptyIface(): PenguinInterface {
- // The registry, not a bare Map: that IS the surface a plugin gets (see platform.ts).
+/** A backend as a plugin module: one provider contributed to sandbox.providers. */
+function backend(name: string, onCreate?: () => void): ModuleDef {
return {
- workflow: new WorkflowFactories(),
- tool: new Map(),
- sandbox: { registerProvider: () => {} },
+ manifest: parseManifest({
+ name: `ext-${name}`,
+ requires: {},
+ provides: {},
+ contributes: {
+ "SandboxModule.providers": [{ id: `ext-${name}.provider`, name, dimensions: ["fs-write"] }],
+ },
+ children: [],
+ }),
+ create() {
+ onCreate?.();
+ return { api: {}, bind: { [`ext-${name}.provider`]: provider(name) } };
+ },
};
}
-/**
- * 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); plugin 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("plugin host", () => {
- it("activate runs once; typed events deliver both views in activation order", async () => {
- const host = new PluginHost();
- 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 plugin, 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 plugin is fine, and events with no handlers deliver to no one", async () => {
+ it("holds every plugin's modules in load order", () => {
const host = new PluginHost();
- 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 PluginHost();
- 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 PluginHost();
- 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 plugins and re-runs nothing.
- await host.dispose();
- expect(done).toEqual(["fast", "slow"]);
- expect(warn).toHaveBeenCalledTimes(2);
- } finally {
- warn.mockRestore();
- }
- });
-});
-
-describe("plugin host — activation is transactional", () => {
- it("an async activate is awaited, so its rejection is an ordinary load failure", async () => {
- const host = new PluginHost();
- 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 plugin is not published, so nothing it registered is ever delivered.
- host.emit("create", {} as PenguinContext);
- expect(order).toEqual([]);
+ host.use({ specifier: "a", modules: [backend("a1"), backend("a2")] });
+ host.use({ specifier: "b", modules: [backend("b1")] });
+ expect(host.modules().map((m) => m.manifest.name)).toEqual(["ext-a1", "ext-a2", "ext-b1"]);
});
- it("a failed activate still runs whatever it had already registered for cleanup", async () => {
+ it("refuses a module name another plugin already loaded, naming both", () => {
const host = new PluginHost();
- 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 PluginHost();
- 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 plugins.json ordering, and a plugin
- // could take over a name another one owns without either noticing.
- expect(() => iface.workflow.set("same", () => ({ run: () => "B" }))).toThrow(
- /workflow 'same' is already registered/,
+ host.use({ specifier: "a", modules: [backend("x")] });
+ expect(() => host.use({ specifier: "b", modules: [backend("x")] })).toThrow(
+ /plugin 'b': module 'ext-x' is already loaded/,
);
- 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("pluginHostFrom", () => {
it("claims the host the runtime published", () => {
- const host = new PluginHost();
const resources = new HotResources();
+ const host = new PluginHost();
resources.register(PLUGINS_RESOURCE_ID, host);
expect(pluginHostFrom(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 plugins.
- pluginHostFrom(new HotResources()).emit("initialize", iface);
- expect(iface.workflow.size).toBe(0);
+ expect(pluginHostFrom(new HotResources()).modules()).toEqual([]);
});
});
-describe("plugin 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;
+describe("plugin modules on the real platform", () => {
+ /** A bare-kernel boot (no capabilities): the sandbox floor plus whatever plugins contribute. */
+ async function bootWith(modules: ModuleDef[]) {
+ const resources = new HotResources();
+ resources.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });
const host = new PluginHost();
- 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 plugins.
- const resources = bareKernel();
+ host.use({ specifier: "test", modules });
resources.register(PLUGINS_RESOURCE_ID, host);
+ return boot(
+ packagedPlatform.impl,
+ packagedPlatform.iface,
+ initialDoc(packagedPlatform.iface, { motd: "m" }),
+ resources,
+ );
+ }
- const instA = await quietBoot(resources);
- try {
- expect(initializes).toBe(1);
- expect(contexts).toHaveLength(1);
- const ctx = contexts[0]!;
- // The sandbox config surface rides the same context (see ../src/sandbox/).
- expect(ctx.sandbox.settings()).toEqual({ mode: "danger-full-access" });
- // `terminals` is NOT on the closed contract: it is this harness's own, so reaching it
- // is an explicit cast — the same one a plugin depending on this embedder writes.
- expect(typeof (ctx as HarnessContext).terminals.handleIds).toBe("function");
- // …and the workflow this plugin 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();
- }
+ it("boots an App when the runtime published no host at all", async () => {
+ const resources = new HotResources();
+ resources.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });
+ const inst = await boot(
+ packagedPlatform.impl,
+ packagedPlatform.iface,
+ initialDoc(packagedPlatform.iface, { motd: "m" }),
+ resources,
+ );
+ expect(inst.api.info()).toMatchObject({ impl: "packaged" });
+ inst.dispose();
+ });
+
+ it("creates every plugin module per App, so a swap never carries an instance across", async () => {
+ let created = 0;
+ const a = await bootWith([backend("one", () => created++)]);
+ expect(created).toBe(1);
+ a.dispose();
+ const b = await bootWith([backend("one", () => created++)]);
+ expect(created).toBe(2);
+ b.dispose();
+ });
+
+ it("a contribution to a slot no module declares refuses the boot, naming it", async () => {
+ const stray: ModuleDef = {
+ manifest: parseManifest({
+ name: "ext-stray",
+ requires: {},
+ provides: {},
+ contributes: { "nowhere.slot": [{ id: "ext-stray.x" }] },
+ children: [],
+ }),
+ create: () => ({ api: {} }),
+ };
+ await expect(bootWith([stray])).rejects.toThrow(/contributes to 'nowhere.slot'/);
});
});
diff --git a/packages/server/test/project-config-cache.test.ts b/packages/server/test/project-config-cache.test.ts
index 512d0ad1..588ed9c0 100644
--- a/packages/server/test/project-config-cache.test.ts
+++ b/packages/server/test/project-config-cache.test.ts
@@ -14,6 +14,7 @@ import {
} from "@prismshadow/penguin-core";
import { ProjectConfigService } from "../src/services/project-config-service.js";
import { makeTempRoot } from "./helpers.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
const P = "project-cfg";
const PRICED = {
@@ -35,7 +36,7 @@ describe("project-config read cache", () => {
beforeEach(async () => {
root = await makeTempRoot();
- svc = new ProjectConfigService(root);
+ svc = wire(ProjectConfigService, { config: { root } });
file = projectConfigPath(root, P);
await svc.writeRaw(P, { name: "cached", models: [PRICED] });
await backdate(file, "2026-01-01T00:00:00Z");
diff --git a/packages/server/test/reset-admin-password.test.ts b/packages/server/test/reset-admin-password.test.ts
index 8f4fe7d4..030e9f0c 100644
--- a/packages/server/test/reset-admin-password.test.ts
+++ b/packages/server/test/reset-admin-password.test.ts
@@ -17,6 +17,7 @@ import { initialAdminPasswordPath } from "../src/initial-password.js";
import { acquireServerLock } from "../src/lock.js";
import { resetAdminPassword } from "../src/reset-admin-password.js";
import { makeTempRoot } from "./helpers.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
describe("resetAdminPassword", () => {
const roots: string[] = [];
@@ -36,7 +37,7 @@ describe("resetAdminPassword", () => {
async function seedDatabase(root: string): Promise<string> {
const dbPath = path.join(root, "web.db");
const db = openDatabase(dbPath);
- const users = new UsersRepo(db);
+ const users = wire(UsersRepo, { db: db });
const createdAt = "2026-01-01T00:00:00.000Z";
users.insert({
userId: ADMIN_USER_ID,
@@ -56,7 +57,7 @@ describe("resetAdminPassword", () => {
avatar: null,
createdAt,
});
- const sessions = new AuthSessionsRepo(db);
+ const sessions = wire(AuthSessionsRepo, { db: db });
const later = "2027-01-01T00:00:00.000Z";
sessions.insert({
tokenHash: "admin-session",
@@ -90,15 +91,15 @@ describe("resetAdminPassword", () => {
const db = openDatabase(dbPath);
try {
- const admin = new UsersRepo(db).findById(ADMIN_USER_ID);
+ const admin = wire(UsersRepo, { db: db }).findById(ADMIN_USER_ID);
expect(admin?.passwordIsInitial).toBe(true);
// The old password no longer works, and the new one is a value nobody holds.
expect(await verifyPassword("old-password-1", admin!.passwordHash)).toBe(false);
// The admin's session rows are deleted; a bystander's are untouched.
- const sessions = new AuthSessionsRepo(db);
+ const sessions = wire(AuthSessionsRepo, { db: db });
expect(sessions.findByTokenHash("admin-session")).toBeNull();
expect(sessions.findByTokenHash("alice-session")).not.toBeNull();
- const alice = new UsersRepo(db).findById("alice");
+ const alice = wire(UsersRepo, { db: db }).findById("alice");
expect(await verifyPassword("alice-password-1", alice!.passwordHash)).toBe(true);
} finally {
db.close();
@@ -118,7 +119,7 @@ describe("resetAdminPassword", () => {
expect(result).toMatchObject({ outcome: "server_running", lock: { port } });
const db = openDatabase(dbPath);
try {
- const admin = new UsersRepo(db).findById(ADMIN_USER_ID);
+ const admin = wire(UsersRepo, { db: db }).findById(ADMIN_USER_ID);
expect(await verifyPassword("old-password-1", admin!.passwordHash)).toBe(true);
} finally {
db.close();
diff --git a/packages/server/test/sandbox.test.ts b/packages/server/test/sandbox.test.ts
index 671e9076..80076a3c 100644
--- a/packages/server/test/sandbox.test.ts
+++ b/packages/server/test/sandbox.test.ts
@@ -4,7 +4,7 @@
* settings' ride on the parked platform context.
*/
import { describe, expect, it, vi } from "vitest";
-import { boot, initialDoc } from "@prismshadow/penguin-core/kernel";
+import { boot, initialDoc, parseManifest } from "@prismshadow/penguin-core/kernel";
import type { Json } from "@prismshadow/penguin-core/kernel";
import { HotResources } from "../src/hmr/resources.js";
import { PENGUIN_FAMILY, RUNTIME_INTERFACES_RESOURCE_ID } from "../src/hmr/capabilities.js";
@@ -12,7 +12,6 @@ import { packagedPlatform } from "../src/hmr/platform.js";
import { PluginHost, PLUGINS_RESOURCE_ID } from "../src/plugin/host.js";
import { SandboxService } from "../src/sandbox/index.js";
import type {
- PenguinContext,
SandboxDimension,
SandboxPolicy,
SandboxProvider,
@@ -171,9 +170,30 @@ describe("sandbox settings ride the parked context across a swap", () => {
// terminals-only boot legal (see capabilities.ts's RuntimeClaim). The sandbox floor is
// business-independent, so this is all these tests need behind the platform.
resources.register(RUNTIME_INTERFACES_RESOURCE_ID, { family: PENGUIN_FAMILY });
+ // The observer is itself a plugin module requiring the sandbox — the surface an
+ // actual consumer has.
+ let seen: SandboxService | null = null;
const host = new PluginHost();
- let seen: PenguinContext | null = null;
- await host.use({ activate: (extCtx) => extCtx.on("create", (ctx) => (seen = ctx)) });
+ host.use({
+ specifier: "observer",
+ modules: [
+ {
+ manifest: parseManifest({
+ name: "observer",
+ requires: {
+ sandbox: { iface: "@prismshadow/penguin-server#Sandbox", from: "SandboxModule" },
+ },
+ provides: {},
+ contributes: {},
+ children: [],
+ }),
+ create({ use }) {
+ seen = use.sandbox as SandboxService;
+ return { api: {} };
+ },
+ },
+ ],
+ });
resources.register(PLUGINS_RESOURCE_ID, host);
const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const inst = await boot(
@@ -182,16 +202,23 @@ describe("sandbox settings ride the parked context across a swap", () => {
initialDoc(packagedPlatform.iface, doc),
resources,
).finally(() => warn.mockRestore());
- return { inst, ctx: () => seen! };
+ return { inst, ctx: () => ({ sandbox: { settings: () => seen!.currentSettings() } }) };
}
it("a confining mode survives park -> fresh boot instead of resetting to unconfined", async () => {
- const a = await bootObserved({ motd: "m", sandbox: { mode: "read-only" } });
+ // The settings live in the sandbox module's own parked document (platform v2).
+ const a = await bootObserved({
+ motd: "m",
+ modules: { SandboxModule: { v: 1, self: { settings: { mode: "read-only" } } } },
+ });
try {
expect(a.ctx().sandbox.settings()).toEqual({ mode: "read-only" });
- const parked = (await a.inst.api.park()) as { motd: string; sandbox?: { mode: string } };
- expect(parked.sandbox).toEqual({ mode: "read-only" });
+ const parked = (await a.inst.api.park()) as {
+ motd: string;
+ modules: { SandboxModule?: { self: { settings?: { mode: string } } | null } };
+ };
+ expect(parked.modules.SandboxModule?.self).toEqual({ settings: { mode: "read-only" } });
const b = await bootObserved(parked);
try {
@@ -204,14 +231,45 @@ describe("sandbox settings ride the parked context across a swap", () => {
}
});
+ it("the document stays readable across generations: a first-generation doc boots, and what parks is a first-generation doc", async () => {
+ // The first platforms parked the settings as a top-level `sandbox` field, with no `modules`.
+ const a = await bootObserved({ motd: "gen-1", sandbox: { mode: "read-only" } });
+ try {
+ expect(a.ctx().sandbox.settings()).toEqual({ mode: "read-only" });
+ const parked = (await a.inst.api.park()) as {
+ motd: string;
+ sandbox?: unknown;
+ modules: { SandboxModule?: { self: unknown }; sandbox?: unknown };
+ };
+ // Parked both ways: under the node for this generation, top-level for the first one —
+ // so a rollback to a first-generation platform still confines.
+ expect(parked.modules.SandboxModule?.self).toEqual({ settings: { mode: "read-only" } });
+ expect(parked.sandbox).toEqual({ mode: "read-only" });
+ // A document parked under the node's earlier hand-written name reads the same.
+ const b = await bootObserved({
+ motd: "gen-2",
+ modules: { sandbox: { v: 1, self: { settings: { mode: "read-only" } } } },
+ });
+ try {
+ expect(b.ctx().sandbox.settings()).toEqual({ mode: "read-only" });
+ } finally {
+ b.inst.dispose();
+ }
+ } finally {
+ a.inst.dispose();
+ }
+ });
+
it("a document parked before the sandbox field existed restores as the default (off)", async () => {
const a = await bootObserved({ motd: "old-doc" });
try {
expect(a.ctx().sandbox.settings()).toEqual({ mode: "danger-full-access" });
- // The sandbox field is absent, not present-and-default: that is what keeps a
- // default deployment's document acceptable to a sandbox-ignorant bundle's schema.
- const parked = (await a.inst.api.park()) as { motd: string; sandbox?: unknown };
- expect(parked.sandbox).toBeUndefined();
+ // Pristine settings park as nothing, not as present-and-default.
+ const parked = (await a.inst.api.park()) as {
+ motd: string;
+ modules: { SandboxModule?: { self: unknown } };
+ };
+ expect(parked.modules.SandboxModule?.self ?? null).toBeNull();
expect(parked.motd).toBe("old-doc");
} finally {
a.inst.dispose();
diff --git a/packages/server/test/scheduler.test.ts b/packages/server/test/scheduler.test.ts
index 1ca69604..7fa76008 100644
--- a/packages/server/test/scheduler.test.ts
+++ b/packages/server/test/scheduler.test.ts
@@ -22,10 +22,13 @@ import { SchedulesRepo } from "../src/db/repos/schedules.js";
import { SessionsRepo } from "../src/db/repos/sessions.js";
import { UsersRepo } from "../src/db/repos/users.js";
import type { ErrorRecordArgs } from "../src/runtime/error-recorder.js";
+import type { ScheduleSessionCreator, ScheduleTaskRunner } from "../src/runtime/scheduler.js";
+import type { OmniMessage } from "@prismshadow/penguin-core";
import { Scheduler } from "../src/runtime/scheduler.js";
import { ProjectConfigService } from "../src/services/project-config-service.js";
import type { ScheduleServerEvent } from "../src/api/types.js";
import { makeTempRoot } from "./helpers.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
const P = "p1";
const A = "agent_x";
@@ -62,7 +65,7 @@ describe("scheduler", () => {
models: [{ provider: "custom", model_id: "m-bench" }],
});
db = openDatabase(":memory:");
- const users = new UsersRepo(db);
+ const users = wire(UsersRepo, { db: db });
users.insert({
userId: "owner_a",
passwordHash: "x",
@@ -72,10 +75,10 @@ describe("scheduler", () => {
avatar: null,
createdAt: "2026-07-16T00:00:00Z",
});
- const projects = new ProjectsRepo(db);
+ const projects = wire(ProjectsRepo, { db: db });
projects.insert({ projectId: P, ownerUserId: "owner_a", createdAt: "2026-07-16T00:00:00Z" });
- repo = new SchedulesRepo(db);
- sessions = new SessionsRepo(db);
+ repo = wire(SchedulesRepo, { db: db });
+ sessions = wire(SessionsRepo, { db: db });
nowMs = T0;
busy = new Set();
started = [];
@@ -83,29 +86,29 @@ describe("scheduler", () => {
events = [];
errors = [];
let seq = 0;
- scheduler = new Scheduler({
- root,
+ scheduler = wire(Scheduler, {
+ config: { root },
repo,
projects,
sessions,
runner: {
- statusOf: (id) => (busy.has(id) ? "running" : "idle"),
- startTask: async (sessionId, input) => {
+ statusOf: (id: string) => (busy.has(id) ? "running" : "idle"),
+ startTask: async (sessionId: string, input: OmniMessage[]) => {
started.push({ sessionId, text: JSON.stringify(input[0]?.payload ?? "") });
return { sessionId };
},
- },
+ } satisfies ScheduleTaskRunner,
sessionCreator: {
- createSession: async (args) => {
+ createSession: async (args: Parameters<ScheduleSessionCreator["createSession"]>[0]) => {
created.push(args);
const sessionId = `session-new-${++seq}`;
insertSession(sessionId);
return { sessionId };
},
},
- projectConfig: new ProjectConfigService(root),
- errors: { record: (args) => void errors.push(args) },
- notify: (userId, event) => void events.push({ userId, event }),
+ projectConfig: wire(ProjectConfigService, { config: { root } }),
+ errors: { record: (args: ErrorRecordArgs) => void errors.push(args) },
+ notify: (userId: string, event: ScheduleServerEvent) => void events.push({ userId, event }),
now: () => nowMs,
});
await fs.mkdir(scheduleDir(root, P, A), { recursive: true });
diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.ts
index 96054e50..f5a39e41 100644
--- a/packages/server/test/session-manager.test.ts
+++ b/packages/server/test/session-manager.test.ts
@@ -53,6 +53,7 @@ import { SessionSources } from "../src/runtime/session-sources.js";
import type { TitleRequest } from "../src/runtime/title-generator.js";
import type { UsageContext } from "../src/runtime/usage-recorder.js";
import { waitFor } from "./helpers.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
const ROW: SessionRow = {
sessionId: "session-1",
@@ -157,7 +158,7 @@ describe("session-manager", () => {
beforeEach(() => {
db = openDatabase(":memory:");
- sessions = new SessionsRepo(db);
+ sessions = wire(SessionsRepo, { db: db });
sessions.insert(ROW);
channels = new ChannelHub();
sources = new SessionSources();
diff --git a/packages/server/test/title-generator.test.ts b/packages/server/test/title-generator.test.ts
index dde8ade0..4b7887b2 100644
--- a/packages/server/test/title-generator.test.ts
+++ b/packages/server/test/title-generator.test.ts
@@ -20,6 +20,7 @@ import type { ChannelEvent } from "../src/runtime/channel.js";
import { TitleGenerator, fallbackTitle } from "../src/runtime/title-generator.js";
import type { UsageContext } from "../src/runtime/usage-recorder.js";
import { waitFor } from "./helpers.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
const ROW: SessionRow = {
sessionId: "session-t1",
@@ -101,7 +102,7 @@ describe("title-generator", () => {
beforeEach(() => {
db = openDatabase(":memory:");
- sessions = new SessionsRepo(db);
+ sessions = wire(SessionsRepo, { db: db });
sessions.insert(ROW);
channels = new ChannelHub();
recorded = [];
diff --git a/packages/server/test/trace-service.test.ts b/packages/server/test/trace-service.test.ts
index d329d7f9..d96f7632 100644
--- a/packages/server/test/trace-service.test.ts
+++ b/packages/server/test/trace-service.test.ts
@@ -38,6 +38,7 @@ const legacyEnd = (status: string) => requestEnd(status as StopReason);
import type { TraceService } from "../src/services/trace-service.js";
import type { SessionRow } from "../src/db/repos/sessions.js";
import { openDatabase } from "../src/db/database.js";
+import { wire } from "@prismshadow/penguin-core/kernel";
import { ErrorsRepo } from "../src/db/repos/errors.js";
import { UsageRepo } from "../src/db/repos/usage.js";
import { SessionSources } from "../src/runtime/session-sources.js";
@@ -255,7 +256,7 @@ describe("trace-service", () => {
// the figure the conversation toolbar shows — land on the file's total.
const db = openDatabase(":memory:");
try {
- const rows = new UsageRepo(db);
+ const rows = wire(UsageRepo, { db });
for (const ts of stamps) {
const at = new Date(Date.parse(ts) + 3000).toISOString();
rows.insert({
@@ -273,7 +274,12 @@ describe("trace-service", () => {
total: usage.total,
});
}
- const center = new UsageService(rows, new ErrorsRepo(db), lookup, () => new Date());
+ const center = wire(UsageService, {
+ usage: rows,
+ errors: wire(ErrorsRepo, { db }),
+ lookupPricing: lookup,
+ now: () => new Date(),
+ });
const res = await center.query(P, { groupBy: "session" });
expect(res.groups.find((g) => g.key === S)?.cost).toBeCloseTo(a.cost!, 12);
} finally {
diff --git a/packages/server/test/usage.test.ts b/packages/server/test/usage.test.ts
index 74b62adb..dbe2fedb 100644
--- a/packages/server/test/usage.test.ts
+++ b/packages/server/test/usage.test.ts
@@ -17,6 +17,7 @@ import type { PricingRates } from "../src/services/usage-service.js";
import { openDatabase } from "../src/db/database.js";
import { enumerateBuckets, enumerateTsBuckets, formatLocalDate } from "../src/internal/dates.js";
import type { DatabaseSync } from "node:sqlite";
+import { wire } from "@prismshadow/penguin-core/kernel";
const CTX = {
projectId: "project-x",
@@ -48,12 +49,12 @@ describe("usage-recorder", () => {
beforeEach(() => {
db = openDatabase(":memory:");
- repo = new UsageRepo(db);
+ repo = wire(UsageRepo, { db: db });
});
afterEach(() => db.close());
it("token_usage → one row (the request bucket; only Tokens persisted, never cost)", async () => {
- const rec = new UsageRecorder(repo);
+ const rec = wire(UsageRecorder, { usage: repo });
await rec.record(CTX, tokenUsage(counts(1000), counts(115)));
const rows = db.prepare("SELECT * FROM usage_records").all();
expect(rows).toHaveLength(1);
@@ -66,7 +67,7 @@ describe("usage-recorder", () => {
});
it("a sub-session's session_meta registers the origin→model mapping; token_usage is attributed via it", async () => {
- const rec = new UsageRecorder(repo);
+ const rec = wire(UsageRecorder, { usage: repo });
const childMeta = withOrigin(
sessionMeta(meta("session-child", "child-model")),
"session-child",
@@ -80,20 +81,20 @@ describe("usage-recorder", () => {
});
it("falls back to the main Session's Model when the origin mapping is missing", async () => {
- const rec = new UsageRecorder(repo);
+ const rec = wire(UsageRecorder, { usage: repo });
await rec.record(CTX, withOrigin(tokenUsage(counts(5), counts(5)), "session-unknown"));
const row = db.prepare("SELECT model_id FROM usage_records").get()!;
expect(row.model_id).toBe("main-model");
});
it("non-token_usage messages are a no-op", async () => {
- const rec = new UsageRecorder(repo);
+ const rec = wire(UsageRecorder, { usage: repo });
await rec.record(CTX, sessionMeta(meta("session-main", "main-model")));
expect(db.prepare("SELECT COUNT(*) AS n FROM usage_records").get()!.n).toBe(0);
});
it("the origin mapping is capped: past the limit the earliest entry is evicted and falls back to the main Session's Model", async () => {
- const rec = new UsageRecorder(repo);
+ const rec = wire(UsageRecorder, { usage: repo });
for (let i = 0; i <= ORIGIN_MODELS_MAX; i++) {
// ORIGIN_MODELS_MAX + 1 entries total: the earliest, sub-0, gets evicted.
await rec.record(CTX, withOrigin(sessionMeta(meta(`sub-${i}`, "sub-model")), `sub-${i}`));
@@ -123,9 +124,10 @@ describe("usage-service (cost computed on the fly)", () => {
beforeEach(() => {
db = openDatabase(":memory:");
- repo = new UsageRepo(db);
- const errors = new ErrorsRepo(db);
- service = (now: Date) => new UsageService(repo, errors, lookup, () => now);
+ repo = wire(UsageRepo, { db: db });
+ const errors = wire(ErrorsRepo, { db: db });
+ service = (now: Date) =>
+ wire(UsageService, { usage: repo, errors, lookupPricing: lookup, now: () => now });
pricing = { m1: { cacheRead: 0.3, cacheWrite: 3.75, output: 15 } };
});
afterEach(() => db.close());
@@ -170,7 +172,12 @@ describe("usage-service (cost computed on the fly)", () => {
const peakCost = (10 * 1 + 1 * 2 + 5 * 4) / 1e6;
const expected = peakCost + peakCost / 2;
for (const at of ["2026-08-31T01:30:00Z", "2026-08-31T12:00:00Z", "2026-09-06T01:30:00Z"]) {
- const svc = new UsageService(repo, new ErrorsRepo(db), tiered, () => new Date(at));
+ const svc = wire(UsageService, {
+ usage: repo,
+ errors: wire(ErrorsRepo, { db: db }),
+ lookupPricing: tiered,
+ now: () => new Date(at),
+ });
const res = await svc.query("p1", { groupBy: "date", from: "2026-08-31", to: "2026-08-31" });
expect(res.summary.total.cost, at).toBeCloseTo(expected, 10);
}
@@ -242,15 +249,15 @@ describe("usage-service (cost computed on the fly)", () => {
// covers it, so it must not be priced — and must not perturb the ones that are.
insert("2026-06-20", { modelId: "m-old" });
const asked: string[] = [];
- const svc = new UsageService(
- repo,
- new ErrorsRepo(db),
- async (p, provider, modelId) => {
+ const svc = wire(UsageService, {
+ usage: repo,
+ errors: wire(ErrorsRepo, { db: db }),
+ lookupPricing: async (p: string, provider: string, modelId: string) => {
asked.push(modelId);
return lookup(p, provider, modelId);
},
- () => now,
- );
+ now: () => now,
+ });
const res = await svc.query("p1", { groupBy: "date", from: "2026-07-06", to: "2026-07-06" });
expect(asked).toEqual(["m1"]);
expect(res.summary.total.cost).toBeCloseTo(ROW_COST, 12);
@@ -347,8 +354,12 @@ describe("usage-service model totals (unfiltered, for the models page)", () => {
beforeEach(() => {
db = openDatabase(":memory:");
- repo = new UsageRepo(db);
- service = new UsageService(repo, new ErrorsRepo(db), lookup);
+ repo = wire(UsageRepo, { db: db });
+ service = wire(UsageService, {
+ usage: repo,
+ errors: wire(ErrorsRepo, { db: db }),
+ lookupPricing: lookup,
+ });
});
afterEach(() => db.close());
@@ -407,9 +418,10 @@ describe("usage-service series (zero-filled time-series buckets)", () => {
beforeEach(() => {
db = openDatabase(":memory:");
- repo = new UsageRepo(db);
- const errors = new ErrorsRepo(db);
- service = (now: Date) => new UsageService(repo, errors, lookup, () => now);
+ repo = wire(UsageRepo, { db: db });
+ const errors = wire(ErrorsRepo, { db: db });
+ service = (now: Date) =>
+ wire(UsageService, { usage: repo, errors, lookupPricing: lookup, now: () => now });
pricing = { m1: { cacheRead: 0.3, cacheWrite: 3.75, output: 15 } };
});
afterEach(() => db.close());
@@ -677,8 +689,12 @@ describe("usage-service.queryErrors (error table paging)", () => {
beforeEach(() => {
db = openDatabase(":memory:");
- errors = new ErrorsRepo(db);
- service = new UsageService(new UsageRepo(db), errors, async () => undefined);
+ errors = wire(ErrorsRepo, { db: db });
+ service = wire(UsageService, {
+ usage: wire(UsageRepo, { db: db }),
+ errors,
+ lookupPricing: async () => undefined,
+ });
// 25 rows, oldest first — so "newest first" ordering is observable across a page boundary.
for (let i = 0; i < 25; i += 1) {
errors.insert({
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 5ed1faf6..0da79cec 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -155,6 +155,7 @@ import type {
VersionResponse,
WorkspaceFilesResponse,
WorkspaceSearchResponse,
+ ContributionsResponse,
} from "@prismshadow/penguin-server/api";
import type { MCPServerConfig } from "@prismshadow/penguin-core/interfaces";
import { apiFetch, apiFetchWithMeta } from "./client";
diff --git a/packages/web/src/lib/nav-group-collapse.ts b/packages/web/src/lib/nav-group-collapse.ts
index 2d0a7da7..05a066e3 100644
--- a/packages/web/src/lib/nav-group-collapse.ts
+++ b/packages/web/src/lib/nav-group-collapse.ts
@@ -22,15 +22,16 @@
* absent: reading a Trace happens in the chat toolbar's panel switcher, which is the only
* place it happens.
*/
-export const NAV_GROUP_KEYS = [
- "agents",
- "plugins",
- "models",
- "machines",
- "usage",
- "benchmark",
-] as const;
-export type NavGroupKey = (typeof NAV_GROUP_KEYS)[number];
+import { NAV_PAGE_KEYS, PAGES } from "./pages";
+
+export type NavGroupKey = "agents" | "plugins" | "models" | "machines" | "usage" | "benchmark";
+/**
+ * The manifest, derived from the app's own module.json (lib/pages.ts): every page whose
+ * `nav` is "main", in manifest order. The literal key type above is the set the strings
+ * and icons are typed against; pages.test.ts pins that the manifest never names a key
+ * outside it.
+ */
+export const NAV_GROUP_KEYS = NAV_PAGE_KEYS as readonly NavGroupKey[];
/**
* Entries the server refuses to a non-admin, so the sidebar does not offer them. Machines
@@ -38,7 +39,9 @@ export type NavGroupKey = (typeof NAV_GROUP_KEYS)[number];
* `/api/machines` gates on `isAdmin` — a row that always answers 403 is worse than no row.
* On a personal or desktop server the only account IS the admin, so nothing is hidden there.
*/
-const ADMIN_ONLY_NAV_KEYS: ReadonlySet<NavGroupKey> = new Set<NavGroupKey>(["machines"]);
+const ADMIN_ONLY_NAV_KEYS: ReadonlySet<NavGroupKey> = new Set(
+ PAGES.filter((p) => p.nav === "main" && p.admin).map((p) => p.key as NavGroupKey),
+);
/**
* Entries built but not yet offered. They keep their place in the manifest — the page, its
@@ -50,7 +53,9 @@ const ADMIN_ONLY_NAV_KEYS: ReadonlySet<NavGroupKey> = new Set<NavGroupKey>(["mac
* That is a capability worth shipping deliberately rather than as a row that happens to appear,
* so it waits for a release that means to introduce it.
*/
-const UNRELEASED_NAV_KEYS: ReadonlySet<NavGroupKey> = new Set<NavGroupKey>(["machines"]);
+const UNRELEASED_NAV_KEYS: ReadonlySet<NavGroupKey> = new Set(
+ PAGES.filter((p) => p.nav === "main" && !p.released).map((p) => p.key as NavGroupKey),
+);
/** The manifest as this user sees it. */
export function navKeysFor(isAdmin: boolean): readonly NavGroupKey[] {
diff --git a/packages/web/src/lib/pages.ts b/packages/web/src/lib/pages.ts
new file mode 100644
index 00000000..d973c26c
--- /dev/null
+++ b/packages/web/src/lib/pages.ts
@@ -0,0 +1,66 @@
+/**
+ * The web app's pages, from its own manifest (src/module.json — the `web.pages` slot the
+ * server's web module declares). The router mounts them and the sidebar's nav group is
+ * derived from them, so a page is one JSON entry: its route, whether it sits in the main
+ * nav, whether the server refuses it to non-admins, and which renderer draws it.
+ *
+ * The same shape arrives from the server (GET /api/contributions) for pages a pushed
+ * platform or a plugin contributes; `mergePages` folds those in — a page whose
+ * renderer this build does not carry is skipped, since there is nothing to draw it with.
+ */
+import manifest from "../module.json";
+
+export interface PageEntry {
+ id: string;
+ key: string;
+ path: string;
+ nav: "main" | "none";
+ admin: boolean;
+ /** Built but not yet offered: kept in the manifest, reachable by URL and tests, hidden from the nav. */
+ released: boolean;
+ renderer: { builtin: string } | { iframe: { src: string; namespace: string } };
+}
+
+export const PAGES: readonly PageEntry[] = manifest.contributes["web.pages"] as PageEntry[];
+
+/** Keys of the pages in the main nav, in manifest order — the nav manifest. */
+export const NAV_PAGE_KEYS: readonly string[] = PAGES.filter((p) => p.nav === "main").map(
+ (p) => p.key,
+);
+
+/** The nav as this user sees it: released pages, minus admin-only ones for a non-admin. */
+export function navPagesFor(isAdmin: boolean): readonly PageEntry[] {
+ return PAGES.filter((p) => p.nav === "main" && p.released && (isAdmin || !p.admin));
+}
+
+/**
+ * Local pages plus server-contributed ones this build can render. A server entry whose
+ * key a local page already owns is ignored — the local manifest wins for its own pages.
+ */
+export function mergePages(
+ local: readonly PageEntry[],
+ remote: ReadonlyArray<Record<string, unknown>>,
+ builtinRenderers: ReadonlySet<string>,
+): PageEntry[] {
+ const keys = new Set(local.map((p) => p.key));
+ const out = [...local];
+ for (const entry of remote) {
+ const page = entry as Partial<PageEntry>;
+ if (typeof page.key !== "string" || typeof page.path !== "string" || keys.has(page.key))
+ continue;
+ const renderer = page.renderer;
+ if (renderer === undefined) continue;
+ if ("builtin" in renderer && !builtinRenderers.has(renderer.builtin)) continue;
+ out.push({
+ id: typeof page.id === "string" ? page.id : `remote.${page.key}`,
+ key: page.key,
+ path: page.path,
+ nav: page.nav === "main" ? "main" : "none",
+ admin: page.admin === true,
+ released: page.released !== false,
+ renderer,
+ });
+ keys.add(page.key);
+ }
+ return out;
+}
diff --git a/packages/web/src/module.json b/packages/web/src/module.json
new file mode 100644
index 00000000..69ead2fe
--- /dev/null
+++ b/packages/web/src/module.json
@@ -0,0 +1,109 @@
+{
+ "name": "web",
+ "provides": {
+ "web": "WebShell"
+ },
+ "contributes": {
+ "web.pages": [
+ {
+ "id": "web.chat",
+ "key": "chat",
+ "path": "/chat/:sessionId?",
+ "nav": "none",
+ "admin": false,
+ "released": true,
+ "renderer": {
+ "builtin": "ChatPage"
+ }
+ },
+ {
+ "id": "web.agents",
+ "key": "agents",
+ "path": "/agents",
+ "nav": "main",
+ "admin": false,
+ "released": true,
+ "renderer": {
+ "builtin": "AgentsPage"
+ }
+ },
+ {
+ "id": "web.agent-settings",
+ "key": "agent-settings",
+ "path": "/agents/:agentId",
+ "nav": "none",
+ "admin": false,
+ "released": true,
+ "renderer": {
+ "builtin": "AgentSettingsPage"
+ }
+ },
+ {
+ "id": "web.plugins",
+ "key": "plugins",
+ "path": "/plugins",
+ "nav": "main",
+ "admin": false,
+ "released": true,
+ "renderer": {
+ "builtin": "PluginsPage"
+ }
+ },
+ {
+ "id": "web.models",
+ "key": "models",
+ "path": "/models",
+ "nav": "main",
+ "admin": false,
+ "released": true,
+ "renderer": {
+ "builtin": "ModelsPage"
+ }
+ },
+ {
+ "id": "web.machines",
+ "key": "machines",
+ "path": "/machines",
+ "nav": "main",
+ "admin": true,
+ "released": false,
+ "renderer": {
+ "builtin": "MachinesPage"
+ }
+ },
+ {
+ "id": "web.usage",
+ "key": "usage",
+ "path": "/usage",
+ "nav": "main",
+ "admin": false,
+ "released": true,
+ "renderer": {
+ "builtin": "UsagePage"
+ }
+ },
+ {
+ "id": "web.benchmark",
+ "key": "benchmark",
+ "path": "/benchmark",
+ "nav": "main",
+ "admin": false,
+ "released": true,
+ "renderer": {
+ "builtin": "BenchmarkPage"
+ }
+ },
+ {
+ "id": "web.benchmark-detail",
+ "key": "benchmark-detail",
+ "path": "/benchmark/:benchmarkId",
+ "nav": "none",
+ "admin": false,
+ "released": true,
+ "renderer": {
+ "builtin": "BenchmarkDetailPage"
+ }
+ }
+ ]
+ }
+}
diff --git a/packages/web/src/router.tsx b/packages/web/src/router.tsx
index de2d3259..0b32ab04 100644
--- a/packages/web/src/router.tsx
+++ b/packages/web/src/router.tsx
@@ -18,6 +18,35 @@ import { UsagePage } from "./features/usage/usage-page";
import { BenchmarkPage } from "./features/benchmark/benchmark-page";
import { BenchmarkDetailPage } from "./features/benchmark/benchmark-detail-page";
import { TerminalPage } from "./features/terminal/terminal-page";
+import { MachinesPage } from "./features/machines/machines-page";
+import { PAGES } from "./lib/pages";
+import type { PageEntry } from "./lib/pages";
+
+/**
+ * The renderers the manifest may name. A page is a module.json entry plus one line here;
+ * a server-contributed page renders only when its `builtin` is in this registry.
+ */
+const BUILTIN_PAGES: Record<string, React.ComponentType> = {
+ ChatPage,
+ AgentsPage,
+ AgentSettingsPage,
+ PluginsPage,
+ ModelsPage,
+ MachinesPage,
+ UsagePage,
+ BenchmarkPage,
+ BenchmarkDetailPage,
+};
+
+function renderPage(page: PageEntry): React.ReactNode {
+ if ("iframe" in page.renderer) {
+ return (
+ <iframe title={page.key} src={page.renderer.iframe.src} className="h-full w-full border-0" />
+ );
+ }
+ const Component = BUILTIN_PAGES[page.renderer.builtin];
+ return Component === undefined ? <Navigate to="/chat" replace /> : <Component />;
+}
/** Route guard: shows blank while initializing, redirects to /login when not authenticated. */
function RequireAuth() {
@@ -67,16 +96,12 @@ export function AppRouter() {
/>
<Route element={<RequireAuth />}>
<Route index element={<Navigate to="/chat" replace />} />
- <Route path="/chat/:sessionId?" element={<ChatPage />} />
- <Route path="/agents" element={<AgentsPage />} />
- <Route path="/agents/:agentId" element={<AgentSettingsPage />} />
- <Route path="/plugins" element={<PluginsPage />} />
- <Route path="/models" element={<ModelsPage />} />
- {/* Admin-only server-side (403 otherwise); the sidebar hides the row for
- everyone else, so a member only ever reaches this by typing the URL. */}
- <Route path="/usage" element={<UsagePage />} />
- <Route path="/benchmark" element={<BenchmarkPage />} />
- <Route path="/benchmark/:benchmarkId" element={<BenchmarkDetailPage />} />
+ {/* Every page is a module.json entry (lib/pages.ts). Admin-only ones are refused
+ server-side (403); the sidebar hides their row, so a member only ever reaches
+ one by typing the URL. */}
+ {PAGES.map((page) => (
+ <Route key={page.id} path={page.path} element={renderPage(page)} />
+ ))}
{/* System settings and user management live in the settings dialog now (see
SettingsDialog); their old routes fall through to the catch-all. */}
<Route path="*" element={<Navigate to="/chat" replace />} />
diff --git a/packages/web/test/nav-group-collapse.test.ts b/packages/web/test/nav-group-collapse.test.ts
index bd648378..d6b9dd1b 100644
--- a/packages/web/test/nav-group-collapse.test.ts
+++ b/packages/web/test/nav-group-collapse.test.ts
@@ -47,7 +47,7 @@ describe("NAV_GROUP_KEYS", () => {
"benchmark",
]);
// Pin the endpoints by label: a manifest edit that shifts the range shows up here.
- expect(zh.nav[NAV_GROUP_KEYS[0]]).toBe("智能体");
+ expect(zh.nav[NAV_GROUP_KEYS[0]!]).toBe("智能体");
expect(zh.nav[NAV_GROUP_KEYS[NAV_GROUP_KEYS.length - 1]!]).toBe("评估中心");
});
diff --git a/packages/web/test/pages.test.ts b/packages/web/test/pages.test.ts
new file mode 100644
index 00000000..919678ec
--- /dev/null
+++ b/packages/web/test/pages.test.ts
@@ -0,0 +1,90 @@
+/**
+ * The web app's page manifest (src/module.json) and how server contributions fold in.
+ */
+import { describe, expect, it } from "vitest";
+import { NAV_PAGE_KEYS, PAGES, mergePages, navPagesFor } from "../src/lib/pages";
+import { NAV_GROUP_KEYS } from "../src/lib/nav-group-collapse";
+import { zh } from "../src/lib/strings";
+import { NAV_ICONS } from "../src/components/ui/icons";
+
+describe("the page manifest", () => {
+ it("names only keys the nav strings and icons are typed for", () => {
+ for (const key of NAV_PAGE_KEYS) {
+ expect(zh.nav).toHaveProperty(key);
+ expect(NAV_ICONS).toHaveProperty(key);
+ }
+ expect(NAV_GROUP_KEYS).toEqual(NAV_PAGE_KEYS);
+ });
+
+ it("every page has a unique id, key and path, and a renderer", () => {
+ const ids = new Set(PAGES.map((p) => p.id));
+ expect(ids.size).toBe(PAGES.length);
+ expect(new Set(PAGES.map((p) => p.key)).size).toBe(PAGES.length);
+ expect(new Set(PAGES.map((p) => p.path)).size).toBe(PAGES.length);
+ for (const page of PAGES)
+ expect("builtin" in page.renderer || "iframe" in page.renderer).toBe(true);
+ });
+
+ it("the nav a member sees drops admin-only and unreleased pages", () => {
+ const admin = navPagesFor(true).map((p) => p.key);
+ const member = navPagesFor(false).map((p) => p.key);
+ expect(admin).not.toContain("machines"); // unreleased for everyone
+ expect(member.every((key) => admin.includes(key))).toBe(true);
+ for (const page of PAGES.filter((p) => p.nav === "main" && p.admin))
+ expect(member).not.toContain(page.key);
+ });
+});
+
+describe("mergePages", () => {
+ const known = new Set(["AgentsPage", "UsagePage"]);
+
+ it("adds a server page whose renderer this build carries, after the local ones", () => {
+ const merged = mergePages(
+ PAGES,
+ [
+ {
+ id: "x.reports",
+ key: "reports",
+ path: "/reports",
+ nav: "main",
+ renderer: { builtin: "UsagePage" },
+ },
+ ],
+ known,
+ );
+ expect(merged.at(-1)).toMatchObject({
+ key: "reports",
+ path: "/reports",
+ nav: "main",
+ admin: false,
+ released: true,
+ });
+ });
+
+ it("skips a page with an unknown builtin renderer, and keeps a local page over a same-key remote one", () => {
+ const merged = mergePages(
+ PAGES,
+ [
+ { key: "later", path: "/later", renderer: { builtin: "NotBuiltHere" } },
+ { key: "agents", path: "/elsewhere", renderer: { builtin: "AgentsPage" } },
+ ],
+ known,
+ );
+ expect(merged.map((p) => p.key)).toEqual(PAGES.map((p) => p.key));
+ });
+
+ it("an iframe renderer needs no registry entry", () => {
+ const merged = mergePages(
+ [],
+ [
+ {
+ key: "wf",
+ path: "/wf",
+ renderer: { iframe: { src: "/workflow/a/wf/", namespace: "wf" } },
+ },
+ ],
+ known,
+ );
+ expect(merged).toHaveLength(1);
+ });
+});
diff --git a/plugins/sandbox-bwrap/package.json b/plugins/sandbox-bwrap/package.json
index 180dd8c3..53e4a03d 100644
--- a/plugins/sandbox-bwrap/package.json
+++ b/plugins/sandbox-bwrap/package.json
@@ -15,12 +15,13 @@
"license": "Apache-2.0",
"files": [
"dist",
- "README.md"
+ "README.md",
+ "ifaces.json"
],
"scripts": {
"typecheck": "tsc --noEmit -p tsconfig.json",
"test": "vitest run --passWithNoTests",
- "build": "tsup"
+ "build": "node ../../scripts/gen-ifaces.mjs --project tsconfig.json --out ifaces.json && tsup"
},
"devDependencies": {
"@prismshadow/penguin-core": "workspace:*",
diff --git a/plugins/sandbox-bwrap/src/index.ts b/plugins/sandbox-bwrap/src/index.ts
index 53ace425..e7bd0b3e 100644
--- a/plugins/sandbox-bwrap/src/index.ts
+++ b/plugins/sandbox-bwrap/src/index.ts
@@ -3,8 +3,9 @@
*
* A PLUGIN PACKAGE, not part of the platform: a deployment lists it in plugins.json and
* the harness resolves it from the installation (see the server's plugin/loader.ts).
- * It compiles against the type-only `@prismshadow/penguin-core/plugin` surface and
- * carries no runtime dependency on the harness — and none on the DSH ecosystem either:
+ * It compiles against the `@prismshadow/penguin-core/plugin` surface (types, plus the
+ * decorators its bundle carries) and has no runtime dependency on the harness — and
+ * none on the DSH ecosystem either:
* it talks to `bwrap` directly and implements every dimension of the sandbox interface,
* including the two DSH's vocabulary does not cover.
*
@@ -33,9 +34,10 @@ import { spawnSync } from "node:child_process";
import { statSync } from "node:fs";
import path from "node:path";
import { tmpdir } from "node:os";
+import { Bind, Component } from "@prismshadow/penguin-core/plugin";
import type {
ConfinedArgv,
- PluginContext,
+ Plugin,
SandboxPolicy,
SandboxProvider,
} from "@prismshadow/penguin-core/plugin";
@@ -126,11 +128,29 @@ export function createPenguinBwrapProvider(internals: PenguinBwrapInternals = {}
};
}
-/** The plugin: registered per App creation, like every other backend. Default export = the plugin. */
-export function activate(ctx: PluginContext): void {
- // Backends register per App creation — a hot swap re-registers them into the fresh
- // registry — so the subscription is to the event, not a one-time registration here.
- ctx.on("initialize", (iface) => {
- iface.sandbox.registerProvider("penguin-bwrap", createPenguinBwrapProvider());
- });
+/**
+ * The plugin's one module: a provider on the sandbox slot, the code half of the
+ * contribution the decorator declares (its manifest is generated into ifaces.json from
+ * here). Created per App, so a hot swap gets a fresh provider.
+ */
+@Component({
+ contributes: {
+ "SandboxModule.providers": [
+ {
+ id: "sandbox-bwrap.provider",
+ name: "penguin-bwrap",
+ dimensions: ["fs-write", "network", "mask-paths"],
+ },
+ ],
+ },
+})
+export class SandboxBwrap {
+ @Bind("sandbox-bwrap.provider") provider!: SandboxProvider;
+
+ setup() {
+ this.provider = createPenguinBwrapProvider();
+ }
}
+
+const plugin: Plugin = { modules: [SandboxBwrap] };
+export default plugin;
diff --git a/plugins/sandbox-dsh/package.json b/plugins/sandbox-dsh/package.json
index b6689615..35594712 100644
--- a/plugins/sandbox-dsh/package.json
+++ b/plugins/sandbox-dsh/package.json
@@ -15,12 +15,13 @@
"license": "Apache-2.0",
"files": [
"dist",
- "README.md"
+ "README.md",
+ "ifaces.json"
],
"scripts": {
"typecheck": "tsc --noEmit -p tsconfig.json",
"test": "vitest run --passWithNoTests",
- "build": "tsup"
+ "build": "node ../../scripts/gen-ifaces.mjs --project tsconfig.json --out ifaces.json && tsup"
},
"dependencies": {
"@deepseek-ai/cordis": "^4.0.1",
diff --git a/plugins/sandbox-dsh/src/index.ts b/plugins/sandbox-dsh/src/index.ts
index 1a248ebe..27dfab21 100644
--- a/plugins/sandbox-dsh/src/index.ts
+++ b/plugins/sandbox-dsh/src/index.ts
@@ -21,22 +21,22 @@
* them fails THIS load — reported fail-closed by the service — instead of failing the
* whole platform bundle's import.
*/
+import { Bind, Component } from "@prismshadow/penguin-core/plugin";
import type {
ConfinedArgv,
- PluginContext,
+ Plugin,
SandboxProvider,
+ SandboxProviderSource,
} from "@prismshadow/penguin-core/plugin";
/** Mount the stock DSH chain on a bare cordis Context — exactly how DSH's own tests mount it. */
export async function loadDshAdaptor(): Promise<SandboxProvider | null> {
const { Context } = await import("@deepseek-ai/cordis");
const { LocalSandboxProvider } = await import("@deepseek-ai/dsh-sandbox-local");
- const cordisCtx = new Context();
- // A cordis plugin, not a Penguin one: `Context.plugin` is cordis's own API, and the two
- // vocabularies share nothing but the word. Hence the name — `ctx` in this package is
- // the PluginContext `activate` receives, below.
- await cordisCtx.plugin(LocalSandboxProvider, {});
- const dsh = cordisCtx.sandbox;
+ const ctx = new Context();
+ // `ctx.plugin` is cordis's own API name, not this repo's vocabulary.
+ await ctx.plugin(LocalSandboxProvider, {});
+ const dsh = ctx.sandbox;
return {
// DSH's own words: "Network and process visibility are outside this vocabulary."
dimensions: ["fs-write"],
@@ -55,11 +55,25 @@ export async function loadDshAdaptor(): Promise<SandboxProvider | null> {
};
}
-/** The plugin: registered per App creation, so a hot swap re-registers it. Default export = the plugin. */
-export function activate(ctx: PluginContext): void {
- // Backends register per App creation — a hot swap re-registers them into the fresh
- // registry — so the subscription is to the event, not a one-time registration here.
- ctx.on("initialize", (iface) => {
- iface.sandbox.registerProvider("dsh-local", loadDshAdaptor());
- });
+/**
+ * The plugin's one module: a provider on the sandbox slot, the code half of the
+ * contribution the decorator declares (its manifest is generated into ifaces.json from
+ * here). Created per App, so a hot swap gets a fresh provider.
+ */
+@Component({
+ contributes: {
+ "SandboxModule.providers": [
+ { id: "sandbox-dsh.provider", name: "dsh-local", dimensions: ["fs-write"] },
+ ],
+ },
+})
+export class SandboxDsh {
+ @Bind("sandbox-dsh.provider") provider!: SandboxProviderSource;
+
+ setup() {
+ this.provider = loadDshAdaptor();
+ }
}
+
+const plugin: Plugin = { modules: [SandboxDsh] };
+export default plugin;
diff --git a/plugins/sandbox-mxc/package.json b/plugins/sandbox-mxc/package.json
index ec1acf6e..b31fd14e 100644
--- a/plugins/sandbox-mxc/package.json
+++ b/plugins/sandbox-mxc/package.json
@@ -15,12 +15,13 @@
"license": "Apache-2.0",
"files": [
"dist",
- "README.md"
+ "README.md",
+ "ifaces.json"
],
"scripts": {
"typecheck": "tsc --noEmit -p tsconfig.json",
"test": "vitest run --passWithNoTests",
- "build": "tsup"
+ "build": "node ../../scripts/gen-ifaces.mjs --project tsconfig.json --out ifaces.json && tsup"
},
"peerDependencies": {
"@microsoft/mxc-sdk": ">=0.7.0 <1"
diff --git a/plugins/sandbox-mxc/src/index.ts b/plugins/sandbox-mxc/src/index.ts
index f301b1a8..2f9e0b44 100644
--- a/plugins/sandbox-mxc/src/index.ts
+++ b/plugins/sandbox-mxc/src/index.ts
@@ -3,8 +3,9 @@
* MXC (Microsoft eXecution Containers).
*
* A PLUGIN PACKAGE, not part of the platform: a deployment lists it in plugins.json and
- * the harness resolves it from the installation. It compiles against the type-only
- * `@prismshadow/penguin-core/plugin` surface and has no runtime dependency on the
+ * the harness resolves it from the installation. It compiles against the
+ * `@prismshadow/penguin-core/plugin` surface (types, plus the decorators its bundle
+ * carries) and has no runtime dependency on the
* harness or on any other backend.
*
* WHY THIS EXISTS: Windows has no bubblewrap and no sandbox-exec, and the DSH adaptor's
@@ -38,11 +39,13 @@
import { createRequire } from "node:module";
import path from "node:path";
import { spawnSync } from "node:child_process";
+import { Bind, Component } from "@prismshadow/penguin-core/plugin";
import type {
ConfinedArgv,
- PluginContext,
+ Plugin,
SandboxPolicy,
SandboxProvider,
+ SandboxProviderSource,
} from "@prismshadow/penguin-core/plugin";
/** Default probe budget; a probe that hangs must not hang the first spawn forever. */
@@ -186,11 +189,29 @@ export function createMxcProvider(
};
}
-/** The plugin: registered per App creation, like every other backend. Default export = the plugin. */
-export function activate(ctx: PluginContext): void {
- // Backends register per App creation — a hot swap re-registers them into the fresh
- // registry — so the subscription is to the event, not a one-time registration here.
- ctx.on("initialize", (iface) => {
- iface.sandbox.registerProvider("penguin-mxc", loadMxcProvider());
- });
+/**
+ * The plugin's one module: a provider on the sandbox slot, the code half of the
+ * contribution the decorator declares (its manifest is generated into ifaces.json from
+ * here). Created per App, so a hot swap gets a fresh provider.
+ */
+@Component({
+ contributes: {
+ "SandboxModule.providers": [
+ {
+ id: "sandbox-mxc.provider",
+ name: "penguin-mxc",
+ dimensions: ["fs-write", "network", "mask-paths"],
+ },
+ ],
+ },
+})
+export class SandboxMxc {
+ @Bind("sandbox-mxc.provider") provider!: SandboxProviderSource;
+
+ setup() {
+ this.provider = loadMxcProvider();
+ }
}
+
+const plugin: Plugin = { modules: [SandboxMxc] };
+export default plugin;
diff --git a/plugins/sandbox-seatbelt/package.json b/plugins/sandbox-seatbelt/package.json
index eb6e8b30..fce4adc2 100644
--- a/plugins/sandbox-seatbelt/package.json
+++ b/plugins/sandbox-seatbelt/package.json
@@ -15,12 +15,13 @@
"license": "Apache-2.0",
"files": [
"dist",
- "README.md"
+ "README.md",
+ "ifaces.json"
],
"scripts": {
"typecheck": "tsc --noEmit -p tsconfig.json",
"test": "vitest run --passWithNoTests",
- "build": "tsup"
+ "build": "node ../../scripts/gen-ifaces.mjs --project tsconfig.json --out ifaces.json && tsup"
},
"devDependencies": {
"@prismshadow/penguin-core": "workspace:*",
diff --git a/plugins/sandbox-seatbelt/src/index.ts b/plugins/sandbox-seatbelt/src/index.ts
index 65e156f0..0a6aec0a 100644
--- a/plugins/sandbox-seatbelt/src/index.ts
+++ b/plugins/sandbox-seatbelt/src/index.ts
@@ -2,8 +2,9 @@
* @prismshadow/penguin-plugin-sandbox-seatbelt — a macOS Seatbelt sandbox backend.
*
* A PLUGIN PACKAGE, not part of the platform: a deployment lists it in plugins.json and
- * the harness resolves it from the installation. It compiles against the type-only
- * `@prismshadow/penguin-core/plugin` surface and has no runtime dependency on the
+ * the harness resolves it from the installation. It compiles against the
+ * `@prismshadow/penguin-core/plugin` surface (types, plus the decorators its bundle
+ * carries) and has no runtime dependency on the
* harness or on any other backend.
*
* Seatbelt is the macOS counterpart to bubblewrap here, and it expresses all three
@@ -32,9 +33,10 @@ import { spawnSync } from "node:child_process";
import { realpathSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
+import { Bind, Component } from "@prismshadow/penguin-core/plugin";
import type {
ConfinedArgv,
- PluginContext,
+ Plugin,
SandboxPolicy,
SandboxProvider,
} from "@prismshadow/penguin-core/plugin";
@@ -149,11 +151,29 @@ export function createSeatbeltProvider(internals: SeatbeltInternals = {}): Sandb
};
}
-/** The plugin: registered per App creation, like every other backend. Default export = the plugin. */
-export function activate(ctx: PluginContext): void {
- // Backends register per App creation — a hot swap re-registers them into the fresh
- // registry — so the subscription is to the event, not a one-time registration here.
- ctx.on("initialize", (iface) => {
- iface.sandbox.registerProvider("penguin-seatbelt", createSeatbeltProvider());
- });
+/**
+ * The plugin's one module: a provider on the sandbox slot, the code half of the
+ * contribution the decorator declares (its manifest is generated into ifaces.json from
+ * here). Created per App, so a hot swap gets a fresh provider.
+ */
+@Component({
+ contributes: {
+ "SandboxModule.providers": [
+ {
+ id: "sandbox-seatbelt.provider",
+ name: "penguin-seatbelt",
+ dimensions: ["fs-write", "network", "mask-paths"],
+ },
+ ],
+ },
+})
+export class SandboxSeatbelt {
+ @Bind("sandbox-seatbelt.provider") provider!: SandboxProvider;
+
+ setup() {
+ this.provider = createSeatbeltProvider();
+ }
}
+
+const plugin: Plugin = { modules: [SandboxSeatbelt] };
+export default plugin;
diff --git a/scripts/deploy.mjs b/scripts/deploy.mjs
index b3ca241e..d0d6a99f 100644
--- a/scripts/deploy.mjs
+++ b/scripts/deploy.mjs
@@ -144,6 +144,19 @@ async function login() {
*/
async function compileEntry(entry, outfile) {
if (!fs.existsSync(entry)) throw new Error(`compile entry missing: ${entry}`);
+ // The platform imports its generated interface table; make sure it is current.
+ const { execFileSync } = await import("node:child_process");
+ execFileSync(
+ process.execPath,
+ [
+ path.join(ROOT, "scripts/gen-ifaces.mjs"),
+ "--project",
+ path.join(ROOT, "packages/server/tsconfig.json"),
+ "--out",
+ path.join(ROOT, "packages/server/src/ifaces.json"),
+ ],
+ { stdio: "inherit" },
+ );
const esbuild = await import("esbuild");
await esbuild.build({
entryPoints: [entry],
diff --git a/scripts/gen-ifaces.mjs b/scripts/gen-ifaces.mjs
index f46c578d..61cce5d9 100644
--- a/scripts/gen-ifaces.mjs
+++ b/scripts/gen-ifaces.mjs
@@ -72,8 +72,8 @@ function moduleNameOf(fileName) {
const start = dir;
for (;;) {
// A module's name is the `name` of the defineModule({...}) literal in its module.ts;
- // a plugin package's is the one its package.json#penguin.modules entry names,
- // which the package name stands in for here (one module per package is the common case).
+ // a plugin package's classes are keyed by the package name (the table it ships is
+ // generated over its own tsconfig, so the key only has to agree within it).
const mts = path.join(dir, "module.ts");
if (fs.existsSync(mts)) {
const m =