Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(agent-runtime): scaffold RuntimeIO transport ports (#16524)

Arvin Xub634eafcd887
diff --git a/packages/agent-runtime/src/index.ts b/packages/agent-runtime/src/index.ts
index 5c13cc9b02b..84851c57b11 100644
--- a/packages/agent-runtime/src/index.ts
+++ b/packages/agent-runtime/src/index.ts
@@ -2,5 +2,6 @@ export * from './agents';
export * from './audit';
export * from './core';
export * from './groupOrchestration';
+export * from './transport';
export * from './types';
export * from './utils';
diff --git a/packages/agent-runtime/src/transport/blob.ts b/packages/agent-runtime/src/transport/blob.ts
new file mode 100644
index 00000000000..f2e6d76e82d
--- /dev/null
+++ b/packages/agent-runtime/src/transport/blob.ts
@@ -0,0 +1,21 @@
+export interface BlobPersistResult {
+ fileId: string;
+ key: string;
+ url: string;
+}
+
+export interface BlobRef {
+ fileId?: string | null;
+ id?: string | null;
+ url?: string | null;
+}
+
+/**
+ * Persists model-generated blobs (base64 images) and resolves stored file
+ * references to externally accessible URLs. Server adapter wraps `FileService`
+ * (S3); the client adapter can be a no-op / browser-backed implementation.
+ */
+export interface BlobStore {
+ persistBase64: (base64Data: string, pathname: string) => Promise<BlobPersistResult>;
+ resolveUrl: (ref: BlobRef) => Promise<string>;
+}
diff --git a/packages/agent-runtime/src/transport/context.ts b/packages/agent-runtime/src/transport/context.ts
new file mode 100644
index 00000000000..7214c1266a8
--- /dev/null
+++ b/packages/agent-runtime/src/transport/context.ts
@@ -0,0 +1,33 @@
+import type { OpenAIChatMessage, UIChatMessage } from '@lobechat/types';
+
+/**
+ * Inputs for building the final prompt sent to the model.
+ *
+ * NOTE (scaffolding): only the always-required trio is pinned. The many context
+ * sources the server engine consumes (systemRole, knowledge, tool manifests,
+ * agentDocuments, persona/onboarding, topic references, capabilities…) are
+ * resolved/bound by the adapter and firm when `call_llm` / `compress_context`
+ * (Tier C) migrate onto the port.
+ */
+export interface ContextBuildInput {
+ [key: string]: unknown;
+ messages: UIChatMessage[];
+ model: string;
+ provider: string;
+}
+
+export interface ContextBuildOutput {
+ messages: OpenAIChatMessage[];
+}
+
+/**
+ * Builds the processed message list fed to the model (system role injection,
+ * knowledge, skills, history shaping, reference resolution). Server adapter
+ * wraps `serverMessagesEngine`; the client adapter wraps its own context build.
+ *
+ * Heavy outputs MUST stay out of the serialized agent state (Redis 10MB limit)
+ * β€” the adapter routes large payloads to the trace sink, as today.
+ */
+export interface ContextBuilder {
+ build: (input: ContextBuildInput) => Promise<ContextBuildOutput>;
+}
diff --git a/packages/agent-runtime/src/transport/host.ts b/packages/agent-runtime/src/transport/host.ts
new file mode 100644
index 00000000000..36fe4f8bda1
--- /dev/null
+++ b/packages/agent-runtime/src/transport/host.ts
@@ -0,0 +1,42 @@
+import type { BlobStore } from './blob';
+import type { ContextBuilder } from './context';
+import type { LifecycleSink } from './lifecycle';
+import type { LLMTransport } from './llm';
+import type { MessageTransport } from './message';
+import type { StreamSink } from './stream';
+import type { SubAgentTransport } from './subAgent';
+import type { ToolTransport } from './tool';
+
+/**
+ * The injectable IO surface for the runtime executors.
+ *
+ * `messages` + `stream` are required (every executor touches them). The rest
+ * are optional because only some executors need them β€” an executor that needs a
+ * transport asserts its presence at use site:
+ *
+ * - `tools` β†’ call_tool, call_tools_batch
+ * - `subAgent` β†’ exec_sub_agent, exec_sub_agents
+ * - `llm` β†’ call_llm, compress_context
+ * - `context` β†’ call_llm, compress_context
+ * - `blob` β†’ call_llm
+ */
+export interface RuntimeTransports {
+ blob?: BlobStore;
+ context?: ContextBuilder;
+ llm?: LLMTransport;
+ messages: MessageTransport;
+ stream: StreamSink;
+ subAgent?: SubAgentTransport;
+ tools?: ToolTransport;
+}
+
+/**
+ * Single argument to the (future) package-hosted executor factories. The server
+ * builds this once per operation β€” wiring its adapters + lifecycle dispatcher β€”
+ * and the package owns the executor logic. This is the seam that lets the same
+ * executors run on server and client (LOBE-10949 end-state).
+ */
+export interface AgentRuntimeHost {
+ lifecycle?: LifecycleSink;
+ transports: RuntimeTransports;
+}
diff --git a/packages/agent-runtime/src/transport/index.ts b/packages/agent-runtime/src/transport/index.ts
new file mode 100644
index 00000000000..44d21566178
--- /dev/null
+++ b/packages/agent-runtime/src/transport/index.ts
@@ -0,0 +1,9 @@
+export * from './blob';
+export * from './context';
+export * from './host';
+export * from './lifecycle';
+export * from './llm';
+export * from './message';
+export * from './stream';
+export * from './subAgent';
+export * from './tool';
diff --git a/packages/agent-runtime/src/transport/lifecycle.ts b/packages/agent-runtime/src/transport/lifecycle.ts
new file mode 100644
index 00000000000..14cd751d08f
--- /dev/null
+++ b/packages/agent-runtime/src/transport/lifecycle.ts
@@ -0,0 +1,26 @@
+import type { AgentHookType, AnyHookEvent, ToolCallHookEvent } from '../types';
+
+export interface ToolCallMockResult {
+ content: string;
+ isMocked: true;
+}
+
+/**
+ * Lifecycle dispatch port. Decouples executors from the server-side
+ * `HookDispatcher`: an executor calls `lifecycle.dispatch(...)` at its key
+ * moments and the host wires it to whatever observes them (server webhook
+ * dispatcher, client no-op, eval harness).
+ *
+ * This is the coarse-grained surface mirroring the existing 16 hook types.
+ * Per-stage lifecycle nodes (prepare β†’ request β†’ stream β†’ persist β†’ finalize)
+ * are layered on top of this when each executor migrates, not redefined here.
+ *
+ * `dispatchBeforeToolCall` is the one interception point (returns a mock result
+ * to skip real execution); everything else is fire-and-forget observation.
+ */
+export interface LifecycleSink {
+ dispatch: (type: AgentHookType, event: AnyHookEvent) => Promise<void>;
+ dispatchBeforeToolCall: (
+ event: Omit<ToolCallHookEvent, 'mock' | 'operationId'>,
+ ) => Promise<ToolCallMockResult | null>;
+}
diff --git a/packages/agent-runtime/src/transport/llm.ts b/packages/agent-runtime/src/transport/llm.ts
new file mode 100644
index 00000000000..1df4285677f
--- /dev/null
+++ b/packages/agent-runtime/src/transport/llm.ts
@@ -0,0 +1,37 @@
+import type { CallLLMPayload } from '../types';
+
+/**
+ * Aggregated result of one model turn.
+ *
+ * NOTE (scaffolding): only the always-present fields are pinned. usage / cost /
+ * toolCalls / images / finishReason firm when `call_llm` (Tier C) migrates onto
+ * the port β€” that migration is what actually dissolves the 1700-line executor.
+ */
+export interface LLMStreamResult {
+ [key: string]: unknown;
+ content: string;
+ reasoning?: string;
+}
+
+export interface LLMStreamHandlers {
+ onChunk?: (chunk: unknown) => void;
+ onError?: (error: unknown) => void;
+ onFinish?: (result: LLMStreamResult) => void;
+}
+
+/**
+ * Streams a model completion. Server adapter wraps `initModelRuntimeFromDB` +
+ * `ModelRuntime.chat` + `consumeStreamUntilDone`; the client adapter wraps
+ * `chatService.createAssistantMessageStream`.
+ *
+ * Generalizes today's primitive `Agent.modelRuntime` hook. The adapter maps the
+ * runtime payload to its provider format, so the package stays free of
+ * `@lobechat/model-runtime`.
+ */
+export interface LLMTransport {
+ stream: (
+ payload: CallLLMPayload,
+ handlers?: LLMStreamHandlers,
+ signal?: AbortSignal,
+ ) => Promise<LLMStreamResult>;
+}
diff --git a/packages/agent-runtime/src/transport/message.ts b/packages/agent-runtime/src/transport/message.ts
new file mode 100644
index 00000000000..bf69f497df3
--- /dev/null
+++ b/packages/agent-runtime/src/transport/message.ts
@@ -0,0 +1,47 @@
+import type { CreateMessageParams, UIChatMessage, UpdateMessageParams } from '@lobechat/types';
+
+/** Minimal reference an executor needs back after creating a message. */
+export interface RuntimeMessageRef {
+ id: string;
+}
+
+export interface QueryMessagesInput {
+ agentId?: string;
+ current?: number;
+ groupId?: string;
+ pageSize?: number;
+ sessionId?: string;
+ threadId?: string;
+ topicId?: string;
+}
+
+export interface UpdateToolMessageInput {
+ content?: string;
+ metadata?: Record<string, any>;
+ pluginError?: unknown;
+ pluginState?: Record<string, any>;
+}
+
+/**
+ * Persists and reads conversation messages for the runtime.
+ *
+ * The runtime never touches a database directly β€” it goes through this port.
+ * Server adapter wraps `MessageModel` (DB); the client adapter wraps the
+ * optimistic chat store. Methods are async and MUST NOT assume a transaction:
+ * the client persists optimistically (in-memory first, DB later), the server
+ * writes through.
+ *
+ * Reads return the shared {@link UIChatMessage} shape; creates return only the
+ * id the caller needs to anchor follow-up writes.
+ */
+export interface MessageTransport {
+ createAssistantMessage: (params: CreateMessageParams) => Promise<RuntimeMessageRef>;
+ createToolMessage: (params: CreateMessageParams) => Promise<RuntimeMessageRef>;
+ deleteMessage: (id: string) => Promise<void>;
+ /** Existence / parent preflight; returns the id when present. */
+ findById: (id: string) => Promise<RuntimeMessageRef | undefined>;
+ query: (params?: QueryMessagesInput) => Promise<UIChatMessage[]>;
+ update: (id: string, params: Partial<UpdateMessageParams>) => Promise<void>;
+ updatePluginState: (id: string, state: Record<string, any>) => Promise<void>;
+ updateToolMessage: (id: string, params: UpdateToolMessageInput) => Promise<void>;
+}
diff --git a/packages/agent-runtime/src/transport/stream.ts b/packages/agent-runtime/src/transport/stream.ts
new file mode 100644
index 00000000000..b675a878511
--- /dev/null
+++ b/packages/agent-runtime/src/transport/stream.ts
@@ -0,0 +1,29 @@
+import type { AgentEvent } from '../types';
+
+/**
+ * Incremental streaming delta pushed to the consumer during a step.
+ *
+ * NOTE (scaffolding): the exact delta union (text / reasoning / tool-call /
+ * grounding / image) is server-defined today (`StreamChunkData`). It is
+ * intentionally left open here and will be firmed when the first streaming
+ * executor (call_llm, Tier C) migrates onto the port.
+ */
+export interface StreamChunkInput {
+ [key: string]: unknown;
+ reasoning?: string;
+ stepIndex: number;
+ text?: string;
+}
+
+/**
+ * Egress for live streaming. Server adapter forwards to the Redis stream
+ * (`IStreamEventManager`); the client adapter dispatches into the UI store.
+ *
+ * The runtime emits its native {@link AgentEvent}s β€” the adapter is responsible
+ * for translating them to the wire/UI shape, so the package never depends on a
+ * transport-specific event format.
+ */
+export interface StreamSink {
+ publishChunk: (chunk: StreamChunkInput) => Promise<void> | void;
+ publishEvent: (event: AgentEvent) => Promise<void> | void;
+}
diff --git a/packages/agent-runtime/src/transport/subAgent.ts b/packages/agent-runtime/src/transport/subAgent.ts
new file mode 100644
index 00000000000..c6ad0dcf563
--- /dev/null
+++ b/packages/agent-runtime/src/transport/subAgent.ts
@@ -0,0 +1,19 @@
+import type {
+ ExecSubAgentParams,
+ ExecSubAgentResult,
+ ExecVirtualSubAgentParams,
+} from '@lobechat/types';
+
+/**
+ * Forks child agent runs for the `exec_sub_agent` / `exec_sub_agents`
+ * executors. `execVirtualSubAgent` additionally installs the async completion
+ * bridge and marks the child as a sub-agent.
+ *
+ * Group-member fan-out (`lobe-group-management`) is NOT here β€” it is plumbed
+ * through the tool-execution adapter as the per-call member runner, so it
+ * stays bound inside {@link ToolTransport}.
+ */
+export interface SubAgentTransport {
+ execSubAgent: (params: ExecSubAgentParams) => Promise<ExecSubAgentResult>;
+ execVirtualSubAgent: (params: ExecVirtualSubAgentParams) => Promise<ExecSubAgentResult>;
+}
diff --git a/packages/agent-runtime/src/transport/tool.ts b/packages/agent-runtime/src/transport/tool.ts
new file mode 100644
index 00000000000..86501d685ef
--- /dev/null
+++ b/packages/agent-runtime/src/transport/tool.ts
@@ -0,0 +1,37 @@
+import type { ChatToolPayload } from '@lobechat/types';
+
+/** Neutral mirror of the server `ToolExecutionResultResponse`. */
+export interface ToolRunResult {
+ content: string;
+ /** Server tool paused (client/device dispatch) β€” result arrives later. */
+ deferred?: boolean;
+ error?: unknown;
+ executionTime?: number;
+ state?: Record<string, any>;
+ success: boolean;
+}
+
+/**
+ * Per-call context the runtime knows at the moment of a tool call. The heavy
+ * server context (tool manifest map, sub-agent / group-member runners, DB
+ * handle, client-dispatch + result-archival + device-audit) is bound when the
+ * adapter is constructed β€” NOT passed here β€” so this stays transport-neutral.
+ */
+export interface ToolRunContext {
+ activeDeviceId?: string;
+ agentId?: string;
+ assistantMessageId?: string;
+ groupId?: string;
+ messageId?: string;
+ threadId?: string;
+ topicId?: string;
+}
+
+/**
+ * Executes a single tool call. Server adapter wraps `ToolExecutionService`
+ * (absorbing `dispatchClientTool`, result archival, and device audit); the
+ * client adapter wraps `internal_invokeDifferentTypePlugin`.
+ */
+export interface ToolTransport {
+ run: (call: ChatToolPayload, context: ToolRunContext) => Promise<ToolRunResult>;
+}