Skip to content

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

refactor(core): split the interface contracts by which side of the engine needs them (#459)

Yaowei Zheng6528f21463dc
diff --git a/changelog/unreleased/2026-08-24-interfaces-split.md b/changelog/unreleased/2026-08-24-interfaces-split.md
new file mode 100644
index 00000000..4bb57dde
--- /dev/null
+++ b/changelog/unreleased/2026-08-24-interfaces-split.md
@@ -0,0 +1,66 @@
+# Interface contracts split by which side of the engine needs them
+
+- **Date:** 2026-08-24
+- **Type:** refactor
+- **Scope:** `core`, `server`, `docs`
+- **PR:** [#459](https://github.com/Prism-Shadow/penguin-harness/pull/459)
+- **Breaking:** yes — `SubagentHandle.run` and `sendToBackgroundSubagent` take an OmniMessage list instead of a string, and the build/version types left the `/interfaces` subpath
+
+[中文版](2026-08-24-interfaces-split.zh.md)
+
+`packages/core/src/interfaces.ts` held four unrelated groups in one 749-line file, with the
+build/version types physically splitting the Environment section in half. It is now a
+directory, divided by which side of `context_engine` needs each contract, and the
+message-versus-control division that runs through all three boundaries is written down.
+
+## The split
+
+- `interfaces/llm.ts` — the model-request contract (`GenerativeModelConfig`,
+ `GenerativeModelParameters`, `LLMOutcome`, `LLMInterface`).
+- `interfaces/environment.ts` — tool execution, configuration, the subagent contracts, and
+ the management-plane API.
+- `interfaces/shared.ts` — the vocabulary both sides genuinely need: `ToolDefinition`,
+ `ThinkingLevelName`, `ApproveFn`, the command policy.
+- `interfaces/index.ts` — the barrel, still the published
+ `@prismshadow/penguin-core/interfaces` entry, so existing imports keep working.
+- `version-info.ts` — `BuildInfo` / `HarnessInfo` / `VersionReport` and friends, which
+ describe neither contract; they ship from the package root now.
+
+## Two planes, stated
+
+The docs page ([Core Interfaces](/interfaces)) now states what crosses each boundary. The
+**content** is OmniMessage and nothing else. Alongside it runs a **control plane** that is
+deliberately not message-shaped — `signal`, `thinkingLevel`, `approve` and its
+`ApprovalDecision`, and `streamGenerate`'s `LLMOutcome` return value — each with the reason
+it stays a parameter. Environment's remaining non-message members are named as its
+**management plane**: `listTools`, `toolPermission`, the background-command and subagent
+listings, their stop/steer entry points and the listener attachments — none of which pass
+through the engine at all, since they serve Session assembly and a host's own UI.
+
+## One vocabulary into a subagent
+
+`SubagentHandle.run` took a `prompt: string` while the same handle's `steer` took
+`OmniMessage[]`, and `sendToBackgroundSubagent` took a `text: string`. Both now take the
+OmniMessage list `Session.run` takes.
+
+The caller owns each message's `sender`, which fixes a mis-attribution: a round started from
+the subagents panel on an idle child was stamped `parent_agent`, recording the user's own
+words in the child's Trace as if the parent agent had dispatched them. Only the model's
+dispatch stamps `parent_agent` now; a panel message carries no sender, matching what the
+panel's steering path already did.
+
+## Compatibility
+
+No stored data or configuration is affected, and no host-visible behavior changes apart from
+the `sender` fix above. Two source-level breaks for SDK embedders:
+
+- An embedder providing its own `SubagentRunner` must change `run({ prompt })` to
+ `run({ messages })` — `messages` is the round's input in the shape `Session.run` takes
+ (`[userText(prompt, "parent_agent")]` reproduces the old behavior exactly). The same
+ applies to a custom `EnvironmentInterface.sendToBackgroundSubagent`.
+- `BuildInfo`, `BuildRuntimeInfo`, `HarnessInfo`, `HarnessSource` and `VersionReport` are no
+ longer exported from `@prismshadow/penguin-core/interfaces`; import them from
+ `@prismshadow/penguin-core`.
+
+No compatibility shim is kept for either: both are compile-time errors with a one-line fix,
+and a dual-shape `run` argument would have re-introduced the ambiguity this change removes.
diff --git a/changelog/unreleased/2026-08-24-interfaces-split.zh.md b/changelog/unreleased/2026-08-24-interfaces-split.zh.md
new file mode 100644
index 00000000..26de4b81
--- /dev/null
+++ b/changelog/unreleased/2026-08-24-interfaces-split.zh.md
@@ -0,0 +1,57 @@
+# 接口契约按「引擎哪一侧需要」拆分
+
+- **Date:** 2026-08-24
+- **Type:** refactor
+- **Scope:** `core`, `server`, `docs`
+- **PR:** [#459](https://github.com/Prism-Shadow/penguin-harness/pull/459)
+- **Breaking:** yes — `SubagentHandle.run` 与 `sendToBackgroundSubagent` 改收 OmniMessage 数组而非字符串,且 build/version 类型移出 `/interfaces` 子路径
+
+[English](2026-08-24-interfaces-split.md)
+
+`packages/core/src/interfaces.ts` 把四组互不相关的东西塞在一个 749 行的文件里,其中 build/version
+类型还在物理上把 Environment 段劈成两半。现在它是一个目录,按 `context_engine` 的哪一侧需要该契约
+划分;贯穿三条边界的「消息面 / 控制面」之分也一并写进文档。
+
+## 划分
+
+- `interfaces/llm.ts`——模型请求契约(`GenerativeModelConfig`、`GenerativeModelParameters`、
+ `LLMOutcome`、`LLMInterface`)。
+- `interfaces/environment.ts`——工具执行、配置、子会话契约,以及管理面 API。
+- `interfaces/shared.ts`——两侧确实共用的词汇:`ToolDefinition`、`ThinkingLevelName`、
+ `ApproveFn`、命令策略。
+- `interfaces/index.ts`——barrel,仍是对外发布的 `@prismshadow/penguin-core/interfaces` 入口,
+ 既有导入路径全部照旧。
+- `version-info.ts`——`BuildInfo` / `HarnessInfo` / `VersionReport` 一族,它们描述的既不是 LLM
+ 也不是 Environment,改由包根导出。
+
+## 两条面,写明
+
+文档页([接口契约](/interfaces))现在写明每条边界上流动的是什么。**内容**只有 OmniMessage。与之
+并行的是刻意不做成消息形态的**控制面**——`signal`、`thinkingLevel`、`approve` 及其
+`ApprovalDecision`、以及 `streamGenerate` 的 `LLMOutcome` 返回值——每一项都附上它为何仍是参数。
+Environment 其余的非消息成员被命名为它的**管理面**:`listTools`、`toolPermission`、后台命令与
+子会话的各类列举、停止/插话入口与监听器挂载——它们根本不经过引擎,服务的是 Session 装配与宿主
+自己的 UI。
+
+## 通往子会话的一套词汇
+
+`SubagentHandle.run` 收 `prompt: string`,而同一个 handle 的 `steer` 收 `OmniMessage[]`;
+`sendToBackgroundSubagent` 收 `text: string`。两者现在都收 `Session.run` 所收的 OmniMessage 数组。
+
+每条消息的 `sender` 由调用方决定,这顺带修掉一处归属错误:从子会话面板对空闲子会话发起的一轮,
+此前被标记为 `parent_agent`,于是用户自己的话被记进子会话 Trace,仿佛是父 Agent 派发的。现在只有
+模型自己的派发标记 `parent_agent`,面板消息不带 sender——与面板的插话路径本来的做法一致。
+
+## 兼容性
+
+不涉及任何存量数据或存量配置,除上述 `sender` 修正外也不改变任何宿主可见行为。对 SDK 嵌入方有两处
+源码级不兼容:
+
+- 自带 `SubagentRunner` 的嵌入方需把 `run({ prompt })` 改为 `run({ messages })`——`messages` 是
+ 本轮输入,形状与 `Session.run` 相同(`[userText(prompt, "parent_agent")]` 精确复现旧行为)。
+ 自定义 `EnvironmentInterface.sendToBackgroundSubagent` 同理。
+- `BuildInfo`、`BuildRuntimeInfo`、`HarnessInfo`、`HarnessSource`、`VersionReport` 不再从
+ `@prismshadow/penguin-core/interfaces` 导出,改从 `@prismshadow/penguin-core` 导入。
+
+两处都不保留兼容层:它们都是编译期报错、一行即可修好;而让 `run` 同时接受两种形状,等于把这次改动
+消除的那份含糊重新引进来。
diff --git a/packages/cli/test/version.test.ts b/packages/cli/test/version.test.ts
index 10339dc3..2de405b1 100644
--- a/packages/cli/test/version.test.ts
+++ b/packages/cli/test/version.test.ts
@@ -10,7 +10,7 @@ import path from "node:path";
import { describe, expect, it } from "vitest";
import { Command } from "commander";
import { buildInfo } from "@prismshadow/penguin-core";
-import type { VersionReport } from "@prismshadow/penguin-core/interfaces";
+import type { VersionReport } from "@prismshadow/penguin-core";
import { versionReport } from "@prismshadow/penguin-server/version-report";
import { registerVersionCommand } from "../src/commands/version.js";
import { cli } from "../src/index.js";
diff --git a/packages/core/package.json b/packages/core/package.json
index 20c9305b..7e7e3c64 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -26,8 +26,8 @@
"import": "./dist/omnimessage/markers/index.js"
},
"./interfaces": {
- "types": "./dist/interfaces.d.ts",
- "import": "./dist/interfaces.js"
+ "types": "./dist/interfaces/index.d.ts",
+ "import": "./dist/interfaces/index.js"
},
"./model-catalog": {
"types": "./dist/state/model-catalog.d.ts",
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index 183110bf..21007cc5 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -67,7 +67,7 @@ import type {
ThinkingLevelName,
ToolDefinition,
VisionDescriberService,
-} from "./interfaces.js";
+} from "./interfaces/index.js";
import type { ModelEntry } from "./state/index.js";
/**
@@ -744,7 +744,7 @@ export class Agent {
metaSent = true;
return withOrigin(childSession.metaMessage, hop);
},
- async *run({ prompt, signal, approve, thinkingLevel: turnThinkingLevel }) {
+ async *run({ messages, signal, approve, thinkingLevel: turnThinkingLevel }) {
if (!metaSent) {
metaSent = true;
yield withOrigin(childSession.metaMessage, hop);
@@ -759,18 +759,18 @@ export class Agent {
// The engine writes a run's input to the CHILD's own Trace but never replays
// it to its consumer (a session's normal caller typed that input itself) —
// here the consumer is the PARENT, whose frontend has never seen the child's
- // prompt. Forward the input message itself (origin-tagged, ahead of the run's
- // output) so the live nested view shows the child's user side exactly like a
- // reloaded one (history expansion splices the child Trace, which carries this
- // same message). The parent engine drops origin messages from the parent
- // Trace, so replay never duplicates it. Later rounds (input_subagent
- // follow-up prompts) come through this same generator and are forwarded the
- // same way.
- // sender "parent_agent": in the child's Trace this user turn came from the
- // parent agent (run_subagent's prompt / input_subagent's follow-up), not a human.
- const input = userText(prompt, "parent_agent");
- yield withOrigin(input, hop);
- for await (const msg of childSession.run([input], {
+ // prompt. Forward the input messages themselves (origin-tagged, ahead of the
+ // run's output) so the live nested view shows the child's user side exactly
+ // like a reloaded one (history expansion splices the child Trace, which
+ // carries these same messages). The parent engine drops origin messages from
+ // the parent Trace, so replay never duplicates them. Later rounds
+ // (input_subagent follow-up prompts, a host panel's message) come through this
+ // same generator and are forwarded the same way.
+ // The caller owns each message's `sender` — "parent_agent" for the model's own
+ // dispatch, none for a human's message from a host panel — so the child's Trace
+ // records who actually spoke.
+ for (const input of messages) yield withOrigin(input, hop);
+ for await (const msg of childSession.run(messages, {
...(signal ? { signal } : {}),
...(childApprove ? { approve: childApprove } : {}),
...(turnThinkingLevel !== undefined ? { thinkingLevel: turnThinkingLevel } : {}),
diff --git a/packages/core/src/engine/context-engine.ts b/packages/core/src/engine/context-engine.ts
index b07d0fc6..99f328b9 100644
--- a/packages/core/src/engine/context-engine.ts
+++ b/packages/core/src/engine/context-engine.ts
@@ -79,7 +79,7 @@ import type {
LLMInterface,
LLMOutcome,
ThinkingLevelName,
-} from "../interfaces.js";
+} from "../interfaces/index.js";
/** Trace sink: `write` a complete/event/meta message; `rotate` starts a new file (compaction splits files). */
export interface TraceSink {
diff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.ts
index 0461b378..49d8418e 100644
--- a/packages/core/src/environment/environment.ts
+++ b/packages/core/src/environment/environment.ts
@@ -44,7 +44,7 @@ import type {
ToolDefinition,
ToolExecutionRequest,
ToolPermission,
-} from "../interfaces.js";
+} from "../interfaces/index.js";
import type { BuiltinTool, ToolResult } from "./tools/types.js";
import { BUILTIN_TOOL_FACTORIES } from "./tools/registry.js";
import { McpToolProvider } from "./mcp/provider.js";
@@ -286,24 +286,26 @@ export class Environment implements EnvironmentInterface {
* Host-initiated message to one child session — a user's input on the child, whatever its
* state: steering mid-run, a follow-up run when idle, a revival through the runner when the
* session is no longer live (see EnvironmentInterface.sendToBackgroundSubagent). Converges
- * on the same managed-session channel input_subagent uses; the message carries no sender
- * (human origin), unlike the model path's "parent_agent". `opts.thinkingLevel` pins only a
- * round this call starts — steering cannot change the round already in flight.
+ * on the same managed-session channel input_subagent uses, taking the same OmniMessage list;
+ * the caller's messages carry no sender (human origin), unlike the model path's
+ * "parent_agent" — and they reach both branches unchanged, so a steered round and a started
+ * round record the same author. `opts.thinkingLevel` pins only a round this call starts —
+ * steering cannot change the round already in flight.
*/
async sendToBackgroundSubagent(
childSessionId: string,
- text: string,
+ messages: OmniMessage[],
opts?: SubagentMessageOptions,
): Promise<SubagentMessageOutcome> {
const session = this.subagentSessions.bySessionId(childSessionId);
- if (!session) return this.resumeAndRun(childSessionId, text, opts);
+ if (!session) return this.resumeAndRun(childSessionId, messages, opts);
this.attachHostTap(session);
- if (session.steer([userText(text)])) return "steered";
+ if (session.steer(messages)) return "steered";
if (session.running) return "busy";
try {
// A host round is the user's own conversation with the child, not work the model
// dispatched: it must not fire a background completion notice at the parent.
- session.startRun(text, {
+ session.startRun(messages, {
...(opts?.thinkingLevel !== undefined ? { thinkingLevel: opts.thinkingLevel } : {}),
suppressDoneReport: true,
});
@@ -317,11 +319,11 @@ export class Environment implements EnvironmentInterface {
* The resume fallback of sendToBackgroundSubagent: revives the released child Session
* (resumeSession semantics via SubagentRunner.resume), re-manages it — live index,
* background registration (so the model can address it again by subagent_id), forwarding
- * tap, and the host approval fallback via track — and starts its next round with the text.
+ * tap, and the host approval fallback via track — and starts its next round with the messages.
*/
private async resumeAndRun(
childSessionId: string,
- text: string,
+ messages: OmniMessage[],
opts?: SubagentMessageOptions,
): Promise<SubagentMessageOutcome> {
const agentId = opts?.resume?.agentId;
@@ -345,7 +347,7 @@ export class Environment implements EnvironmentInterface {
this.attachHostTap(session);
try {
// Host-initiated like the started path: no completion notice at the parent.
- session.startRun(text, {
+ session.startRun(messages, {
...(opts?.thinkingLevel !== undefined ? { thinkingLevel: opts.thinkingLevel } : {}),
suppressDoneReport: true,
});
diff --git a/packages/core/src/environment/mcp/config.ts b/packages/core/src/environment/mcp/config.ts
index f79372eb..e7aba4a2 100644
--- a/packages/core/src/environment/mcp/config.ts
+++ b/packages/core/src/environment/mcp/config.ts
@@ -23,7 +23,7 @@
* names), so one typo in a hand-edited YAML cannot take the whole Agent down.
* Docs: /docs/tools § "MCP servers".
*/
-import type { MCPServerConfig, ToolPermission } from "../../interfaces.js";
+import type { MCPServerConfig, ToolPermission } from "../../interfaces/index.js";
/** Default per-server budget for connecting + initial handshake (ms). */
export const DEFAULT_MCP_CONNECT_TIMEOUT_MS = 10_000;
diff --git a/packages/core/src/environment/mcp/provider.ts b/packages/core/src/environment/mcp/provider.ts
index de6b26e5..df89e396 100644
--- a/packages/core/src/environment/mcp/provider.ts
+++ b/packages/core/src/environment/mcp/provider.ts
@@ -37,7 +37,7 @@ import { StdioClientTransport, getDefaultEnvironment } from "@modelcontextprotoc
import { partialToolCallOutput } from "../../omnimessage/index.js";
import type { McpServerConnectResult, OmniMessage } from "../../omnimessage/index.js";
import { VERSION } from "../../index.js";
-import type { MCPServerConfig, ToolDefinition, ToolPermission } from "../../interfaces.js";
+import type { MCPServerConfig, ToolDefinition, ToolPermission } from "../../interfaces/index.js";
import type { BuiltinTool, ToolResult } from "../tools/types.js";
import { resolveMCPServers, type ResolvedMCPServer } from "./config.js";
diff --git a/packages/core/src/environment/tools/command/session-manager.ts b/packages/core/src/environment/tools/command/session-manager.ts
index b820e5d8..1b67804f 100644
--- a/packages/core/src/environment/tools/command/session-manager.ts
+++ b/packages/core/src/environment/tools/command/session-manager.ts
@@ -11,7 +11,7 @@
*/
import { ManagedSession } from "./session.js";
import { BackgroundRegistry } from "../background/index.js";
-import type { ProxyEnvPolicy } from "../../../interfaces.js";
+import type { ProxyEnvPolicy } from "../../../interfaces/index.js";
/** Concurrent managed-session cap: evicts once exceeded (exited sessions first, otherwise LRU — killing a background process has bounded cost). */
const MAX_SESSIONS = 64;
diff --git a/packages/core/src/environment/tools/describe-image.ts b/packages/core/src/environment/tools/describe-image.ts
index ccfa5038..6efd08a4 100644
--- a/packages/core/src/environment/tools/describe-image.ts
+++ b/packages/core/src/environment/tools/describe-image.ts
@@ -18,7 +18,11 @@
*/
import { imageUrlMessage, partialToolCallOutput, userText } from "../../omnimessage/index.js";
import type { OmniMessage } from "../../omnimessage/index.js";
-import type { LLMOutcome, ToolDefinitionConfig, VisionDescriberService } from "../../interfaces.js";
+import type {
+ LLMOutcome,
+ ToolDefinitionConfig,
+ VisionDescriberService,
+} from "../../interfaces/index.js";
import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
import { formatSize, loadImage } from "./read-image.js";
diff --git a/packages/core/src/environment/tools/edit-file.ts b/packages/core/src/environment/tools/edit-file.ts
index 68c660b6..f490e7b3 100644
--- a/packages/core/src/environment/tools/edit-file.ts
+++ b/packages/core/src/environment/tools/edit-file.ts
@@ -25,7 +25,7 @@ import path from "node:path";
import { readFile, stat } from "node:fs/promises";
import { partialToolCallOutput } from "../../omnimessage/index.js";
import type { OmniMessage } from "../../omnimessage/index.js";
-import type { ToolDefinitionConfig } from "../../interfaces.js";
+import type { ToolDefinitionConfig } from "../../interfaces/index.js";
import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
import { atomicWriteFile } from "../../internal/atomic-write.js";
import { buildReplacementHunks, renderHunk } from "./diff.js";
diff --git a/packages/core/src/environment/tools/exec-command.ts b/packages/core/src/environment/tools/exec-command.ts
index af729daa..cefdea29 100644
--- a/packages/core/src/environment/tools/exec-command.ts
+++ b/packages/core/src/environment/tools/exec-command.ts
@@ -21,7 +21,7 @@
import path from "node:path";
import { partialToolCallOutput } from "../../omnimessage/index.js";
import type { OmniMessage } from "../../omnimessage/index.js";
-import type { EnvironmentServices, ToolDefinitionConfig } from "../../interfaces.js";
+import type { EnvironmentServices, ToolDefinitionConfig } from "../../interfaces/index.js";
import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
import { DEFAULT_EXEC_YIELD_MS, isStopSignal, resultForExit } from "./command/index.js";
import type { ManagedSession } from "./command/index.js";
diff --git a/packages/core/src/environment/tools/input-command.ts b/packages/core/src/environment/tools/input-command.ts
index 6d74d333..331b3764 100644
--- a/packages/core/src/environment/tools/input-command.ts
+++ b/packages/core/src/environment/tools/input-command.ts
@@ -23,7 +23,7 @@
*/
import { partialToolCallOutput } from "../../omnimessage/index.js";
import type { OmniMessage } from "../../omnimessage/index.js";
-import type { EnvironmentServices, ToolDefinitionConfig } from "../../interfaces.js";
+import type { EnvironmentServices, ToolDefinitionConfig } from "../../interfaces/index.js";
import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
import {
DEFAULT_EMPTY_POLL_YIELD_MS,
diff --git a/packages/core/src/environment/tools/input-subagent.ts b/packages/core/src/environment/tools/input-subagent.ts
index 18bacc6e..805ca5dd 100644
--- a/packages/core/src/environment/tools/input-subagent.ts
+++ b/packages/core/src/environment/tools/input-subagent.ts
@@ -24,7 +24,7 @@
*/
import { partialToolCallOutput, userText } from "../../omnimessage/index.js";
import type { OmniMessage } from "../../omnimessage/index.js";
-import type { EnvironmentServices, ToolDefinitionConfig } from "../../interfaces.js";
+import type { EnvironmentServices, ToolDefinitionConfig } from "../../interfaces/index.js";
import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
import {
DEFAULT_SUBAGENT_POLL_YIELD_MS,
@@ -133,7 +133,7 @@ export function createInputSubagentTool(
} else if (!session.running) {
// startRun expresses edge cases like already-disposed via throw, collapsed here into failed (the tool never throws outward).
try {
- session.startRun(prompt);
+ session.startRun([userText(prompt, "parent_agent")]);
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
yield delta(`[input_subagent error: ${message}]`);
diff --git a/packages/core/src/environment/tools/read-file.ts b/packages/core/src/environment/tools/read-file.ts
index 160bc7ed..e3132d5d 100644
--- a/packages/core/src/environment/tools/read-file.ts
+++ b/packages/core/src/environment/tools/read-file.ts
@@ -32,7 +32,7 @@ import path from "node:path";
import { open, realpath, stat } from "node:fs/promises";
import { partialToolCallOutput } from "../../omnimessage/index.js";
import type { OmniMessage } from "../../omnimessage/index.js";
-import type { ToolDefinitionConfig } from "../../interfaces.js";
+import type { ToolDefinitionConfig } from "../../interfaces/index.js";
import { missingPathHint } from "./path-hint.js";
import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
diff --git a/packages/core/src/environment/tools/read-image.ts b/packages/core/src/environment/tools/read-image.ts
index ef63504e..e4e5fda7 100644
--- a/packages/core/src/environment/tools/read-image.ts
+++ b/packages/core/src/environment/tools/read-image.ts
@@ -25,7 +25,7 @@ import path from "node:path";
import { readFile, stat } from "node:fs/promises";
import { partialToolCallOutput } from "../../omnimessage/index.js";
import type { OmniMessage } from "../../omnimessage/index.js";
-import type { ToolDefinitionConfig } from "../../interfaces.js";
+import type { ToolDefinitionConfig } from "../../interfaces/index.js";
import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
/** Tool name constant (used only within this tool module, never exposed to Environment). */
diff --git a/packages/core/src/environment/tools/registry.ts b/packages/core/src/environment/tools/registry.ts
index f9cef066..bbd1b421 100644
--- a/packages/core/src/environment/tools/registry.ts
+++ b/packages/core/src/environment/tools/registry.ts
@@ -11,7 +11,7 @@
* Docs: packages/docs/content/tools.{zh,en}.md (site path /docs/tools) documents every
* built-in tool and the approval flow — keep the page in sync when this table changes.
*/
-import type { EnvironmentServices, ToolDefinitionConfig } from "../../interfaces.js";
+import type { EnvironmentServices, ToolDefinitionConfig } from "../../interfaces/index.js";
import type { BuiltinTool } from "./types.js";
import { READ_FILE_NAME, createReadFileTool } from "./read-file.js";
import { EDIT_FILE_NAME, createEditFileTool } from "./edit-file.js";
diff --git a/packages/core/src/environment/tools/run-subagent.ts b/packages/core/src/environment/tools/run-subagent.ts
index d3a4e0c9..562dd466 100644
--- a/packages/core/src/environment/tools/run-subagent.ts
+++ b/packages/core/src/environment/tools/run-subagent.ts
@@ -27,14 +27,14 @@
* a nonexistent agent are expressed by the runner as a throw, and collapsed to failed.
* Docs: /docs/tools § "Subagents".
*/
-import { partialToolCallOutput } from "../../omnimessage/index.js";
+import { partialToolCallOutput, userText } from "../../omnimessage/index.js";
import type { OmniMessage } from "../../omnimessage/index.js";
-import { SUBAGENT_THINKING_LEVELS } from "../../interfaces.js";
+import { SUBAGENT_THINKING_LEVELS } from "../../interfaces/index.js";
import type {
EnvironmentServices,
ThinkingLevelName,
ToolDefinitionConfig,
-} from "../../interfaces.js";
+} from "../../interfaces/index.js";
import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
import {
DEFAULT_SUBAGENT_YIELD_MS,
@@ -178,7 +178,7 @@ export function createSubagentTool(
// not at the first input_subagent access.
const meta = session.takeMeta();
if (meta) yield meta;
- session.startRun(prompt);
+ session.startRun([userText(prompt, "parent_agent")]);
return {
stopReason: "completed",
note:
@@ -193,7 +193,7 @@ export function createSubagentTool(
let registered = false;
signal?.addEventListener("abort", onAbort, { once: true });
try {
- session.startRun(prompt);
+ session.startRun([userText(prompt, "parent_agent")]);
yield* collectWindow(session, {
yieldMs,
toolCallId,
diff --git a/packages/core/src/environment/tools/subagent/collect.ts b/packages/core/src/environment/tools/subagent/collect.ts
index 7f972aa4..712cf12f 100644
--- a/packages/core/src/environment/tools/subagent/collect.ts
+++ b/packages/core/src/environment/tools/subagent/collect.ts
@@ -11,7 +11,7 @@
*/
import { partialToolCallOutput } from "../../../omnimessage/index.js";
import type { OmniMessage } from "../../../omnimessage/index.js";
-import type { ApproveFn } from "../../../interfaces.js";
+import type { ApproveFn } from "../../../interfaces/index.js";
import type { ManagedSubagentSession } from "./session.js";
export async function* collectWindow(
diff --git a/packages/core/src/environment/tools/subagent/session-manager.ts b/packages/core/src/environment/tools/subagent/session-manager.ts
index e558563d..5c613937 100644
--- a/packages/core/src/environment/tools/subagent/session-manager.ts
+++ b/packages/core/src/environment/tools/subagent/session-manager.ts
@@ -9,7 +9,7 @@
* evicted; if there's still no room, the tool rejects spawning a new one.
* Docs: /docs/tools § "Background session caps".
*/
-import type { ApproveFn, BackgroundSubagentInfo } from "../../../interfaces.js";
+import type { ApproveFn, BackgroundSubagentInfo } from "../../../interfaces/index.js";
import { BackgroundRegistry } from "../background/index.js";
import type { ManagedSubagentSession } from "./session.js";
diff --git a/packages/core/src/environment/tools/subagent/session.ts b/packages/core/src/environment/tools/subagent/session.ts
index 4facb030..736b5c3f 100644
--- a/packages/core/src/environment/tools/subagent/session.ts
+++ b/packages/core/src/environment/tools/subagent/session.ts
@@ -35,7 +35,7 @@
*/
import type { OmniMessage } from "../../../omnimessage/index.js";
import type { ApprovalDecision, ToolCallPayload } from "../../../omnimessage/index.js";
-import type { ApproveFn, SubagentHandle, ThinkingLevelName } from "../../../interfaces.js";
+import type { ApproveFn, SubagentHandle, ThinkingLevelName } from "../../../interfaces/index.js";
import type { ToolResult } from "../types.js";
import { CappedTextBuffer, WakeSignal } from "../background/index.js";
@@ -149,14 +149,16 @@ export class ManagedSubagentSession {
/**
* Starts a new round of the task on the child Session (async pump, doesn't block the caller).
- * `opts.thinkingLevel` pins this round only (a host follow-up's per-turn picker);
+ * `messages` is the round's input in the same OmniMessage shape `steer` takes — the caller
+ * owns their `sender`, so a model dispatch and a human's panel message stay distinguishable
+ * in the child's Trace. `opts.thinkingLevel` pins this round only (a host follow-up's per-turn picker);
* `opts.suppressDoneReport` keeps the settle watcher quiet for this round — a HOST-initiated
* round is the user's own conversation with the child, not work the model dispatched, so the
* parent must not receive a completion notice for it. Throws if already disposed or still
* running (converted to an explanatory output by the caller).
*/
startRun(
- prompt: string,
+ messages: OmniMessage[],
opts?: { thinkingLevel?: ThinkingLevelName; suppressDoneReport?: boolean },
): void {
if (this.killed) throw new Error("subagent session disposed");
@@ -166,7 +168,7 @@ export class ManagedSubagentSession {
this.reportCurrentRun = opts?.suppressDoneReport !== true;
this.runCtrl = new AbortController();
this.notifyState();
- void this.pump(prompt, this.runCtrl, opts?.thinkingLevel);
+ void this.pump(messages, this.runCtrl, opts?.thinkingLevel);
}
/**
@@ -343,7 +345,7 @@ export class ManagedSubagentSession {
/** Drives one round of `handle.run`: buffers messages and text, settling the terminal state when it ends. */
private async pump(
- prompt: string,
+ messages: OmniMessage[],
runCtrl: AbortController,
thinkingLevel?: ThinkingLevelName,
): Promise<void> {
@@ -352,7 +354,7 @@ export class ManagedSubagentSession {
try {
// Either scope ends the round: the session-lifetime kill, or this run's own abort.
for await (const msg of this.handle.run({
- prompt,
+ messages,
signal: AbortSignal.any([this.abortCtrl.signal, runCtrl.signal]),
approve: this.childApprove,
...(thinkingLevel !== undefined ? { thinkingLevel } : {}),
diff --git a/packages/core/src/environment/tools/types.ts b/packages/core/src/environment/tools/types.ts
index 8a987553..b14a1229 100644
--- a/packages/core/src/environment/tools/types.ts
+++ b/packages/core/src/environment/tools/types.ts
@@ -8,7 +8,7 @@
* no changes needed to Environment.
*/
import type { OmniMessage, StopReason } from "../../omnimessage/index.js";
-import type { ApproveFn, ToolDefinitionConfig } from "../../interfaces.js";
+import type { ApproveFn, ToolDefinitionConfig } from "../../interfaces/index.js";
/**
* Tool execution context: runtime information needed to execute one tool call.
diff --git a/packages/core/src/environment/tools/write-file.ts b/packages/core/src/environment/tools/write-file.ts
index 60818381..63eeb2bd 100644
--- a/packages/core/src/environment/tools/write-file.ts
+++ b/packages/core/src/environment/tools/write-file.ts
@@ -29,7 +29,7 @@ import { atomicWriteFile, resolveWriteTarget } from "../../internal/atomic-write
import { buildLineDiffHunks, renderHunk } from "./diff.js";
import { partialToolCallOutput } from "../../omnimessage/index.js";
import type { OmniMessage } from "../../omnimessage/index.js";
-import type { ToolDefinitionConfig } from "../../interfaces.js";
+import type { ToolDefinitionConfig } from "../../interfaces/index.js";
import type { BuiltinTool, ToolExecutionContext, ToolResult } from "./types.js";
/** Tool name constant (used only within this tool module, never exposed to Environment). */
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index aeef65d1..ca9a43e8 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -15,12 +15,14 @@
* ```
*/
-import type { BuildInfo } from "./interfaces.js";
+import type { BuildInfo } from "./version-info.js";
import { resolveBuildInfo } from "./internal/build-info.js";
// Protocol and interface contracts (foundation)
export * from "./omnimessage/index.js";
-export * from "./interfaces.js";
+export * from "./interfaces/index.js";
+// Build/harness identity: not an interface contract, so it sits outside interfaces/ (see version-info.ts).
+export type * from "./version-info.js";
// Only the default server port leaves internal: the CLI / server default-port source of truth.
export { DEFAULT_SERVER_PORT } from "./internal/ports.js";
diff --git a/packages/core/src/interfaces.ts b/packages/core/src/interfaces/environment.ts
similarity index 59%
rename from packages/core/src/interfaces.ts
rename to packages/core/src/interfaces/environment.ts
index d808e5be..e22b0110 100644
--- a/packages/core/src/interfaces.ts
+++ b/packages/core/src/interfaces/environment.ts
@@ -1,38 +1,29 @@
/**
- * Internal SDK interface contracts: LLM, Environment.
+ * What the Environment side needs: the contract `context_engine` executes an approved tool
+ * call through, plus the configuration and runtime services an Environment is built with.
*
- * `context_engine` only handles OmniMessage; protocol conversion and concrete implementations
- * are each interface's own responsibility.
- * Human is not an "interface/class with methods" but the SDK's input/output boundary itself:
- * output is streamed by `Session.run()` as an async generator, and input is delivered via
- * `run`'s `RunOptions` — approvals are requested one at a time through the injected `approve`
- * callback, and interruption goes through `signal`. Hence no Human interface is defined here.
+ * Two planes live in this file and must not be confused (see the docs page):
+ * - the **message plane** — `executeTool`, which the engine drives: an OmniMessage tool call
+ * in, a stream of OmniMessage out, nothing else;
+ * - the **management plane** — the tool list, the permission lookup, the background command
+ * and subagent listings, their stop/steer entry points and the listener attachments. These
+ * never pass through `context_engine`: they serve a host's own UI (the Web App's process
+ * and subagents panels, an approval mode's permission check) and are ordinary method calls
+ * returning ordinary data.
*
- * These types form the foundational contract shared by all units; implementing units integrate
- * against them.
- *
- * Docs: packages/docs/content/interfaces.{zh,en}.md (site path /docs/interfaces) explains each
- * contract and its extension seams — keep the page in sync when changing signatures here.
+ * Docs: packages/docs/content/interfaces.{zh,en}.md (site path /docs/interfaces).
*/
-import type {
- ApprovalDecision,
- OmniMessage,
- StopReason,
- ToolCallPayload,
- ToolDefinition,
-} from "./omnimessage/types.js";
+import type { OmniMessage, ToolCallPayload, ToolDefinition } from "../omnimessage/types.js";
+import type { ApproveFn, ThinkingLevelName } from "./shared.js";
+import type { LLMInterface } from "./llm.js";
// Concrete classes, used only for EnvironmentServices type annotations (type-only import; no runtime dependency, no circular reference).
-import type { CommandSessionManager } from "./environment/tools/command/session-manager.js";
-import type { SubagentSessionManager } from "./environment/tools/subagent/session-manager.js";
-import type { ToolCallIdAllocator } from "./llm/tool-call-ids.js";
+import type { CommandSessionManager } from "../environment/tools/command/session-manager.js";
+import type { SubagentSessionManager } from "../environment/tools/subagent/session-manager.js";
// ---------------------------------------------------------------------------
-// Tool definitions and configuration
+// Tool configuration
// ---------------------------------------------------------------------------
-// ToolDefinition is defined in omnimessage/types.ts (the tool_list_ready event carries the full tool schema); re-exported here to keep the original import path.
-export type { ToolDefinition } from "./omnimessage/types.js";
-
/** Tool permission: read-only / read-write. */
export type ToolPermission = "r" | "rw";
@@ -89,181 +80,8 @@ export interface ToolConfig {
mcpServers: MCPServerConfig[];
}
-/**
- * Per-tool approval callback: the Human boundary gives allow/deny for each complete `tool_call`.
- * `context_engine` calls it once per tool call within a turn. Subagents forward the parent's
- * approval callback, so the child Agent **inherits the parent Agent's approval mode**.
- * The third decision, `"forbidden"`, is never a host's answer: `Session.run` wraps the
- * injected callback with the project sandbox command policy (see {@link CommandPolicyConfig}),
- * and a vetoed call answers `"forbidden"` without the wrapped callback being consulted.
- * Docs: /docs/interfaces § "ApproveFn".
- */
-export type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDecision>;
-
-/**
- * One command-policy deny rule — plain project-editable data: a name (identifies the rule
- * in the settings UI), a regex source tested against the whitespace-normalized command, an
- * optional free-text description, and a per-rule switch.
- * Docs: /docs/configuration § "Command policy".
- */
-export interface CommandPolicyRule {
- name: string;
- /** JavaScript regex source (no flags). */
- pattern: string;
- /** What the rule catches (free text, shown in the settings UI). */
- description?: string;
- /** Per-rule switch; absent = true. */
- enabled?: boolean;
-}
-
-/**
- * The project sandbox command policy (the `[command_policy]` block of
- * `.project_config.toml`, threaded into every Session the Agent creates). `Session.run`
- * wraps the injected approval callback with it, so a hit is denied without the human being
- * asked — under every approval mode. It is Project-owned security config, deliberately
- * outside Agent State so the Agent cannot rewrite it. The factory rule set is seeded into
- * new projects like model presets (copied at creation, never rewritten); an absent config
- * or an absent `rules` list means the factory set applies, and `enabled: false` switches
- * the whole policy off. An accident guardrail, not a security boundary — see
- * internal/command-policy.ts for what walks past it.
- * Docs: /docs/configuration § "Command policy".
- */
-export interface CommandPolicyConfig {
- /** Master switch; absent = true. */
- enabled?: boolean;
- /** The deny-rule list, evaluated in order; absent = the factory set (a stored empty list means no rules). */
- rules?: CommandPolicyRule[];
-}
-
-// ---------------------------------------------------------------------------
-// LLM interface
-// ---------------------------------------------------------------------------
-
-export type ThinkingLevelName = "none" | "low" | "medium" | "high" | "xhigh" | "max";
-
-/**
- * GenerativeModel initialization config.
- * Docs: /docs/interfaces § "GenerativeModelConfig".
- */
-export interface GenerativeModelConfig {
- modelId: string;
- apiKey?: string;
- baseUrl?: string;
- /**
- * AgentHub client protocol (`openai-chat` / `openai-responses` / `claude-4-8` /
- * `deepseek-v4` / …; the bare `openai` spelling is a deprecated alias of `openai-chat`). If
- * omitted, AgentHub infers it from `modelId`; custom-named models or third-party models
- * using an OpenAI protocol must specify it explicitly.
- */
- clientType?: string;
- tools: ToolDefinition[];
- /** Full system Prompt after placeholder substitution in the system_config.system_prompt template. */
- systemPrompt?: string;
- /**
- * Model context window (tokens, from the model entry). Used to clamp each request's
- * effective output cap so `input + max_tokens` stays inside the window (issue #218).
- * Unset (or implausibly small, see llm/context-limits.ts resolveContextWindow): the
- * clamp is disabled — a hard cap is never derived from an assumed window.
- */
- contextWindow?: number;
- /**
- * Output token cap per Request; non-positive (-1) means no explicit cap (omitted from the
- * request). With `contextWindow` set, a positive cap is a ceiling, not a constant: each
- * request sends `min(maxTokens, contextWindow − estimated input − safety margin)` (see
- * llm/context-limits.ts) so small-window models never fail provider validation.
- */
- maxTokens?: number;
- /**
- * Per-model fast mode (from the model entry's `fast_mode` annotation): when true, every
- * request opts into the provider's faster serving tier at premium pricing (AgentHub
- * UniConfig `fast_mode`). Off by default. Models without a fast tier reject the parameter
- * before any network I/O (AgentHub `UnsupportedParameterError`); `streamGenerate` reports
- * that as a permanent `failed` outcome so the engine surfaces it instead of retrying.
- */
- fastMode?: boolean;
- /** Construction-time default thinking level; a per-request `GenerativeModelParameters.thinkingLevel` overrides it for that request. */
- thinkingLevel?: ThinkingLevelName;
- /** LLM Request timeout (ms): from system_config.model.timeoutMs; <=0 disables it. Defaults to 120000. */
- requestTimeoutMs?: number;
- /**
- * tool_call_id uniqueness registry (Session-level). Pass the same instance when rebuilding a new
- * GenerativeModel on compaction so the uniqueness scope covers the whole Session; defaults to a fresh
- * one. See llm/tool-call-ids.ts.
- */
- toolCallIds?: ToolCallIdAllocator;
-}
-
-export interface GenerativeModelParameters {
- /** OmniMessage array for the input newly added this turn; implementations must merge it into a single UniMessage (multiple roles not accepted). */
- newMessages: OmniMessage[];
- signal?: AbortSignal;
- /**
- * Per-request thinking level override: applied to **this request only**; omitted falls back
- * to the construction-time default (`GenerativeModelConfig.thinkingLevel`). The thinking
- * level is a per-turn parameter, not a Session invariant.
- */
- thinkingLevel?: ThinkingLevelName;
-}
-
-/**
- * The terminal state of an LLM request, returned as the **return value** of the `streamGenerate`
- * async generator (not a yielded message). The status values share the same six-value protocol
- * as OmniMessage `stop_reason`:
- * - `completed`: finished normally (already produced `token_usage`);
- * - `timeout`: LLM timed out or lost connection, needs reconnect — retried by `context_engine`
- * within the same run;
- * - `malformed`: AgentHub response failed JSON parsing, needs reconnect — also retried by
- * `context_engine`;
- * - `aborted`: user-initiated interruption — stop and hand back to the user;
- * - `failed`: an error the retry classifier did not judge transient (params, etc.) — still
- * retried by `context_engine` within the same run (`errorMessage` provides the display text).
- * The classification stays honest — this is reported as `failed`, not relabelled a
- * timeout — while the *policy* retries it, because that classifier is an allowlist and a
- * gateway phrasing a transient fault its own way lands here;
- * - `auth`: the provider rejected the credentials (see `isAuthenticationError`) — the one
- * status that stops the run outright, since no retry can turn a rejected credential into
- * a working one; hosts also key on it to disable input until the model's API key is
- * updated (only the model reference is fixed at Session creation; credentials come from
- * the current Project config, so a key update lets the Session continue).
- * Docs: /docs/interfaces § "LLMOutcome semantics".
- */
-export interface LLMOutcome {
- status: StopReason;
- /**
- * Error detail (`describeError` text): present on `failed` / `auth`, and on `timeout` /
- * `malformed` when a concrete transport/provider error was caught (a plain idle timeout
- * has none). Carried onto the `request_end` event as `error_message` — one name across
- * the internal outcome and the wire — so observability (the Cost center's errors panel)
- * can show the real reason behind a retried request.
- */
- errorMessage?: string;
- /**
- * Marks a `failed` outcome as deterministic: a client-side rejection thrown before any
- * network I/O (currently AgentHub's `UnsupportedParameterError` for `fast_mode` on a model
- * without a fast tier), which the identical request can never retry into working. The
- * engine skips the reconnect ladder for it and aborts the run with `errorMessage` — the
- * same terminal handling as `auth`, but the fix is a config change (turn off fast mode for
- * the model), not a credential update, so it stays a `failed` and hosts don't gate input.
- */
- permanent?: boolean;
-}
-
-/**
- * A stateful LLM object attached to a Session.
- * `streamGenerate` yields streaming `partial_*` messages as an async generator, and appends the
- * corresponding complete `model_msg` once each fragment ends; Token usage is emitted as a
- * `token_usage` event_msg. **Never throws to `context_engine`**: any interruption/exception is
- * closed off in well-formed structure and returned normally, and **must** report the terminal
- * state via `LLMOutcome` — error handling happens entirely inside the LLM interface, and
- * `context_engine` only decides subsequent actions based on the outcome.
- * Docs: /docs/interfaces § "LLMInterface".
- */
-export interface LLMInterface {
- streamGenerate(parameters: GenerativeModelParameters): AsyncGenerator<OmniMessage, LLMOutcome>;
-}
-
// ---------------------------------------------------------------------------
-// Environment interface
+// Subagents, services and configuration
// ---------------------------------------------------------------------------
/**
@@ -291,8 +109,13 @@ export interface SubagentHandle {
* carry origin as well.
*/
run(input: {
- /** The task Prompt handed to the child Agent. */
- prompt: string;
+ /**
+ * The round's input, in the shape `Session.run` takes a Prompt in — the same OmniMessage
+ * list `steer` carries, so both ways into a child session speak one vocabulary. The
+ * caller owns the messages' `sender`: the model's dispatch is `parent_agent`, a human's
+ * message from a host panel carries none.
+ */
+ messages: OmniMessage[];
signal?: AbortSignal;
/** The parent Agent's approval callback; forwarded to the child Session to inherit the parent's approval mode. */
approve?: ApproveFn;
@@ -519,111 +342,6 @@ export interface BackgroundCommandInfo {
serviceUrl?: string;
}
-/**
- * Node and OS the build is executing on — the part of a build's identity that is a property
- * of the run rather than of the artifact.
- */
-export interface BuildRuntimeInfo {
- /** `process.versions.node`. */
- node: string;
- /** `process.platform`. */
- platform: string;
- /** `process.arch`. */
- arch: string;
-}
-
-/**
- * Identity of the running build: everything `penguin version --json` prints and everything
- * GET /api/version returns. Both render this object without adding facts of their own, so a
- * report gathered over HTTP and one gathered at a shell are the same report.
- *
- * Produced by core's `buildInfo()`. Which fields carry information depends on `channel`: a
- * release knows its date and the commit it was built from, a source build knows its git
- * position instead.
- */
-export interface BuildInfo {
- /** Dotted release number, from core's VERSION constant. Never null, never prefixed. */
- version: string;
- /**
- * The one-line human identity, and the whole of `penguin version`'s output: `v0.2.3` for a
- * release, and git's own description for a source build — `v0.2.3-14-g9e8f7d6-dirty` reads
- * as fourteen commits past v0.2.3, at 9e8f7d6, with uncommitted changes. Always begins
- * `v` followed by a digit, so any form reads as a version.
- *
- * Not necessarily `v{version}`: a tag description names the nearest reachable TAG, which
- * during release preparation is the previous one — `VERSION` is bumped in its own commit
- * and the new tag is created afterwards, so a build from that window truthfully reports
- * `v0.2.3-N-g…` while `version` already reads 0.2.4. Compare `version` when you mean the
- * release number and `describe` when you mean the position in history.
- */
- describe: string;
- /** `release` once the release workflow has stamped the build; `source` for every other build. */
- channel: "release" | "source";
- /** Release build date (UTC yyyy-mm-dd); null in a source build. */
- buildDate: string | null;
- /** Full commit sha this build came from; null when neither the stamp nor git supplied one. */
- commit: string | null;
- /** Branch checked out at build time; null for a release, and for a detached HEAD. */
- branch: string | null;
- /**
- * Whether tracked files differed from the commit. Null means the question does not apply
- * rather than "clean": a release stamps its constants into the tree before building, so
- * cleanliness is not a fact about release artifacts.
- */
- dirty: boolean | null;
- runtime: BuildRuntimeInfo;
-}
-
-/**
- * Where a hot update was pushed from, as the pusher recorded it. Provenance only: nothing
- * here is ever executed or resolved, and both fields are whatever the pushing client sent.
- */
-export interface HarnessSource {
- /** The pushing checkout's origin remote, or its directory name when it has no remote. */
- repo: string;
- /** `git describe --tags --dirty` of the pushing checkout, spelled as {@link BuildInfo.describe}. */
- revision: string;
-}
-
-/**
- * What this machine's HMR store has committed — the harness code a hot update put there,
- * which a restart resumes. A property of the data root rather than of the running process:
- * it answers "which harness was pushed here", not "which code is executing".
- *
- * That distinction matters because the two can differ. `penguin` runs the packaged CLI
- * while `penguin-hmr` runs the store's; a server whose committed version failed to restore
- * warns and falls back to its packaged platform. Null in {@link VersionReport} means
- * nothing was ever pushed to this root.
- */
-export interface HarnessInfo {
- /** Null for a version pushed by a client that recorded no provenance. */
- source: HarnessSource | null;
- /** When the version was committed to the store (ISO 8601); null if it predates the record. */
- pushedAt: string | null;
- /**
- * The committed artifacts' content-addressed pointers, relative to `<root>/hmr` — the
- * identity of the pushed code itself, independent of what the pusher claimed about it.
- */
- bundles: {
- platform: string | null;
- cli: string | null;
- web: string | null;
- };
-}
-
-/**
- * What `penguin version --json` prints and what GET /api/version returns: the running
- * build's identity, plus the harness this machine has in its HMR store.
- *
- * The two halves come from different places and neither can supply the other. {@link
- * BuildInfo} describes the artifact this process is executing and core resolves it alone;
- * `harness` describes the data root's store, so only a caller that knows which root is in
- * play can fill it.
- */
-export interface VersionReport extends BuildInfo {
- harness: HarnessInfo | null;
-}
-
/**
* One live subagent child session owned by the environment: the child Session id (the origin
* hop the frontend already correlates by), the registry handle when the session was promoted
@@ -696,11 +414,12 @@ export interface EnvironmentInterface {
* Host-initiated message to one child session, by child Session id: steering while the
* child runs, a follow-up run while it is idle, a revival (`opts.resume`) when the session
* is no longer live (see SubagentMessageOutcome/SubagentMessageOptions). The human and the
- * model (`input_subagent`) converge on the managed session's same channel. Optional.
+ * model (`input_subagent`) converge on the managed session's same channel, and both hand
+ * it the same thing — an OmniMessage list, whichever state the child is in. Optional.
*/
sendToBackgroundSubagent?(
childSessionId: string,
- text: string,
+ messages: OmniMessage[],
opts?: SubagentMessageOptions,
): Promise<SubagentMessageOutcome>;
/**
diff --git a/packages/core/src/interfaces/index.ts b/packages/core/src/interfaces/index.ts
new file mode 100644
index 00000000..a68c2d83
--- /dev/null
+++ b/packages/core/src/interfaces/index.ts
@@ -0,0 +1,24 @@
+/**
+ * Internal SDK interface contracts, split by which side of `context_engine` needs them:
+ * `./llm.ts` (the model request), `./environment.ts` (tool execution and the environment's
+ * management plane), and `./shared.ts` (the vocabulary both genuinely need). This barrel is
+ * the published `@prismshadow/penguin-core/interfaces` entry and re-exports all three, so
+ * every existing import path keeps working.
+ *
+ * `context_engine` only handles OmniMessage: the content crossing all three boundaries is
+ * OmniMessage and nothing else. What crosses alongside it is the **control plane** —
+ * `signal`, `thinkingLevel`, the `approve` callback, and the LLM's `LLMOutcome` return
+ * value — deliberately not message-shaped, because none of it is conversation content.
+ * Protocol conversion and concrete implementations are each interface's own responsibility.
+ *
+ * Human is not an "interface/class with methods" but the SDK's input/output boundary itself:
+ * output is streamed by `Session.run()` as an async generator, and input is delivered via
+ * `run`'s `RunOptions` — approvals are requested one at a time through the injected `approve`
+ * callback, and interruption goes through `signal`. Hence no Human interface is defined here.
+ *
+ * Docs: packages/docs/content/interfaces.{zh,en}.md (site path /docs/interfaces) explains each
+ * contract and its extension seams — keep the page in sync when changing signatures here.
+ */
+export type * from "./shared.js";
+export type * from "./llm.js";
+export * from "./environment.js";
diff --git a/packages/core/src/interfaces/llm.ts b/packages/core/src/interfaces/llm.ts
new file mode 100644
index 00000000..f455e35d
--- /dev/null
+++ b/packages/core/src/interfaces/llm.ts
@@ -0,0 +1,135 @@
+/**
+ * What the LLM side needs: the contract `context_engine` drives one model request through.
+ *
+ * The engine calls exactly one method here — `streamGenerate` — and reads exactly two things
+ * back: the yielded OmniMessage stream, and the generator's `LLMOutcome` return value (the
+ * request's terminal state; see the docs page's "control plane"). Protocol conversion to and
+ * from the provider is the implementation's own business.
+ *
+ * Docs: packages/docs/content/interfaces.{zh,en}.md (site path /docs/interfaces).
+ */
+import type { OmniMessage, StopReason, ToolDefinition } from "../omnimessage/types.js";
+import type { ThinkingLevelName } from "./shared.js";
+// Concrete class, used only as a type annotation (type-only import; no runtime dependency, no circular reference).
+import type { ToolCallIdAllocator } from "../llm/tool-call-ids.js";
+
+/**
+ * GenerativeModel initialization config.
+ * Docs: /docs/interfaces § "GenerativeModelConfig".
+ */
+export interface GenerativeModelConfig {
+ modelId: string;
+ apiKey?: string;
+ baseUrl?: string;
+ /**
+ * AgentHub client protocol (`openai-chat` / `openai-responses` / `claude-4-8` /
+ * `deepseek-v4` / …; the bare `openai` spelling is a deprecated alias of `openai-chat`). If
+ * omitted, AgentHub infers it from `modelId`; custom-named models or third-party models
+ * using an OpenAI protocol must specify it explicitly.
+ */
+ clientType?: string;
+ tools: ToolDefinition[];
+ /** Full system Prompt after placeholder substitution in the system_config.system_prompt template. */
+ systemPrompt?: string;
+ /**
+ * Model context window (tokens, from the model entry). Used to clamp each request's
+ * effective output cap so `input + max_tokens` stays inside the window (issue #218).
+ * Unset (or implausibly small, see llm/context-limits.ts resolveContextWindow): the
+ * clamp is disabled — a hard cap is never derived from an assumed window.
+ */
+ contextWindow?: number;
+ /**
+ * Output token cap per Request; non-positive (-1) means no explicit cap (omitted from the
+ * request). With `contextWindow` set, a positive cap is a ceiling, not a constant: each
+ * request sends `min(maxTokens, contextWindow − estimated input − safety margin)` (see
+ * llm/context-limits.ts) so small-window models never fail provider validation.
+ */
+ maxTokens?: number;
+ /**
+ * Per-model fast mode (from the model entry's `fast_mode` annotation): when true, every
+ * request opts into the provider's faster serving tier at premium pricing (AgentHub
+ * UniConfig `fast_mode`). Off by default. Models without a fast tier reject the parameter
+ * before any network I/O (AgentHub `UnsupportedParameterError`); `streamGenerate` reports
+ * that as a permanent `failed` outcome so the engine surfaces it instead of retrying.
+ */
+ fastMode?: boolean;
+ /** Construction-time default thinking level; a per-request `GenerativeModelParameters.thinkingLevel` overrides it for that request. */
+ thinkingLevel?: ThinkingLevelName;
+ /** LLM Request timeout (ms): from system_config.model.timeoutMs; <=0 disables it. Defaults to 120000. */
+ requestTimeoutMs?: number;
+ /**
+ * tool_call_id uniqueness registry (Session-level). Pass the same instance when rebuilding a new
+ * GenerativeModel on compaction so the uniqueness scope covers the whole Session; defaults to a fresh
+ * one. See llm/tool-call-ids.ts.
+ */
+ toolCallIds?: ToolCallIdAllocator;
+}
+
+export interface GenerativeModelParameters {
+ /** OmniMessage array for the input newly added this turn; implementations must merge it into a single UniMessage (multiple roles not accepted). */
+ newMessages: OmniMessage[];
+ signal?: AbortSignal;
+ /**
+ * Per-request thinking level override: applied to **this request only**; omitted falls back
+ * to the construction-time default (`GenerativeModelConfig.thinkingLevel`). The thinking
+ * level is a per-turn parameter, not a Session invariant.
+ */
+ thinkingLevel?: ThinkingLevelName;
+}
+
+/**
+ * The terminal state of an LLM request, returned as the **return value** of the `streamGenerate`
+ * async generator (not a yielded message). The status values share the same six-value protocol
+ * as OmniMessage `stop_reason`:
+ * - `completed`: finished normally (already produced `token_usage`);
+ * - `timeout`: LLM timed out or lost connection, needs reconnect — retried by `context_engine`
+ * within the same run;
+ * - `malformed`: AgentHub response failed JSON parsing, needs reconnect — also retried by
+ * `context_engine`;
+ * - `aborted`: user-initiated interruption — stop and hand back to the user;
+ * - `failed`: an error the retry classifier did not judge transient (params, etc.) — still
+ * retried by `context_engine` within the same run (`errorMessage` provides the display text).
+ * The classification stays honest — this is reported as `failed`, not relabelled a
+ * timeout — while the *policy* retries it, because that classifier is an allowlist and a
+ * gateway phrasing a transient fault its own way lands here;
+ * - `auth`: the provider rejected the credentials (see `isAuthenticationError`) — the one
+ * status that stops the run outright, since no retry can turn a rejected credential into
+ * a working one; hosts also key on it to disable input until the model's API key is
+ * updated (only the model reference is fixed at Session creation; credentials come from
+ * the current Project config, so a key update lets the Session continue).
+ * Docs: /docs/interfaces § "LLMOutcome semantics".
+ */
+export interface LLMOutcome {
+ status: StopReason;
+ /**
+ * Error detail (`describeError` text): present on `failed` / `auth`, and on `timeout` /
+ * `malformed` when a concrete transport/provider error was caught (a plain idle timeout
+ * has none). Carried onto the `request_end` event as `error_message` — one name across
+ * the internal outcome and the wire — so observability (the Cost center's errors panel)
+ * can show the real reason behind a retried request.
+ */
+ errorMessage?: string;
+ /**
+ * Marks a `failed` outcome as deterministic: a client-side rejection thrown before any
+ * network I/O (currently AgentHub's `UnsupportedParameterError` for `fast_mode` on a model
+ * without a fast tier), which the identical request can never retry into working. The
+ * engine skips the reconnect ladder for it and aborts the run with `errorMessage` — the
+ * same terminal handling as `auth`, but the fix is a config change (turn off fast mode for
+ * the model), not a credential update, so it stays a `failed` and hosts don't gate input.
+ */
+ permanent?: boolean;
+}
+
+/**
+ * A stateful LLM object attached to a Session.
+ * `streamGenerate` yields streaming `partial_*` messages as an async generator, and appends the
+ * corresponding complete `model_msg` once each fragment ends; Token usage is emitted as a
+ * `token_usage` event_msg. **Never throws to `context_engine`**: any interruption/exception is
+ * closed off in well-formed structure and returned normally, and **must** report the terminal
+ * state via `LLMOutcome` — error handling happens entirely inside the LLM interface, and
+ * `context_engine` only decides subsequent actions based on the outcome.
+ * Docs: /docs/interfaces § "LLMInterface".
+ */
+export interface LLMInterface {
+ streamGenerate(parameters: GenerativeModelParameters): AsyncGenerator<OmniMessage, LLMOutcome>;
+}
diff --git a/packages/core/src/interfaces/shared.ts b/packages/core/src/interfaces/shared.ts
new file mode 100644
index 00000000..32aa0883
--- /dev/null
+++ b/packages/core/src/interfaces/shared.ts
@@ -0,0 +1,64 @@
+/**
+ * Vocabulary both sides of the engine share.
+ *
+ * These are the types that resist the LLM/Environment split because both contracts genuinely
+ * need them: the tool schema Environment produces and the LLM consumes, the thinking level a
+ * Session sets and both a request and a spawned child carry, and the approval callback that
+ * touches all three boundaries (Human answers it, the engine calls it, Environment forwards
+ * it to derived sessions).
+ *
+ * Docs: packages/docs/content/interfaces.{zh,en}.md (site path /docs/interfaces).
+ */
+import type { ApprovalDecision, OmniMessage, ToolCallPayload } from "../omnimessage/types.js";
+
+// ToolDefinition is defined in omnimessage/types.ts (the tool_list_ready event carries the full tool schema); re-exported here to keep the original import path.
+export type { ToolDefinition } from "../omnimessage/types.js";
+
+/** Thinking level of one request. Shared: the LLM takes it per request and as a construction default, and a spawned child Session inherits or overrides it. */
+export type ThinkingLevelName = "none" | "low" | "medium" | "high" | "xhigh" | "max";
+
+/**
+ * Per-tool approval callback: the Human boundary gives allow/deny for each complete `tool_call`.
+ * `context_engine` calls it once per tool call within a turn. Subagents forward the parent's
+ * approval callback, so the child Agent **inherits the parent Agent's approval mode**.
+ * The third decision, `"forbidden"`, is never a host's answer: `Session.run` wraps the
+ * injected callback with the project sandbox command policy (see {@link CommandPolicyConfig}),
+ * and a vetoed call answers `"forbidden"` without the wrapped callback being consulted.
+ * Docs: /docs/interfaces § "ApproveFn".
+ */
+export type ApproveFn = (toolCall: OmniMessage<ToolCallPayload>) => Promise<ApprovalDecision>;
+
+/**
+ * One command-policy deny rule — plain project-editable data: a name (identifies the rule
+ * in the settings UI), a regex source tested against the whitespace-normalized command, an
+ * optional free-text description, and a per-rule switch.
+ * Docs: /docs/configuration § "Command policy".
+ */
+export interface CommandPolicyRule {
+ name: string;
+ /** JavaScript regex source (no flags). */
+ pattern: string;
+ /** What the rule catches (free text, shown in the settings UI). */
+ description?: string;
+ /** Per-rule switch; absent = true. */
+ enabled?: boolean;
+}
+
+/**
+ * The project sandbox command policy (the `[command_policy]` block of
+ * `.project_config.toml`, threaded into every Session the Agent creates). `Session.run`
+ * wraps the injected approval callback with it, so a hit is denied without the human being
+ * asked — under every approval mode. It is Project-owned security config, deliberately
+ * outside Agent State so the Agent cannot rewrite it. The factory rule set is seeded into
+ * new projects like model presets (copied at creation, never rewritten); an absent config
+ * or an absent `rules` list means the factory set applies, and `enabled: false` switches
+ * the whole policy off. An accident guardrail, not a security boundary — see
+ * internal/command-policy.ts for what walks past it.
+ * Docs: /docs/configuration § "Command policy".
+ */
+export interface CommandPolicyConfig {
+ /** Master switch; absent = true. */
+ enabled?: boolean;
+ /** The deny-rule list, evaluated in order; absent = the factory set (a stored empty list means no rules). */
+ rules?: CommandPolicyRule[];
+}
diff --git a/packages/core/src/internal/build-info.ts b/packages/core/src/internal/build-info.ts
index c1c33a1e..135bed81 100644
--- a/packages/core/src/internal/build-info.ts
+++ b/packages/core/src/internal/build-info.ts
@@ -20,7 +20,7 @@
*/
import path from "node:path";
import { fileURLToPath } from "node:url";
-import type { BuildInfo } from "../interfaces.js";
+import type { BuildInfo } from "../version-info.js";
import type { CheckoutFacts } from "./git-facts.js";
import { findCheckoutRoot, readCheckout } from "./git-facts.js";
diff --git a/packages/core/src/internal/command-policy.ts b/packages/core/src/internal/command-policy.ts
index 05961e32..848b5c38 100644
--- a/packages/core/src/internal/command-policy.ts
+++ b/packages/core/src/internal/command-policy.ts
@@ -42,7 +42,7 @@
* it and no substitute.
* Docs: /docs/configuration § "Command policy".
*/
-import type { ApproveFn, CommandPolicyConfig, CommandPolicyRule } from "../interfaces.js";
+import type { ApproveFn, CommandPolicyConfig, CommandPolicyRule } from "../interfaces/index.js";
import { effectiveCommandPolicyRules } from "../state/command-policy-defaults.js";
import { EXEC_COMMAND_NAME } from "../environment/tools/exec-command.js";
import { INPUT_COMMAND_NAME, INTERRUPT } from "../environment/tools/input-command.js";
diff --git a/packages/core/src/internal/session-title.ts b/packages/core/src/internal/session-title.ts
index c4c42cd4..8180310a 100644
--- a/packages/core/src/internal/session-title.ts
+++ b/packages/core/src/internal/session-title.ts
@@ -21,7 +21,7 @@ import type {
TokenCounts,
TokenUsagePayload,
} from "../omnimessage/index.js";
-import type { LLMInterface } from "../interfaces.js";
+import type { LLMInterface } from "../interfaces/index.js";
/** Cap on conversation text spliced into the title request (user/model each truncated separately, to control cost). */
const EXCERPT_MAX_CHARS = 2000;
diff --git a/packages/core/src/llm/generative-model.ts b/packages/core/src/llm/generative-model.ts
index f8d3992c..08d0cff5 100644
--- a/packages/core/src/llm/generative-model.ts
+++ b/packages/core/src/llm/generative-model.ts
@@ -71,7 +71,7 @@ import type {
LLMOutcome,
ThinkingLevelName,
ToolDefinition,
-} from "../interfaces.js";
+} from "../interfaces/index.js";
import { ToolCallIdAllocator, stripToolCallIdSuffix } from "./tool-call-ids.js";
import {
approximateMessagesTokens,
diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts
index cc39e99d..539635b4 100644
--- a/packages/core/src/session.ts
+++ b/packages/core/src/session.ts
@@ -47,7 +47,7 @@ import type {
EnvironmentInterface,
LLMInterface,
ToolPermission,
-} from "./interfaces.js";
+} from "./interfaces/index.js";
import { withCommandPolicy } from "./internal/command-policy.js";
import { generateTitleWithLLM } from "./internal/session-title.js";
import type { SessionTitleResult } from "./internal/session-title.js";
@@ -818,11 +818,11 @@ export class Session {
*/
async sendToBackgroundSubagent(
childSessionId: string,
- text: string,
+ messages: OmniMessage[],
opts?: SubagentMessageOptions,
): Promise<SubagentMessageOutcome> {
return (
- (await this.environment.sendToBackgroundSubagent?.(childSessionId, text, opts)) ?? "gone"
+ (await this.environment.sendToBackgroundSubagent?.(childSessionId, messages, opts)) ?? "gone"
);
}
diff --git a/packages/core/src/state/agent-state.ts b/packages/core/src/state/agent-state.ts
index af8dd20c..df54a8c8 100644
--- a/packages/core/src/state/agent-state.ts
+++ b/packages/core/src/state/agent-state.ts
@@ -19,7 +19,7 @@ import {
parseSkillFrontmatter,
type SkillMetadata,
} from "@prismshadow/penguin-skills";
-import type { ToolConfig, ToolDefinitionConfig } from "../interfaces.js";
+import type { ToolConfig, ToolDefinitionConfig } from "../interfaces/index.js";
import { atomicWriteFile } from "../internal/atomic-write.js";
import {
AGENT_ID_PLACEHOLDER,
diff --git a/packages/core/src/state/command-policy-defaults.ts b/packages/core/src/state/command-policy-defaults.ts
index c86b8453..de480dc3 100644
--- a/packages/core/src/state/command-policy-defaults.ts
+++ b/packages/core/src/state/command-policy-defaults.ts
@@ -12,7 +12,7 @@
* Descriptions are stored data (project-editable after seeding), so they are plain
* English like the rest of the config file.
*/
-import type { CommandPolicyConfig, CommandPolicyRule } from "../interfaces.js";
+import type { CommandPolicyConfig, CommandPolicyRule } from "../interfaces/index.js";
/**
* THE single "absent = factory set" fallback: every consumer of the rule list —
diff --git a/packages/core/src/state/default-config.ts b/packages/core/src/state/default-config.ts
index 8c735b57..f1420a8e 100644
--- a/packages/core/src/state/default-config.ts
+++ b/packages/core/src/state/default-config.ts
@@ -17,8 +17,12 @@
* such as \`<app_data_dir>\`, \`<agent_id>\`, \`<session_id>\` — these are **not substituted**;
* the model fills in the actual values from the Environment section itself.
*/
-import { SUBAGENT_THINKING_LEVELS } from "../interfaces.js";
-import type { MCPServerConfig, ThinkingLevelName, ToolDefinitionConfig } from "../interfaces.js";
+import { SUBAGENT_THINKING_LEVELS } from "../interfaces/index.js";
+import type {
+ MCPServerConfig,
+ ThinkingLevelName,
+ ToolDefinitionConfig,
+} from "../interfaces/index.js";
import type { CompactionMode } from "../omnimessage/types.js";
import { KERNEL_VERSION } from "./kernel-history.js";
diff --git a/packages/core/src/state/project-config.ts b/packages/core/src/state/project-config.ts
index f1a4d644..c568e165 100644
--- a/packages/core/src/state/project-config.ts
+++ b/packages/core/src/state/project-config.ts
@@ -27,7 +27,11 @@
import fs from "node:fs/promises";
import path from "node:path";
import { parse as parseToml, stringify as stringifyToml } from "smol-toml";
-import type { CommandPolicyConfig, CommandPolicyRule, ThinkingLevelName } from "../interfaces.js";
+import type {
+ CommandPolicyConfig,
+ CommandPolicyRule,
+ ThinkingLevelName,
+} from "../interfaces/index.js";
import { atomicWriteFile } from "../internal/atomic-write.js";
import { DEFAULT_COMMAND_POLICY_RULES } from "./command-policy-defaults.js";
import { canonicalClientType, presetModelEntries } from "./model-catalog.js";
diff --git a/packages/core/src/version-info.ts b/packages/core/src/version-info.ts
new file mode 100644
index 00000000..1947dabf
--- /dev/null
+++ b/packages/core/src/version-info.ts
@@ -0,0 +1,114 @@
+/**
+ * Identity of the running build and of this machine's harness store — what
+ * `penguin version --json` prints and what GET /api/version returns.
+ *
+ * Deliberately not part of the interface contracts: this says nothing about the LLM or the
+ * Environment, and no boundary of the agent loop carries it. Core's `buildInfo()` produces
+ * the {@link BuildInfo} half; only a caller that knows which data root is in play can fill
+ * the harness half.
+ */
+
+/**
+ * Node and OS the build is executing on — the part of a build's identity that is a property
+ * of the run rather than of the artifact.
+ */
+export interface BuildRuntimeInfo {
+ /** `process.versions.node`. */
+ node: string;
+ /** `process.platform`. */
+ platform: string;
+ /** `process.arch`. */
+ arch: string;
+}
+
+/**
+ * Identity of the running build: everything `penguin version --json` prints and everything
+ * GET /api/version returns. Both render this object without adding facts of their own, so a
+ * report gathered over HTTP and one gathered at a shell are the same report.
+ *
+ * Produced by core's `buildInfo()`. Which fields carry information depends on `channel`: a
+ * release knows its date and the commit it was built from, a source build knows its git
+ * position instead.
+ */
+export interface BuildInfo {
+ /** Dotted release number, from core's VERSION constant. Never null, never prefixed. */
+ version: string;
+ /**
+ * The one-line human identity, and the whole of `penguin version`'s output: `v0.2.3` for a
+ * release, and git's own description for a source build — `v0.2.3-14-g9e8f7d6-dirty` reads
+ * as fourteen commits past v0.2.3, at 9e8f7d6, with uncommitted changes. Always begins
+ * `v` followed by a digit, so any form reads as a version.
+ *
+ * Not necessarily `v{version}`: a tag description names the nearest reachable TAG, which
+ * during release preparation is the previous one — `VERSION` is bumped in its own commit
+ * and the new tag is created afterwards, so a build from that window truthfully reports
+ * `v0.2.3-N-g…` while `version` already reads 0.2.4. Compare `version` when you mean the
+ * release number and `describe` when you mean the position in history.
+ */
+ describe: string;
+ /** `release` once the release workflow has stamped the build; `source` for every other build. */
+ channel: "release" | "source";
+ /** Release build date (UTC yyyy-mm-dd); null in a source build. */
+ buildDate: string | null;
+ /** Full commit sha this build came from; null when neither the stamp nor git supplied one. */
+ commit: string | null;
+ /** Branch checked out at build time; null for a release, and for a detached HEAD. */
+ branch: string | null;
+ /**
+ * Whether tracked files differed from the commit. Null means the question does not apply
+ * rather than "clean": a release stamps its constants into the tree before building, so
+ * cleanliness is not a fact about release artifacts.
+ */
+ dirty: boolean | null;
+ runtime: BuildRuntimeInfo;
+}
+
+/**
+ * Where a hot update was pushed from, as the pusher recorded it. Provenance only: nothing
+ * here is ever executed or resolved, and both fields are whatever the pushing client sent.
+ */
+export interface HarnessSource {
+ /** The pushing checkout's origin remote, or its directory name when it has no remote. */
+ repo: string;
+ /** `git describe --tags --dirty` of the pushing checkout, spelled as {@link BuildInfo.describe}. */
+ revision: string;
+}
+
+/**
+ * What this machine's HMR store has committed — the harness code a hot update put there,
+ * which a restart resumes. A property of the data root rather than of the running process:
+ * it answers "which harness was pushed here", not "which code is executing".
+ *
+ * That distinction matters because the two can differ. `penguin` runs the packaged CLI
+ * while `penguin-hmr` runs the store's; a server whose committed version failed to restore
+ * warns and falls back to its packaged platform. Null in {@link VersionReport} means
+ * nothing was ever pushed to this root.
+ */
+export interface HarnessInfo {
+ /** Null for a version pushed by a client that recorded no provenance. */
+ source: HarnessSource | null;
+ /** When the version was committed to the store (ISO 8601); null if it predates the record. */
+ pushedAt: string | null;
+ /**
+ * The committed artifacts' content-addressed pointers, relative to `<root>/hmr` — the
+ * identity of the pushed code itself, independent of what the pusher claimed about it.
+ */
+ bundles: {
+ platform: string | null;
+ cli: string | null;
+ web: string | null;
+ };
+}
+
+/**
+ * What `penguin version --json` prints and what GET /api/version returns: the running
+ * build's identity, plus the harness this machine has in its HMR store.
+ *
+ * The two halves come from different places and neither can supply the other. {@link
+ * BuildInfo} describes the artifact this process is executing and core resolves it alone;
+ * `harness` describes the data root's store, so only a caller that knows which root is in
+ * play can fill it.
+ */
+export interface VersionReport extends BuildInfo {
+ harness: HarnessInfo | null;
+}
diff --git a/packages/core/test/agent.test.ts b/packages/core/test/agent.test.ts
index bccd750d..0df5d8dd 100644
--- a/packages/core/test/agent.test.ts
+++ b/packages/core/test/agent.test.ts
@@ -23,11 +23,16 @@ import {
loadProjectConfig,
saveProjectConfig,
setVaultEntry,
+ userText,
} from "../src/index.js";
import { metaMaxTokens } from "../src/agent.js";
import { mapThinkingLevel } from "../src/llm/index.js";
import { stubProviderKeys } from "./provider-keys.js";
-import type { EnvironmentConfig, EnvironmentServices, SubagentRunner } from "../src/interfaces.js";
+import type {
+ EnvironmentConfig,
+ EnvironmentServices,
+ SubagentRunner,
+} from "../src/interfaces/index.js";
// Captures the services buildRuntime hands to each Environment, so tests can drive the REAL
// subagent runner (the spawn closure in agent.ts). Spawning only constructs the child Session,
@@ -382,7 +387,7 @@ describe("run_subagent spawning follows the PARENT session (never the Project de
const handle = await runner.spawn(input);
let llm: { thinkingLevel?: string } | undefined;
try {
- const gen = handle.run({ prompt: "noop" });
+ const gen = handle.run({ messages: [userText("noop")] });
const first = await gen.next();
expect(first.done).toBe(false);
const msg = first.value!;
@@ -591,7 +596,7 @@ describe("run_subagent spawning follows the PARENT session (never the Project de
// own input, but this caller is the PARENT — the frontend renders the child conversation
// purely from these forwarded messages. (Regression: the panel showed no user messages
// live, while a reload — child-Trace expansion — did show them.)
- const gen = handle.run({ prompt: "count the TODO items" });
+ const gen = handle.run({ messages: [userText("count the TODO items")] });
const first = (await gen.next()).value as { type: string };
expect(first.type).toBe("session_meta");
// The input yield precedes childSession.run: pulling it never issues an LLM request.
diff --git a/packages/core/test/background-execution.test.ts b/packages/core/test/background-execution.test.ts
index c4238dcf..f090d9ed 100644
--- a/packages/core/test/background-execution.test.ts
+++ b/packages/core/test/background-execution.test.ts
@@ -47,7 +47,7 @@ import type {
SubagentRunner,
ToolConfig,
ToolDefinitionConfig,
-} from "../src/interfaces.js";
+} from "../src/interfaces/index.js";
import type { ToolExecutionContext } from "../src/environment/tools/types.js";
// ---------------------------------------------------------------------------
@@ -368,6 +368,13 @@ const HOP = "session-child-12ab34cd";
type RunInput = { prompt: string; signal?: AbortSignal; approve?: ApproveFn };
+/**
+ * Test fakes still talk in prompt strings; the contract now takes the OmniMessage list a
+ * Session's `run` takes, so the adapters below unwrap it once (see SubagentHandle.run).
+ */
+const promptOf = (messages: OmniMessage[]): string =>
+ messages.map((m) => (m.payload as { text?: string }).text ?? "").join("");
+
function runnerOf(run: (input: RunInput) => AsyncGenerator<OmniMessage>): SubagentRunner {
return {
async spawn() {
@@ -384,7 +391,7 @@ function runnerOf(run: (input: RunInput) => AsyncGenerator<OmniMessage>): Subage
payload: { session_id: HOP },
} as unknown as OmniMessage);
},
- run,
+ run: ({ messages, ...rest }) => run({ prompt: promptOf(messages), ...rest }),
dispose() {},
};
return handle;
@@ -503,7 +510,7 @@ describe("run_subagent run_in_background", () => {
// The user messages the idle child from the panel: their conversation, not dispatched
// work — the parent must not be notified when it settles.
const session = manager.get(id)!;
- session.startRun("user says hi", { suppressDoneReport: true });
+ session.startRun([userText("user says hi")], { suppressDoneReport: true });
await waitFor(() => gates.has("user says hi"));
gates.get("user says hi")!();
await waitFor(() => !session.running);
diff --git a/packages/core/test/command-policy.test.ts b/packages/core/test/command-policy.test.ts
index eca74100..2702483b 100644
--- a/packages/core/test/command-policy.test.ts
+++ b/packages/core/test/command-policy.test.ts
@@ -17,7 +17,7 @@ import type {
EnvironmentInterface,
LLMInterface,
LLMOutcome,
-} from "../src/interfaces.js";
+} from "../src/interfaces/index.js";
/** Shorthand: the matched rule name, or null. */
function hit(cmd: string, policy?: CommandPolicyConfig): string | null {
diff --git a/packages/core/test/compaction.test.ts b/packages/core/test/compaction.test.ts
index 1ae66e43..d8148561 100644
--- a/packages/core/test/compaction.test.ts
+++ b/packages/core/test/compaction.test.ts
@@ -53,7 +53,7 @@ import type {
GenerativeModelParameters,
LLMInterface,
LLMOutcome,
-} from "../src/interfaces.js";
+} from "../src/interfaces/index.js";
import { ContextEngine, SUMMARY_RETRY_GUIDANCE } from "../src/engine/context-engine.js";
import { Session } from "../src/session.js";
import type { CompactionSettings } from "../src/engine/context-engine.js";
diff --git a/packages/core/test/describe-image.test.ts b/packages/core/test/describe-image.test.ts
index 687cb9a5..f822492c 100644
--- a/packages/core/test/describe-image.test.ts
+++ b/packages/core/test/describe-image.test.ts
@@ -24,7 +24,7 @@ import type {
LLMOutcome,
ToolDefinitionConfig,
VisionDescriberService,
-} from "../src/interfaces.js";
+} from "../src/interfaces/index.js";
/** 1x1 transparent PNG (includes magic bytes, enough for mime sniffing). */
const PNG_1X1 = Buffer.from(
diff --git a/packages/core/test/engine.test.ts b/packages/core/test/engine.test.ts
index 10397523..9e875887 100644
--- a/packages/core/test/engine.test.ts
+++ b/packages/core/test/engine.test.ts
@@ -27,7 +27,11 @@ import {
withOrigin,
} from "../src/omnimessage/index.js";
import { BUILTIN_TOOL_FACTORIES } from "../src/environment/tools/registry.js";
-import type { GenerativeModelParameters, LLMInterface, LLMOutcome } from "../src/interfaces.js";
+import type {
+ GenerativeModelParameters,
+ LLMInterface,
+ LLMOutcome,
+} from "../src/interfaces/index.js";
import type { OmniMessage, TextPayload, ToolCallPayload } from "../src/omnimessage/index.js";
import { Environment } from "../src/environment/index.js";
import { Writer, readTrace } from "../src/trace/index.js";
@@ -35,7 +39,7 @@ import { ContextEngine, reconnectDelayMs } from "../src/engine/context-engine.js
import { goalRoundMessage } from "../src/goal/goal-prompts.js";
import { parseUserSteeringText } from "../src/omnimessage/markers/index.js";
import { imagesToScratchpadPaths } from "../src/internal/session-support.js";
-import type { ApproveFn, EnvironmentInterface, ToolPermission } from "../src/interfaces.js";
+import type { ApproveFn, EnvironmentInterface, ToolPermission } from "../src/interfaces/index.js";
/** A real 1x1 PNG data URL: the non-vision fold actually decodes and writes it to disk. */
const PNG_DATA_URL =
diff --git a/packages/core/test/environment.test.ts b/packages/core/test/environment.test.ts
index 3e845b61..6e61a989 100644
--- a/packages/core/test/environment.test.ts
+++ b/packages/core/test/environment.test.ts
@@ -12,7 +12,7 @@ import {
} from "../src/omnimessage/index.js";
import type { OmniMessage } from "../src/omnimessage/index.js";
import { BUILTIN_TOOL_FACTORIES } from "../src/environment/tools/registry.js";
-import type { ToolConfig, ToolDefinitionConfig } from "../src/interfaces.js";
+import type { ToolConfig, ToolDefinitionConfig } from "../src/interfaces/index.js";
/** Tool config for exec_command (permission/maxOutputLength adjustable). */
function execTool(overrides: Partial<ToolDefinitionConfig> = {}): ToolDefinitionConfig {
diff --git a/packages/core/test/exec-session.test.ts b/packages/core/test/exec-session.test.ts
index 005f5afd..47f009e8 100644
--- a/packages/core/test/exec-session.test.ts
+++ b/packages/core/test/exec-session.test.ts
@@ -8,7 +8,7 @@ import path from "node:path";
import { Environment, ManagedSession } from "../src/environment/index.js";
import { toolCall } from "../src/omnimessage/index.js";
import type { OmniMessage } from "../src/omnimessage/index.js";
-import type { ProxyEnvPolicy, ToolConfig, ToolDefinitionConfig } from "../src/interfaces.js";
+import type { ProxyEnvPolicy, ToolConfig, ToolDefinitionConfig } from "../src/interfaces/index.js";
function execTool(overrides: Partial<ToolDefinitionConfig> = {}): ToolDefinitionConfig {
return {
diff --git a/packages/core/test/file-tools.test.ts b/packages/core/test/file-tools.test.ts
index 8baa0bb3..8e2ee1a4 100644
--- a/packages/core/test/file-tools.test.ts
+++ b/packages/core/test/file-tools.test.ts
@@ -31,7 +31,7 @@ import { EDIT_FILE_NAME, createEditFileTool } from "../src/environment/tools/edi
import { WRITE_FILE_NAME, createWriteFileTool } from "../src/environment/tools/write-file.js";
import type { BuiltinTool, ToolResult } from "../src/environment/tools/types.js";
import type { OmniMessage } from "../src/omnimessage/index.js";
-import type { ToolDefinitionConfig } from "../src/interfaces.js";
+import type { ToolDefinitionConfig } from "../src/interfaces/index.js";
import { modelVisiblePath } from "../src/internal/model-visible-path.js";
function def(name: string, permission: "r" | "rw"): ToolDefinitionConfig {
diff --git a/packages/core/test/llm.test.ts b/packages/core/test/llm.test.ts
index 1b7ab5f7..e06d90c7 100644
--- a/packages/core/test/llm.test.ts
+++ b/packages/core/test/llm.test.ts
@@ -17,7 +17,7 @@ import {
UnsupportedParameterError,
} from "@prismshadow/agenthub";
import type { UniConfig, UniEvent, UniMessage, UsageMetadata } from "@prismshadow/agenthub";
-import type { LLMOutcome, ThinkingLevelName } from "../src/interfaces.js";
+import type { LLMOutcome, ThinkingLevelName } from "../src/interfaces/index.js";
import {
EventTranslator,
diff --git a/packages/core/test/mcp-tools.test.ts b/packages/core/test/mcp-tools.test.ts
index d4fc60f5..697a2560 100644
--- a/packages/core/test/mcp-tools.test.ts
+++ b/packages/core/test/mcp-tools.test.ts
@@ -14,7 +14,7 @@ import { McpToolProvider, renderCallToolResult } from "../src/environment/mcp/pr
import { Session } from "../src/session.js";
import { assistantText, toolCall, userText } from "../src/omnimessage/index.js";
import type { OmniMessage, SessionMetaPayload } from "../src/omnimessage/index.js";
-import type { LLMInterface, LLMOutcome, MCPServerConfig } from "../src/interfaces.js";
+import type { LLMInterface, LLMOutcome, MCPServerConfig } from "../src/interfaces/index.js";
const FIXTURE = fileURLToPath(new URL("./fixtures/mcp-stdio-server.mjs", import.meta.url));
diff --git a/packages/core/test/read-image.test.ts b/packages/core/test/read-image.test.ts
index 70b0fee5..3e6cb43e 100644
--- a/packages/core/test/read-image.test.ts
+++ b/packages/core/test/read-image.test.ts
@@ -16,7 +16,7 @@ import {
} from "../src/environment/tools/read-image.js";
import type { ToolResult } from "../src/environment/tools/types.js";
import type { OmniMessage } from "../src/omnimessage/index.js";
-import type { ToolDefinitionConfig } from "../src/interfaces.js";
+import type { ToolDefinitionConfig } from "../src/interfaces/index.js";
/** Full bytes of a 1x1 transparent PNG (including the magic number, enough for mime sniffing
* and data URL assertions). */
diff --git a/packages/core/test/replay.test.ts b/packages/core/test/replay.test.ts
index 10b2225e..035b7ef3 100644
--- a/packages/core/test/replay.test.ts
+++ b/packages/core/test/replay.test.ts
@@ -36,7 +36,7 @@ import { parseTraceLines, readTraceTolerant, resumeTrace } from "../src/trace/re
import { ContextEngine } from "../src/engine/context-engine.js";
import { Environment } from "../src/environment/index.js";
import { Writer, readTrace } from "../src/trace/index.js";
-import type { ApproveFn, LLMInterface } from "../src/interfaces.js";
+import type { ApproveFn, LLMInterface } from "../src/interfaces/index.js";
const usage = (total: number): TokenCounts => ({
cache_read: 0,
diff --git a/packages/core/test/service-url.test.ts b/packages/core/test/service-url.test.ts
index 7a76404a..c70c67bb 100644
--- a/packages/core/test/service-url.test.ts
+++ b/packages/core/test/service-url.test.ts
@@ -20,7 +20,7 @@ import {
parseWindowsProbe,
probeGroupListenPorts,
} from "../src/environment/tools/command/index.js";
-import type { ToolConfig } from "../src/interfaces.js";
+import type { ToolConfig } from "../src/interfaces/index.js";
const ESC = String.fromCharCode(0x1b);
diff --git a/packages/core/test/state.test.ts b/packages/core/test/state.test.ts
index 8730ab0e..caf42e53 100644
--- a/packages/core/test/state.test.ts
+++ b/packages/core/test/state.test.ts
@@ -60,7 +60,7 @@ import {
type ProjectConfig,
type SystemConfig,
} from "../src/state/index.js";
-import { SUBAGENT_THINKING_LEVELS } from "../src/interfaces.js";
+import { SUBAGENT_THINKING_LEVELS } from "../src/interfaces/index.js";
import { DEFAULT_COMMAND_POLICY_RULES } from "../src/state/command-policy-defaults.js";
import { sessionEnvironment } from "../src/internal/session-support.js";
diff --git a/packages/core/test/subagent.test.ts b/packages/core/test/subagent.test.ts
index 1e7db9d3..da765d6d 100644
--- a/packages/core/test/subagent.test.ts
+++ b/packages/core/test/subagent.test.ts
@@ -15,6 +15,7 @@ import {
assistantText,
partialText,
toolCall,
+ userText,
withOrigin,
} from "../src/omnimessage/index.js";
import { collectWindow } from "../src/environment/tools/subagent/collect.js";
@@ -25,7 +26,7 @@ import type {
SubagentHandle,
SubagentRunner,
ToolDefinitionConfig,
-} from "../src/interfaces.js";
+} from "../src/interfaces/index.js";
import type { ToolExecutionContext, ToolResult } from "../src/environment/tools/types.js";
const DEF: ToolDefinitionConfig = {
@@ -60,6 +61,19 @@ const pl = (m: OmniMessage): LoosePayload => m.payload as LoosePayload;
type RunInput = { prompt: string; signal?: AbortSignal; approve?: ApproveFn };
+/**
+ * Test fakes still talk in prompt strings; the contract now takes the OmniMessage list a
+ * Session's `run` takes, so the adapters below unwrap it once (see SubagentHandle.run).
+ */
+const promptOf = (messages: OmniMessage[]): string =>
+ messages.map((m) => (m.payload as { text?: string }).text ?? "").join("");
+
+/** Adapts a prompt-string fake to SubagentHandle.run's OmniMessage input. */
+const asHandleRun =
+ <T extends RunInput>(run: (input: T) => AsyncGenerator<OmniMessage>): SubagentHandle["run"] =>
+ ({ messages, ...rest }) =>
+ run({ prompt: promptOf(messages), ...rest } as unknown as T);
+
/** Builds a SubagentRunner from a run implementation (spawn arguments observed via a spy). */
function runnerOf(
run: (input: RunInput) => AsyncGenerator<OmniMessage>,
@@ -73,7 +87,11 @@ function runnerOf(
return {
async spawn(input) {
spawnSpy?.(input);
- const handle: SubagentHandle = { sessionId: HOP, run, dispose() {} };
+ const handle: SubagentHandle = {
+ sessionId: HOP,
+ run: ({ messages, ...rest }) => run({ prompt: promptOf(messages), ...rest }),
+ dispose() {},
+ };
return handle;
},
};
@@ -548,12 +566,12 @@ describe("run_subagent backgrounding + input_subagent", () => {
const session = new ManagedSubagentSession({
sessionId: `session-occupy-0000000${i}`,
// eslint-disable-next-line require-yield
- run: async function* ({ signal }: RunInput): AsyncGenerator<OmniMessage> {
+ run: async function* ({ signal }): AsyncGenerator<OmniMessage> {
await aborted(signal);
},
dispose() {},
});
- session.startRun("occupy");
+ session.startRun([userText("occupy")]);
manager.register(session);
}
const tool = createSubagentTool(DEF, services);
@@ -595,7 +613,7 @@ describe("run_subagent backgrounding + input_subagent", () => {
let emitSecond: (() => void) | null = null;
const session = new ManagedSubagentSession({
sessionId: HOP,
- run: async function* ({ signal }: RunInput): AsyncGenerator<OmniMessage> {
+ run: async function* ({ signal }): AsyncGenerator<OmniMessage> {
yield withOrigin(partialText("delta", "first"), HOP);
await new Promise<void>((resolve) => {
emitSecond = resolve;
@@ -606,7 +624,7 @@ describe("run_subagent backgrounding + input_subagent", () => {
dispose() {},
});
try {
- session.startRun("go");
+ session.startRun([userText("go")]);
const gen = collectWindow(session, { yieldMs: 5000, toolCallId: "call_race" });
const first = await gen.next(); // First: the forwarded "first" child session message
expect(first.done).toBe(false);
@@ -643,10 +661,13 @@ describe("subagent steering and per-run abort", () => {
function steerableChild(): {
runner: SubagentRunner;
prompts: string[];
+ /** Each round's raw input messages (the contract's own shape — sender included). */
+ inputs: OmniMessage[][];
steers: OmniMessage[][];
release: () => void;
} {
const prompts: string[] = [];
+ const inputs: OmniMessage[][] = [];
const steers: OmniMessage[][] = [];
let release!: () => void;
const gate = new Promise<void>((r) => (release = r));
@@ -654,7 +675,9 @@ describe("subagent steering and per-run abort", () => {
async spawn() {
const handle: SubagentHandle = {
sessionId: HOP,
- async *run({ prompt, signal }): AsyncGenerator<OmniMessage> {
+ async *run({ messages, signal }): AsyncGenerator<OmniMessage> {
+ const prompt = promptOf(messages);
+ inputs.push(messages);
prompts.push(prompt);
if (prompts.length === 1) {
yield withOrigin(partialText("delta", `start:${prompt} `), HOP);
@@ -679,7 +702,7 @@ describe("subagent steering and per-run abort", () => {
return handle;
},
};
- return { runner, prompts, steers, release: () => release() };
+ return { runner, prompts, inputs, steers, release: () => release() };
}
it("queues a mid-run prompt as a steering message with the parent_agent sender", async () => {
@@ -810,7 +833,7 @@ describe("subagent steering and per-run abort", () => {
]);
// Host steering while running: human sender (field absent), same handle channel.
- expect(await env.sendToBackgroundSubagent(HOP, "from the panel")).toBe("steered");
+ expect(await env.sendToBackgroundSubagent(HOP, [userText("from the panel")])).toBe("steered");
expect(child.steers).toHaveLength(1);
const payload = child.steers[0]![0]!.payload as { text?: string; sender?: string };
expect(payload.text).toBe("from the panel");
@@ -823,9 +846,15 @@ describe("subagent steering and per-run abort", () => {
// Host message on the idle child starts a follow-up round; its messages reach the
// frontend live through the tap the first host touch attached.
- expect(await env.sendToBackgroundSubagent(HOP, "round two")).toBe("started");
+ expect(await env.sendToBackgroundSubagent(HOP, [userText("round two")])).toBe("started");
await until(() => env.listBackgroundSubagents()[0]?.running === false);
expect(child.prompts).toEqual(["task", "round two"]);
+ // The caller's own message reaches the child unchanged: a human's panel round records
+ // no sender, exactly like the steering above — only the model's dispatch is
+ // "parent_agent" (round one, through run_subagent).
+ const [dispatched, panelRound] = child.inputs as [OmniMessage[], OmniMessage[]];
+ expect((dispatched[0]!.payload as { sender?: string }).sender).toBe("parent_agent");
+ expect((panelRound[0]!.payload as { sender?: string }).sender).toBeUndefined();
await until(() =>
forwarded.some((m) => {
const p = m.payload as { type?: string; text?: string };
@@ -833,7 +862,7 @@ describe("subagent steering and per-run abort", () => {
}),
);
- expect(await env.sendToBackgroundSubagent("session-unknown", "x")).toBe("gone");
+ expect(await env.sendToBackgroundSubagent("session-unknown", [userText("x")])).toBe("gone");
expect(env.abortBackgroundSubagentRun("session-unknown")).toBe(false);
} finally {
env.dispose();
@@ -900,11 +929,11 @@ describe("subagent steering and per-run abort", () => {
};
const runner: SubagentRunner = {
async spawn() {
- return { sessionId: HOP, run, dispose() {} };
+ return { sessionId: HOP, run: asHandleRun(run), dispose() {} };
},
async resume(input) {
resumes.push(input);
- return { sessionId: HOP, run, dispose() {} };
+ return { sessionId: HOP, run: asHandleRun(run), dispose() {} };
},
};
const env = new Environment({
@@ -930,9 +959,9 @@ describe("subagent steering and per-run abort", () => {
// Without the resume option the child is simply gone; with it, the session revives,
// re-registers (the model can address it again), and runs the message as a new round.
- expect(await env.sendToBackgroundSubagent(HOP, "wake up")).toBe("gone");
+ expect(await env.sendToBackgroundSubagent(HOP, [userText("wake up")])).toBe("gone");
expect(
- await env.sendToBackgroundSubagent(HOP, "wake up", {
+ await env.sendToBackgroundSubagent(HOP, [userText("wake up")], {
thinkingLevel: "high",
resume: { agentId: "owner_agent" },
}),
@@ -957,29 +986,33 @@ describe("subagent steering and per-run abort", () => {
};
const runner: SubagentRunner = {
async spawn() {
- return { sessionId: HOP, run, dispose() {} };
+ return { sessionId: HOP, run: asHandleRun(run), dispose() {} };
},
async resume(input) {
resumes.push(input);
- return { sessionId: HOP, run, dispose() {} };
+ return { sessionId: HOP, run: asHandleRun(run), dispose() {} };
},
};
const { services, manager } = makeServices(runner);
// Register the target, let its round settle, then fill the registry so capacity
// eviction RELEASES it (frees the slot — nothing is destroyed).
- const target = new ManagedSubagentSession({ sessionId: HOP, run, dispose() {} });
- target.startRun("first");
+ const target = new ManagedSubagentSession({
+ sessionId: HOP,
+ run: asHandleRun(run),
+ dispose() {},
+ });
+ target.startRun([userText("first")]);
await until(() => !target.running);
manager.track(target);
const id = manager.register(target);
for (let i = 0; i < 8; i += 1) {
const filler = new ManagedSubagentSession({
sessionId: `session-filler-0000000${i}`,
- run,
+ run: asHandleRun(run),
dispose() {},
});
- filler.startRun("filler");
+ filler.startRun([userText("filler")]);
await until(() => !filler.running);
manager.register(filler);
}
@@ -1005,7 +1038,7 @@ describe("subagent steering and per-run abort", () => {
const session = new ManagedSubagentSession({
sessionId: HOP,
// eslint-disable-next-line require-yield
- async *run({ signal }: RunInput): AsyncGenerator<OmniMessage> {
+ async *run({ signal }): AsyncGenerator<OmniMessage> {
await aborted(signal);
},
dispose() {},
@@ -1015,7 +1048,7 @@ describe("subagent steering and per-run abort", () => {
expect(manager.bySessionId(HOP)).toBe(session);
expect(manager.listLive()).toEqual([{ sessionId: HOP, subagentId: null, running: false }]);
- session.startRun("occupy");
+ session.startRun([userText("occupy")]);
const id = manager.register(session);
expect(manager.listLive()).toEqual([{ sessionId: HOP, subagentId: id, running: true }]);
diff --git a/packages/core/tsup.config.ts b/packages/core/tsup.config.ts
index 79e2ee27..db4c07ef 100644
--- a/packages/core/tsup.config.ts
+++ b/packages/core/tsup.config.ts
@@ -11,7 +11,7 @@ export default defineConfig({
// Message markers: their own entry so hosts (web/server/cli) can import the marker
// producers and parsers without pulling the rest of the SDK surface.
"src/omnimessage/markers/index.ts",
- "src/interfaces.ts",
+ "src/interfaces/index.ts",
"src/state/model-catalog.ts",
// Hot-update kernel: zero-dependency subpath so web can bundle it directly.
"src/kernel/index.ts",
diff --git a/packages/docs/content/architecture.en.md b/packages/docs/content/architecture.en.md
index c8f8dbaf..d37e264b 100644
--- a/packages/docs/content/architecture.en.md
+++ b/packages/docs/content/architecture.en.md
@@ -48,7 +48,7 @@ Item by item (design → owner → carrying file or module):
| --- | --- | --- |
| The OmniMessage protocol, message parsing and partial aggregation | SDK | `core/src/omnimessage/` — see [The OmniMessage Protocol](/omni-message) |
| The ReAct loop, carry-over, reconnect, compaction | SDK | `core/src/engine/context-engine.ts` — see [The Agent Loop](/agent-loop) |
-| The approval mechanism (one decision per tool_call) | SDK | `ApproveFn` (`core/src/interfaces.ts`); the concrete mode is injected by CLI/Server |
+| The approval mechanism (one decision per tool_call) | SDK | `ApproveFn` (`core/src/interfaces/shared.ts`); the concrete mode is injected by CLI/Server |
| Tool execution and centralized close-out | SDK | `core/src/environment/` — see [Tools & Approval](/tools) |
| Model access (provider protocol adaptation) | SDK → AgentHub | `core/src/llm/` + `@prismshadow/agenthub` — see [Models & Providers](/models) |
| Trace writing and Session-recovery logic | SDK | `core/src/trace/` (the records themselves live in the file layer) |
@@ -132,4 +132,4 @@ The Server keeps an additional SQLite index (users, authorization, usage stats)
- **Errors converge into messages**: the LLM and Environment never throw into the engine; results carry a six-value `stop_reason` (`completed | failed | aborted | timeout | malformed | auth`), and every LLM-side status except `auth` triggers an in-run reconnect (`failed / timeout / malformed`, up to 5 times with an exponential-with-ceiling backoff). `auth` is the one terminal class: a rejected credential cannot be retried into working. Retrying `failed` is a policy choice — the status itself is still reported as `failed`.
- **A thin model layer**: core defines only `LLMInterface`; provider adaptation lives entirely in AgentHub (`@prismshadow/agenthub`), which is what makes any OpenAI-compatible endpoint reachable. See [Models & Providers](/models).
-Source entry points: `packages/core/src/engine/context-engine.ts`, `packages/core/src/interfaces.ts`.
+Source entry points: `packages/core/src/engine/context-engine.ts`, `packages/core/src/interfaces/`.
diff --git a/packages/docs/content/architecture.zh.md b/packages/docs/content/architecture.zh.md
index 3a6b0eff..ea9a9733 100644
--- a/packages/docs/content/architecture.zh.md
+++ b/packages/docs/content/architecture.zh.md
@@ -48,7 +48,7 @@ PenguinHarness 是一个 pnpm monorepo,核心是 `@prismshadow/penguin-core`
| --- | --- | --- |
| OmniMessage 协议、消息解析与分片聚合 | SDK | `core/src/omnimessage/`,见 [OmniMessage 协议](/omni-message) |
| ReAct 循环、补发、重连、压缩 | SDK | `core/src/engine/context-engine.ts`,见 [Agent 运行循环](/agent-loop) |
-| 审批机制(每个 tool_call 一次决策) | SDK | `ApproveFn`(`core/src/interfaces.ts`);具体模式由 CLI/Server 注入 |
+| 审批机制(每个 tool_call 一次决策) | SDK | `ApproveFn`(`core/src/interfaces/shared.ts`);具体模式由 CLI/Server 注入 |
| 工具执行与统一收尾 | SDK | `core/src/environment/`,见[工具与审批](/tools) |
| 模型接入(Provider 协议适配) | SDK → AgentHub | `core/src/llm/` + `@prismshadow/agenthub`,见[模型与 Provider](/models) |
| Trace 写入与 Session 恢复逻辑 | SDK | `core/src/trace/`(记录本体在文件层) |
@@ -132,4 +132,4 @@ Server 额外维护一个 SQLite 索引库(用户、授权、用量统计),但
- **错误收敛为消息**:LLM 与 Environment 从不向引擎抛异常;结果携带六值 `stop_reason`(`completed | failed | aborted | timeout | malformed | auth`),除 `auth` 外的所有 LLM 侧状态都会触发引擎内重连(`failed / timeout / malformed`,至多 5 次、指数退避设上限)。`auth` 是唯一的终态类别:凭据被拒绝,重试不可能让它变对。重试 `failed` 是策略选择——该状态本身仍如实上报为 `failed`。
- **薄模型层**:core 只定义 `LLMInterface`,Provider 适配全部下沉到 AgentHub(`@prismshadow/agenthub`),因此支持任意 OpenAI 兼容端点,见[模型与 Provider](/models)。
-源码入口:`packages/core/src/engine/context-engine.ts`、`packages/core/src/interfaces.ts`。
+源码入口:`packages/core/src/engine/context-engine.ts`、`packages/core/src/interfaces/`。
diff --git a/packages/docs/content/interfaces.en.md b/packages/docs/content/interfaces.en.md
index cad9fe9c..8a7eb2e4 100644
--- a/packages/docs/content/interfaces.en.md
+++ b/packages/docs/content/interfaces.en.md
@@ -3,7 +3,7 @@ title: Core Interfaces
description: A top-down tour of the contracts — full LLMInterface and EnvironmentInterface signatures, inner types field by field, and every swappable seam.
---
-The context_engine depends on three interfaces: Human, LLM and Environment. All protocol conversion happens inside the implementations — the engine sees only [OmniMessage](/omni-message). This page goes top-down: the two big interface signatures and the Human boundary first, then each interface's inner types layer by layer. All types are exported by `@prismshadow/penguin-core`; source: `packages/core/src/interfaces.ts`.
+The context_engine depends on three interfaces: Human, LLM and Environment. All protocol conversion happens inside the implementations — the engine sees only [OmniMessage](/omni-message). This page goes top-down: the two big interface signatures and the Human boundary first, then each interface's inner types layer by layer. All types are exported by `@prismshadow/penguin-core`; source: `packages/core/src/interfaces/` — `llm.ts` (what the model side needs), `environment.ts` (what the Environment side needs), `shared.ts` (the vocabulary both genuinely need), and `index.ts`, the barrel behind the `@prismshadow/penguin-core/interfaces` subpath.
## Overview
@@ -28,6 +28,22 @@ The context_engine depends on three interfaces: Human, LLM and Environment. All
Two iron rules run through every interface: **never throw into the engine** (errors converge into messages/returns carrying a `stop_reason`), and **the streaming discipline** (`start → delta → stop`, complete message immediately after).
+### Message plane and control plane
+
+The **content** crossing all three boundaries is OmniMessage and nothing else — `session.run`'s input and streamed output, `streamGenerate`'s input array and yielded stream, `executeTool`'s approved call and its output stream, a subagent round's input and its forwarded messages, and every Trace write.
+
+What travels *alongside* it is the **control plane**, deliberately not message-shaped, because none of it is conversation content:
+
+| Control-plane item | Where | Why it is not a message |
+| --- | --- | --- |
+| `signal: AbortSignal` | `RunOptions`, `GenerativeModelParameters`, `ToolExecutionRequest` | An interruption that had to wait its turn in a message queue would not be an interruption. |
+| `thinkingLevel` | `RunOptions` → `GenerativeModelParameters` | A per-request parameter, like a timeout — it says how to run the request, not what to say. |
+| `approve` and its `ApprovalDecision` | `RunOptions`, `ToolExecutionRequest` | The callback takes an OmniMessage tool call; the answer is a three-value enum the engine turns into an `approval_decision` message the moment it has it. |
+| `LLMOutcome` | `streamGenerate`'s generator return value | The request's terminal state, which the engine's retry and reconnect policy branches on. A generator's return value is statically guaranteed to exist; "the last message yielded must be a `request_end`" would only ever be a runtime convention. The engine writes that `request_end` from it. |
+
+Everything else that is not OmniMessage is Environment's management plane, described below.
+
+
## LLMInterface
The complete model-side contract is a single method:
@@ -114,6 +130,11 @@ interface EnvironmentInterface {
}
```
+This interface carries two planes, and only the first one belongs to the agent loop:
+
+- the **message plane** — `executeTool`, the one method `context_engine` ever calls here: an OmniMessage tool call in, a stream of OmniMessage out;
+- the **management plane** — `listTools` and `toolPermission`, plus the optional background-command and subagent members (the listings, `killBackgroundCommand`, `sendToBackgroundSubagent`, `abortBackgroundSubagentRun`, the listener attachments and `dispose`). None of these pass through the engine: they serve Session assembly and a host's own UI — the Web App's process and subagents panels, an approval mode's permission lookup — and are ordinary method calls returning ordinary data. That is why they are not message-shaped, and why widening them would not make the engine's boundary any purer.
+
`executeTool` yields `partial_tool_call_output` fragments and ends with exactly one complete `tool_call_output`; `origin`-tagged nested messages (e.g. forwarded by `run_subagent`) pass through unchanged. The built-in Environment can keep truncated text in the Session scratchpad without exposing storage lifecycle hooks through this public interface. Its model-visible recovery path is a plain absolute path; on Windows it is written with forward slashes, which Node's fs APIs and the package's (Git) Bash tool shell both accept, so the same spelling works as a `read_file` argument and inside shell commands. Rendering is explicitly not this interface's concern — streaming rendering belongs to the CLI / Web front ends.
### ToolExecutionRequest and EnvironmentConfig
@@ -245,7 +266,7 @@ interface SubagentRunner {
interface SubagentHandle {
sessionId: string; // the child Session id: the origin hop; subagent_id derives from its tail
run(input: {
- prompt: string;
+ messages: OmniMessage[]; // the round's input, the shape Session.run takes a Prompt in
signal?: AbortSignal;
approve?: ApproveFn; // the parent's approval callback — forwarding is inheritance
}): AsyncGenerator<OmniMessage>;
@@ -255,6 +276,8 @@ interface SubagentHandle {
Spawning and running are separate, so the same child Session can accept a follow-up Prompt after a turn ends (a long-running Subagent, driven via `input_subagent`). Child Sessions run in the same Workspace with their own Trace; nesting depth is currently capped at 1.
+A round's input is an OmniMessage list — the same shape `steer` takes, and the same shape `EnvironmentInterface.sendToBackgroundSubagent` takes from a host — so both ways into a child session speak one vocabulary. The caller owns each message's `sender`: the model's own dispatch (`run_subagent`, `input_subagent`) stamps `parent_agent`, while a human's message from a host panel carries none, and the child's Trace records who actually spoke.
+
## VisionDescriberService
The image proxy-reading service for text-only models (needed by `describe_image`):
diff --git a/packages/docs/content/interfaces.zh.md b/packages/docs/content/interfaces.zh.md
index 30ecaff7..9189e6b5 100644
--- a/packages/docs/content/interfaces.zh.md
+++ b/packages/docs/content/interfaces.zh.md
@@ -3,7 +3,7 @@ title: 接口契约
description: 自顶向下的接口全览:LLMInterface 与 EnvironmentInterface 的完整签名、内层类型逐字段定义,以及每一处可替换的扩展点。
---
-context_engine 依赖三个接口:Human、LLM、Environment。协议转换全部发生在接口实现内部——引擎只见 [OmniMessage](/omni-message)。本页自顶向下:先给出两大接口的完整签名与 Human 边界,再逐层展开每个接口的内部类型。类型全部由 `@prismshadow/penguin-core` 导出,源码见 `packages/core/src/interfaces.ts`。
+context_engine 依赖三个接口:Human、LLM、Environment。协议转换全部发生在接口实现内部——引擎只见 [OmniMessage](/omni-message)。本页自顶向下:先给出两大接口的完整签名与 Human 边界,再逐层展开每个接口的内部类型。类型全部由 `@prismshadow/penguin-core` 导出,源码见 `packages/core/src/interfaces/`——`llm.ts`(模型侧所需)、`environment.ts`(Environment 侧所需)、`shared.ts`(两侧确实共用的词汇),以及 `index.ts`:`@prismshadow/penguin-core/interfaces` 子路径背后的 barrel。
## 总览
@@ -28,6 +28,22 @@ context_engine 依赖三个接口:Human、LLM、Environment。协议转换全
两条铁律贯穿所有接口:**从不向引擎抛异常**(错误收敛为带 `stop_reason` 的消息/返回值),**流式纪律**(`start → delta → stop`,随后立即产出完整消息)。
+### 消息面与控制面
+
+三条边界上流动的**内容**只有 OmniMessage,没有别的——`session.run` 的输入与流式输出、`streamGenerate` 的输入数组与产出流、`executeTool` 的已批准调用与其输出流、子会话一轮的输入与被转发的消息,以及每一次 Trace 写入。
+
+与之**并行**流动的是**控制面**,刻意不做成消息形态——它们都不是对话内容:
+
+| 控制面项 | 位置 | 为什么不是消息 |
+| --- | --- | --- |
+| `signal: AbortSignal` | `RunOptions`、`GenerativeModelParameters`、`ToolExecutionRequest` | 要在消息队列里排队才生效的打断,就不叫打断了。 |
+| `thinkingLevel` | `RunOptions` → `GenerativeModelParameters` | 逐次请求参数,与超时同类——它说的是这次请求怎么跑,而不是说了什么。 |
+| `approve` 及其 `ApprovalDecision` | `RunOptions`、`ToolExecutionRequest` | 回调的入参是 OmniMessage 工具调用;答案是三值枚举,引擎拿到后立刻转写为 `approval_decision` 消息。 |
+| `LLMOutcome` | `streamGenerate` generator 的返回值 | 本次 Request 的结束态,引擎的重试与重连策略全部据此分支。generator 的返回值由类型强制存在;「最后产出的消息必须是 `request_end`」只能是运行期约定。引擎正是据它写出那条 `request_end`。 |
+
+除此之外仍非 OmniMessage 的部分,属于 Environment 的管理面,见下。
+
+
## LLMInterface
模型侧的完整契约只有一个方法:
@@ -114,6 +130,11 @@ interface EnvironmentInterface {
}
```
+本接口承载两条面,只有第一条属于 Agent 循环:
+
+- **消息面**——`executeTool`,`context_engine` 在此唯一调用的方法:进去一条 OmniMessage 工具调用,出来一串 OmniMessage;
+- **管理面**——`listTools` 与 `toolPermission`,以及可选的后台命令与子会话成员(各类列举、`killBackgroundCommand`、`sendToBackgroundSubagent`、`abortBackgroundSubagentRun`、监听器挂载与 `dispose`)。它们都不经过引擎:服务于 Session 装配与宿主自己的 UI——Web App 的进程面板与子会话面板、审批模式的权限查询——是返回普通数据的普通方法调用。这正是它们不做成消息形态的原因,也是把它们消息化并不会让引擎边界更纯的原因。
+
`executeTool` 逐条产出 `partial_tool_call_output`,并以恰好一条完整 `tool_call_output` 收尾;带 `origin` 的嵌套消息(如 `run_subagent` 转发的子 Session 消息)原样透传。内置 Environment 可以把被截断文本保存在 Session scratchpad 中,无需在此公共接口暴露存储生命周期钩子。其模型可见 recovery 路径是普通绝对路径;Windows 上统一写成正斜杠——Node 的 fs API 与包内 (Git) Bash 工具 Shell 都接受这种写法,同一拼写既可直接作 `read_file` 参数、也可用于 Shell 命令。渲染不是本接口的职责——流式渲染由 CLI / Web 前端完成。
### ToolExecutionRequest 与 EnvironmentConfig
@@ -243,7 +264,7 @@ interface SubagentRunner {
interface SubagentHandle {
sessionId: string; // 子 Session id:消息 origin 的一跳,subagent_id 由其尾部派生
run(input: {
- prompt: string;
+ messages: OmniMessage[]; // 本轮输入,与 Session.run 接收 Prompt 的形状一致
signal?: AbortSignal;
approve?: ApproveFn; // 父级审批回调,转发即继承
}): AsyncGenerator<OmniMessage>;
@@ -253,6 +274,8 @@ interface SubagentHandle {
派生(spawn)与运行(run)分离,同一子 Session 可以在一轮结束后接受追加 Prompt 继续运行(长驻 Subagent,经 `input_subagent` 驱动)。子 Session 在同一 Workspace 中运行、拥有独立 Trace;嵌套深度当前限制为 1。
+一轮的输入是 OmniMessage 数组——与 `steer` 相同的形状,也与宿主调用 `EnvironmentInterface.sendToBackgroundSubagent` 时相同的形状——通往子会话的两条路径由此说同一套词汇。每条消息的 `sender` 由调用方决定:模型自己派发(`run_subagent`、`input_subagent`)标记 `parent_agent`,宿主面板上真人发出的消息不带 sender,子会话的 Trace 因此记录的是真正说话的人。
+
## VisionDescriberService
text-only 模型的图像代读服务(`describe_image` 所需):
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 1079509f..8010d785 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -19,12 +19,12 @@ import type {
ToolCallPayload,
} from "@prismshadow/penguin-core/omnimessage";
import type {
- HarnessInfo,
MCPServerConfig,
ThinkingLevelName,
ToolDefinitionConfig,
- VersionReport,
} from "@prismshadow/penguin-core/interfaces";
+// Build/harness identity is not an interface contract — it ships from the barrel (core's version-info.ts).
+import type { HarnessInfo, VersionReport } from "@prismshadow/penguin-core";
// ---------------------------------------------------------------------------
// General
diff --git a/packages/server/src/hmr/manifest.ts b/packages/server/src/hmr/manifest.ts
index a3b9e080..b21a4783 100644
--- a/packages/server/src/hmr/manifest.ts
+++ b/packages/server/src/hmr/manifest.ts
@@ -19,7 +19,7 @@
import fs from "node:fs";
import fsp from "node:fs/promises";
import path from "node:path";
-import type { HarnessInfo } from "@prismshadow/penguin-core/interfaces";
+import type { HarnessInfo } from "@prismshadow/penguin-core";
/**
* The committed on-disk record: a runtime restart resumes exactly this CODE (platform,
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index 4625474f..d7866c8f 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -1013,7 +1013,10 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
const outcome = await deps.manager.sendToSubagent(
row.sessionId,
pathParam(c, "childSessionId"),
- text,
+ // The HTTP boundary is where a host's payload becomes OmniMessage — no sender, because
+ // a human typed this (the model's own dispatch through input_subagent stamps
+ // "parent_agent" on its side).
+ [userText(text)],
thinkingLevel,
);
if (outcome === "gone") {
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index a8625099..1cc59e37 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -169,7 +169,7 @@ export interface RuntimeSession {
/** Host message to one child session — steering mid-run, a follow-up run when idle, a revival when released (core `Session.sendToBackgroundSubagent`). Optional. */
sendToBackgroundSubagent?(
childSessionId: string,
- text: string,
+ messages: OmniMessage[],
opts?: SubagentMessageOptions,
): Promise<SubagentMessageOutcome>;
/** Subscribes the host's session-lifetime fallback approval sink for child sessions (core `Session.setSubagentApprovalFallback`). Optional. */
@@ -547,7 +547,7 @@ export class SessionManager {
async sendToSubagent(
sessionId: string,
childSessionId: string,
- text: string,
+ messages: OmniMessage[],
thinkingLevel?: ThinkingLevelName,
): Promise<SubagentMessageOutcome> {
const entry = await this.ensureEntry(sessionId);
@@ -558,7 +558,7 @@ export class SessionManager {
? { agentId: childRow.agentId }
: undefined;
return (
- (await entry.session.sendToBackgroundSubagent?.(childSessionId, text, {
+ (await entry.session.sendToBackgroundSubagent?.(childSessionId, messages, {
...(thinkingLevel !== undefined ? { thinkingLevel } : {}),
...(resume ? { resume } : {}),
})) ?? "gone"
diff --git a/packages/server/src/version-report.ts b/packages/server/src/version-report.ts
index b55bb21c..e66577c8 100644
--- a/packages/server/src/version-report.ts
+++ b/packages/server/src/version-report.ts
@@ -12,7 +12,7 @@
* without pulling in a server: the module graph here is core plus a `node:fs` read.
*/
import { buildInfo } from "@prismshadow/penguin-core";
-import type { VersionReport } from "@prismshadow/penguin-core/interfaces";
+import type { VersionReport } from "@prismshadow/penguin-core";
import { readHarnessInfo } from "./hmr/manifest.js";
/**
diff --git a/packages/server/test/session-subagents.test.ts b/packages/server/test/session-subagents.test.ts
index b97fbad5..601a45fc 100644
--- a/packages/server/test/session-subagents.test.ts
+++ b/packages/server/test/session-subagents.test.ts
@@ -58,9 +58,11 @@ function subagentsFakeSession(
listBackgroundSubagents: () => children.map((c) => ({ ...c })),
sendToBackgroundSubagent: async (
childSessionId: string,
- text: string,
+ messages: OmniMessage[],
opts?: SubagentMessageOptions,
): Promise<SubagentMessageOutcome> => {
+ // The route turns the request's text into OmniMessage; the fake reads it back out.
+ const text = messages.map((m) => (m.payload as { text?: string }).text ?? "").join("");
sent.push({ childSessionId, text, ...(opts !== undefined ? { opts } : {}) });
const child = children.find((c) => c.sessionId === childSessionId);
if (!child) {