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.

♻️ refactor: inject graph runtime context continuously (#17761)

Rylan Cai86991beb7533
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
index 8222c2f041f..0abfbf27f9b 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts
@@ -2371,6 +2371,47 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {
);
});
+ it('should forward additional contexts without leaking model parameters', async () => {
+ const ctxWithConfig: RuntimeExecutorContext = {
+ ...ctx,
+ agentConfig: { plugins: [], systemRole: 'test' },
+ };
+ const additionalContexts = [
+ {
+ content: { text: 'Inspect the repository.', type: 'text' as const },
+ placement: 'stable_prefix' as const,
+ wrapper: { tag: 'graph_node_context' },
+ },
+ {
+ content: { text: 'Continue.', type: 'text' as const },
+ placement: 'virtual_tail' as const,
+ wrapper: {
+ attributes: { stage: 'inspection' },
+ tag: 'graph_runtime_guidance',
+ },
+ },
+ ];
+
+ await createRuntimeExecutors(ctxWithConfig).call_llm!(
+ {
+ payload: {
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'gpt-4',
+ provider: 'openai',
+ additionalContexts,
+ },
+ type: 'call_llm',
+ },
+ createMockState(),
+ );
+
+ expect(engineSpy).toHaveBeenCalledWith(expect.objectContaining({ additionalContexts }));
+ const modelPayload = mockChat.mock.calls[0][0];
+ expect(modelPayload).not.toHaveProperty('additionalContexts');
+ expect(JSON.stringify(modelPayload.messages)).toContain('<graph_node_context>');
+ expect(JSON.stringify(modelPayload.messages)).toContain('<graph_runtime_guidance');
+ });
+
it('should pass model knowledge cutoff into serverMessagesEngine', async () => {
const ctxWithConfig: RuntimeExecutorContext = {
...ctx,
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
index 3242d178534..ee014092250 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts
@@ -482,6 +482,7 @@ export const buildServerCallLlmContext = async ({
}
const contextEngineInput = {
+ additionalContexts: llmPayload.additionalContexts,
agentDocuments,
...(agentBuilderContext && { agentBuilderContext }),
agentGroup: state.metadata?.agentGroup as AgentGroupConfig | undefined,
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/index.ts b/apps/server/src/modules/Mecha/ContextEngineering/index.ts
index 3f72d8607c3..ffade6efe39 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/index.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/index.ts
@@ -115,6 +115,7 @@ const createServerVariableGenerators = (params: {
* ```
*/
export const serverMessagesEngine = async ({
+ additionalContexts,
messages = [],
model,
modelDisplayName,
@@ -150,6 +151,7 @@ export const serverMessagesEngine = async ({
userTimezone,
}: ServerMessagesEngineParams): Promise<OpenAIChatMessage[]> => {
const engine = new MessagesEngine({
+ additionalContexts,
// Capability injection
capabilities: {
isCanUseAudio: capabilities?.isCanUseAudio,
diff --git a/apps/server/src/modules/Mecha/ContextEngineering/types.ts b/apps/server/src/modules/Mecha/ContextEngineering/types.ts
index 734aeb8ae18..9bd33128a1a 100644
--- a/apps/server/src/modules/Mecha/ContextEngineering/types.ts
+++ b/apps/server/src/modules/Mecha/ContextEngineering/types.ts
@@ -18,7 +18,11 @@ import type {
UserMemoryData,
} from '@lobechat/context-engine';
import type { PageContentContext } from '@lobechat/prompts';
-import type { RuntimeInitialContext, UIChatMessage } from '@lobechat/types';
+import type {
+ RuntimeAdditionalContextFragment,
+ RuntimeInitialContext,
+ UIChatMessage,
+} from '@lobechat/types';
/**
* Model capability checker functions for server-side
@@ -73,6 +77,8 @@ export interface ServerUserMemoryConfig {
* instead of fetching from stores
*/
export interface ServerMessagesEngineParams {
+ /** Agent-materialized presentation contexts for this LLM call */
+ additionalContexts?: readonly RuntimeAdditionalContextFragment[];
/** Additional variable values to merge with defaults (e.g. device paths) */
additionalVariables?: Record<string, string>;
/** Agent documents to inject into context based on load rules and positions */
diff --git a/packages/agent-runtime/src/agents/GraphAgent.ts b/packages/agent-runtime/src/agents/graph/GraphAgent.ts
similarity index 91%
rename from packages/agent-runtime/src/agents/GraphAgent.ts
rename to packages/agent-runtime/src/agents/graph/GraphAgent.ts
index 224205540a2..732d1f0c7f1 100644
--- a/packages/agent-runtime/src/agents/GraphAgent.ts
+++ b/packages/agent-runtime/src/agents/graph/GraphAgent.ts
@@ -1,6 +1,7 @@
import { ToolNameResolver } from '@lobechat/context-engine';
import type { AgentGraphEdge, AgentGraphNode, ReasoningGraph } from '@lobechat/types';
import { AGENT_GRAPH_ROOT_NODE_ID } from '@lobechat/types';
+import { toJsonSafe } from '@lobechat/utils/json';
import type { UnknownRecord } from '@lobechat/utils/object';
import { isRecord } from '@lobechat/utils/object';
import Ajv from 'ajv';
@@ -13,8 +14,13 @@ import type {
FinishReason,
GeneralAgentCallLLMInstructionPayload,
GeneralAgentConfig,
-} from '../types';
-import { GeneralChatAgent } from './GeneralChatAgent';
+} from '../../types';
+import { GeneralChatAgent } from '../GeneralChatAgent';
+import {
+ evaluateGraphPromptTrigger,
+ getGraphBudgetStatus,
+ materializeGraphPromptContext,
+} from './graphPromptContext';
const GRAPH_RUNTIME_STATE_KEY = '__graphRuntimeState';
const DEFAULT_MAX_GRAPH_INSTRUCTION_COUNT = 256;
@@ -207,7 +213,13 @@ export class GraphAgent implements Agent {
graphState = orchestration.graphState;
this.updateGraphRuntimeState(state, { graphContext, graphState, instructionCount });
- const instruction = this.resolveRuntimeInstruction(orchestration);
+ const instruction = this.applyGraphPromptHooks({
+ context,
+ graphContext,
+ graphState,
+ instruction: this.resolveRuntimeInstruction(orchestration),
+ state,
+ });
// If the graph state machine lowers to a runtime instruction or reaches fin,
// we can return the instruction to the runtime.
@@ -344,25 +356,12 @@ export class GraphAgent implements Agent {
.filter((name): name is string => typeof name === 'string');
if (!graphState.active) {
- const prompt = this.renderPrompt({
- input_context: this.resolveNodeInputContext(graphState.incomingEdge, input),
- output_contract: this.getOutputSchema(graphState.incomingEdge) as PromptObject,
- task_instruction: graphState.incomingEdge.instruction,
- });
- const callLlm = (prompt: string): AgentInstruction => {
- const payload: GeneralAgentCallLLMInstructionPayload = {
- allowedToolNames,
- messages: [...state.messages, { content: prompt, role: 'user' as const }],
- model: state.modelRuntimeConfig?.model ?? '',
- provider: state.modelRuntimeConfig?.provider ?? '',
- tools,
- };
-
- return {
- payload,
- stepLabel: graphState.currentNode,
- type: 'call_llm',
- };
+ const payload: GeneralAgentCallLLMInstructionPayload = {
+ allowedToolNames,
+ messages: state.messages,
+ model: state.modelRuntimeConfig?.model ?? '',
+ provider: state.modelRuntimeConfig?.provider ?? '',
+ tools,
};
return {
@@ -372,7 +371,11 @@ export class GraphAgent implements Agent {
active: true,
nodeStartStepCount: state.stepCount,
},
- instruction: callLlm(prompt),
+ instruction: {
+ payload,
+ stepLabel: graphState.currentNode,
+ type: 'call_llm',
+ },
};
}
@@ -632,6 +635,61 @@ export class GraphAgent implements Agent {
: instruction.type === 'finish';
}
+ private applyGraphPromptHooks(input: {
+ context: AgentRuntimeContext;
+ graphContext: GraphContext;
+ graphState: GraphState;
+ instruction?: AgentInstruction | AgentInstruction[];
+ state: AgentState;
+ }): AgentInstruction | AgentInstruction[] | undefined {
+ const { graphState, instruction } = input;
+ const callsLlm = Array.isArray(instruction)
+ ? instruction.some((item) => item.type === 'call_llm')
+ : instruction?.type === 'call_llm';
+
+ if (!instruction || !callsLlm || graphState.phase !== 'node_in' || !graphState.active) {
+ return instruction;
+ }
+
+ const node = this.getNodeById(graphState.currentNode);
+ if (!node) return instruction;
+
+ const usedNodeRuntimeSteps = Math.max(
+ 0,
+ input.state.stepCount - (graphState.nodeStartStepCount ?? input.state.stepCount),
+ );
+ const budgetStatus = getGraphBudgetStatus(node, usedNodeRuntimeSteps);
+ const additionalContexts = materializeGraphPromptContext({
+ ...(node.type === 'agent' && node.allowedToolApiNames !== undefined
+ ? { allowedToolApiNames: node.allowedToolApiNames }
+ : {}),
+ budgetStatus,
+ inputContext: toJsonSafe(
+ this.resolveNodeInputContext(graphState.incomingEdge, {
+ context: input.context,
+ graphContext: input.graphContext,
+ graphState,
+ state: input.state,
+ }),
+ ),
+ outputContract: toJsonSafe(this.getOutputSchema(graphState.incomingEdge)),
+ stage: graphState.currentNode,
+ taskInstruction: graphState.incomingEdge.instruction,
+ trigger: evaluateGraphPromptTrigger({
+ budgetStatus,
+ isAfterCompression: input.context.phase === 'compression_result',
+ usedNodeRuntimeSteps,
+ }),
+ });
+
+ const attach = (item: AgentInstruction): AgentInstruction =>
+ item.type === 'call_llm'
+ ? { ...item, payload: { ...item.payload, additionalContexts } }
+ : item;
+
+ return Array.isArray(instruction) ? instruction.map(attach) : attach(instruction);
+ }
+
private loadGraphRuntimeState(state: Readonly<AgentState>): GraphRuntimeState {
const graphRuntimeState = state.metadata?.[GRAPH_RUNTIME_STATE_KEY] as
GraphRuntimeState | undefined;
diff --git a/packages/agent-runtime/src/agents/__tests__/GraphAgent.test.ts b/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts
similarity index 80%
rename from packages/agent-runtime/src/agents/__tests__/GraphAgent.test.ts
rename to packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts
index 72e98cf5e48..48ae23173e2 100644
--- a/packages/agent-runtime/src/agents/__tests__/GraphAgent.test.ts
+++ b/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts
@@ -3,11 +3,11 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { ToolNameResolver } from '@lobechat/context-engine';
-import type { ReasoningGraph } from '@lobechat/types';
+import type { ReasoningGraph, RuntimeAdditionalContextFragment } from '@lobechat/types';
import { AGENT_GRAPH_ROOT_NODE_ID, ReasoningGraphSchema } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
-import type { AgentInstruction, AgentRuntimeContext, AgentState } from '../../types';
+import type { AgentInstruction, AgentRuntimeContext, AgentState } from '../../../types';
import { GraphAgent } from '../GraphAgent';
const GRAPH_RUNTIME_STATE_KEY = '__graphRuntimeState';
@@ -99,6 +99,36 @@ const getLastPrompt = (instruction: AgentInstruction | AgentInstruction[]) => {
return typeof lastMessage?.content === 'string' ? lastMessage.content : '';
};
+const getAdditionalContexts = (
+ instruction: AgentInstruction | AgentInstruction[],
+): readonly RuntimeAdditionalContextFragment[] => {
+ const additionalContexts = expectCallLlm(instruction).payload.additionalContexts;
+ expect(additionalContexts).toBeDefined();
+
+ return additionalContexts as readonly RuntimeAdditionalContextFragment[];
+};
+
+const getFragment = (
+ instruction: AgentInstruction | AgentInstruction[],
+ tag: string,
+): RuntimeAdditionalContextFragment | undefined =>
+ getAdditionalContexts(instruction).find((fragment) => fragment.wrapper.tag === tag);
+
+const getGraphNodeContext = (instruction: AgentInstruction | AgentInstruction[]) => {
+ const fragment = getFragment(instruction, 'graph_node_context');
+ expect(fragment?.content.type).toBe('sections');
+
+ return fragment as RuntimeAdditionalContextFragment & {
+ content: Extract<RuntimeAdditionalContextFragment['content'], { type: 'sections' }>;
+ };
+};
+
+const getGraphNodeSection = (instruction: AgentInstruction | AgentInstruction[], tag: string) =>
+ getGraphNodeContext(instruction).content.sections.find((section) => section.tag === tag)?.value;
+
+const getGraphNodeContextText = (instruction: AgentInstruction | AgentInstruction[]) =>
+ JSON.stringify(getGraphNodeContext(instruction));
+
const loadGoalLoopGraph = (): ReasoningGraph => {
const graph = JSON.parse(
readFileSync(path.join(TEST_DIR, 'fixtures/goal-loop.graph.json'), 'utf8'),
@@ -441,7 +471,47 @@ describe('GraphAgent', () => {
});
describe('prompt', () => {
- it('should render node instruction, upstream field value, upstream field description, and deliverable target', async () => {
+ it('should attach node context and entry guidance without the legacy node envelope', async () => {
+ const agent = new GraphAgent({
+ agentConfig: { maxSteps: 100 },
+ graph: loadGoalLoopGraph(),
+ operationId: 'test-operation',
+ });
+ const messages = [{ content: '/goal inspect graph context', role: 'user' as const }];
+ const state = createMockState({ messages });
+
+ const instruction = await agent.runner(createContext('init'), state);
+ const call = expectCallLlm(instruction);
+ const additionalContexts = getAdditionalContexts(instruction);
+
+ expect(call.payload.messages).toEqual(messages);
+ expect(call.payload.messages).not.toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({ content: expect.stringContaining('<task_instruction>') }),
+ ]),
+ );
+ expect(additionalContexts).toHaveLength(2);
+ expect(additionalContexts.map(({ wrapper }) => wrapper.tag)).toEqual([
+ 'graph_node_context',
+ 'graph_runtime_guidance',
+ ]);
+ expect(additionalContexts.map(({ placement }) => placement)).toEqual([
+ 'stable_prefix',
+ 'virtual_tail',
+ ]);
+ expect(getFragment(instruction, 'graph_runtime_guidance')).toMatchObject({
+ wrapper: { attributes: { stage: 'plan' } },
+ });
+ expect(getGraphNodeSection(instruction, 'allowed_tool_api_names')).toEqual([
+ 'read',
+ 'search',
+ ]);
+ expect(getGraphNodeSection(instruction, 'task_instruction')).toContain(
+ 'Convert the user /goal request into concrete goals.',
+ );
+ });
+
+ it('should attach node instruction, upstream field value, field description, and deliverable target', async () => {
const agent = new GraphAgent({
agentConfig: { maxSteps: 100 },
graph: loadGoalLoopGraph(),
@@ -463,22 +533,20 @@ describe('GraphAgent', () => {
createLlmResultContext(JSON.stringify({ goals })),
state,
);
- const prompt = getLastPrompt(workInstruction);
-
- expect(prompt).toContain('<task_instruction>');
- expect(prompt).toContain('<input_context>');
- expect(prompt).toContain('<output_contract>');
- expect(prompt).not.toContain('<taskInstruction>');
- expect(prompt).not.toContain('<inputContext>');
- expect(prompt).not.toContain('<outputContract>');
- expect(prompt).toContain(
+ const serializedContext = getGraphNodeContextText(workInstruction);
+
+ expect(getGraphNodeSection(workInstruction, 'task_instruction')).toBe(
'Complete the planned goals. Work through the provided goals and summarize what changed.',
);
- expect(prompt).toContain('close prompt loop');
- expect(prompt).toContain('Ensure prompt contains values and field semantics.');
- expect(prompt).toContain('Concrete goals planned from the user request.');
- expect(prompt).toContain('summary');
- expect(prompt).toContain('Worker summary describing completed work and remaining risk.');
+ expect(getGraphNodeSection(workInstruction, 'allowed_tool_api_names')).toBeUndefined();
+ expect(serializedContext).toContain('close prompt loop');
+ expect(serializedContext).toContain('Ensure prompt contains values and field semantics.');
+ expect(serializedContext).toContain('Concrete goals planned from the user request.');
+ expect(serializedContext).toContain('summary');
+ expect(serializedContext).toContain(
+ 'Worker summary describing completed work and remaining risk.',
+ );
+ expect(expectCallLlm(workInstruction).payload.messages).toEqual(state.messages);
});
it('should render multi-source input context and verifier output contract', async () => {
@@ -506,17 +574,21 @@ describe('GraphAgent', () => {
createLlmResultContext(JSON.stringify({ summary })),
state,
);
- const prompt = getLastPrompt(verifyInstruction);
+ const serializedContext = getGraphNodeContextText(verifyInstruction);
- expect(prompt).toContain(
+ expect(getGraphNodeSection(verifyInstruction, 'task_instruction')).toBe(
'Verify whether the work satisfies the planned goals. Return fin=true only when all goals are complete.',
);
- expect(prompt).toContain('Concrete goals planned from the user request.');
- expect(prompt).toContain('Render upstream plan fields and worker result together.');
- expect(prompt).toContain('Worker summary describing completed work and remaining risk.');
- expect(prompt).toContain(summary);
- expect(prompt).toContain('review');
- expect(prompt).toContain('Verifier decision and unfinished goals.');
+ expect(serializedContext).toContain('Concrete goals planned from the user request.');
+ expect(serializedContext).toContain(
+ 'Render upstream plan fields and worker result together.',
+ );
+ expect(serializedContext).toContain(
+ 'Worker summary describing completed work and remaining risk.',
+ );
+ expect(serializedContext).toContain(summary);
+ expect(serializedContext).toContain('review');
+ expect(serializedContext).toContain('Verifier decision and unfinished goals.');
});
it('should render extraction instruction, format instruction, schema, and previous error', async () => {
@@ -546,6 +618,7 @@ describe('GraphAgent', () => {
expect(prompt).toContain('Concrete goals planned from the user request.');
expect(prompt).toContain('<previous_error>');
expect(prompt).toContain('The node output is not valid JSON.');
+ expect(expectCallLlm(extractionInstruction).payload.additionalContexts).toBeUndefined();
});
it('should render raw fallback context once when declared input fields are missing', async () => {
@@ -587,14 +660,129 @@ describe('GraphAgent', () => {
workInstruction = await agent.runner(createLlmResultContext(content), state);
}
if (!workInstruction) throw new Error('Expected work instruction');
- const prompt = getLastPrompt(workInstruction);
+ const context = getGraphNodeContextText(workInstruction);
- expect(prompt).toContain('rawFallback');
- expect(prompt).toContain(
+ expect(context).toContain('rawFallback');
+ expect(context).toContain(
'Declared input fields were missing from this source output. Use this raw source output as fallback context.',
);
- expect(prompt).toContain('plan failed but left useful raw planning notes');
- expect(prompt.match(/plan failed but left useful raw planning notes/g)).toHaveLength(1);
+ expect(context).toContain('plan failed but left useful raw planning notes');
+ expect(context.match(/plan failed but left useful raw planning notes/g)).toHaveLength(1);
+ });
+
+ it('should derive normal guidance cadence from existing node runtime steps', async () => {
+ const graph = loadGoalLoopGraph();
+ const agent = new GraphAgent({
+ agentConfig: { maxSteps: 100 },
+ graph: {
+ ...graph,
+ nodes: {
+ ...graph.nodes,
+ plan: { allowedToolApiNames: ['read', 'search'], maxAgentSteps: 100, type: 'agent' },
+ },
+ },
+ modelRuntimeConfig: { model: 'gpt-4', provider: 'openai' },
+ operationId: 'test-operation',
+ });
+ const state = createMockState({
+ messages: [{ content: '/goal inspect cadence', role: 'user' }],
+ });
+
+ await agent.runner(createContext('init'), state);
+ state.stepCount = 7;
+ const stepSeven = await agent.runner(
+ createContext('tools_batch_result', { parentMessageId: 'tool-msg-7' }),
+ state,
+ );
+ state.stepCount = 8;
+ const stepEight = await agent.runner(
+ createContext('tools_batch_result', { parentMessageId: 'tool-msg-8' }),
+ state,
+ );
+
+ expect(getFragment(stepSeven, 'graph_runtime_guidance')).toBeUndefined();
+ expect(getFragment(stepSeven, 'graph_node_context')).toMatchObject({
+ wrapper: { tag: 'graph_node_context' },
+ });
+ expect(getFragment(stepEight, 'graph_runtime_guidance')).toMatchObject({
+ wrapper: { attributes: { stage: 'plan' } },
+ });
+ expect(Object.keys(getGraphRuntimeState(state) ?? {}).sort()).toEqual([
+ 'graphContext',
+ 'graphState',
+ 'instructionCount',
+ ]);
+ });
+
+ it('should use four-step guidance cadence near a finite node budget', async () => {
+ const graph = loadGoalLoopGraph();
+ const agent = new GraphAgent({
+ agentConfig: { maxSteps: 100 },
+ graph: {
+ ...graph,
+ nodes: {
+ ...graph.nodes,
+ plan: { allowedToolApiNames: ['read', 'search'], maxAgentSteps: 20, type: 'agent' },
+ },
+ },
+ modelRuntimeConfig: { model: 'gpt-4', provider: 'openai' },
+ operationId: 'test-operation',
+ });
+ const state = createMockState({
+ messages: [{ content: '/goal inspect near budget cadence', role: 'user' }],
+ });
+
+ await agent.runner(createContext('init'), state);
+ state.stepCount = 15;
+ const beforeWindow = await agent.runner(
+ createContext('tools_batch_result', { parentMessageId: 'tool-msg-15' }),
+ state,
+ );
+ state.stepCount = 16;
+ const inWindow = await agent.runner(
+ createContext('tools_batch_result', { parentMessageId: 'tool-msg-16' }),
+ state,
+ );
+ state.stepCount = 17;
+ const betweenCadence = await agent.runner(
+ createContext('tools_batch_result', { parentMessageId: 'tool-msg-17' }),
+ state,
+ );
+
+ expect(getFragment(beforeWindow, 'graph_runtime_guidance')).toBeUndefined();
+ expect(getFragment(inWindow, 'graph_runtime_guidance')).toMatchObject({
+ wrapper: { attributes: { budget_status: 'near_exhaustion', stage: 'plan' } },
+ });
+ expect(getFragment(betweenCadence, 'graph_runtime_guidance')).toBeUndefined();
+ });
+
+ it('should emit guidance immediately after compression', async () => {
+ const agent = new GraphAgent({
+ agentConfig: { maxSteps: 100 },
+ graph: loadGoalLoopGraph(),
+ modelRuntimeConfig: { model: 'gpt-4', provider: 'openai' },
+ operationId: 'test-operation',
+ });
+ const state = createMockState({
+ messages: [{ content: '/goal rebuild after compression', role: 'user' }],
+ });
+
+ await agent.runner(createContext('init'), state);
+ state.stepCount = 3;
+ const instruction = await agent.runner(
+ createContext('compression_result', {
+ compressedMessages: state.messages,
+ parentMessageId: 'compressed-parent',
+ }),
+ state,
+ );
+
+ expect(getFragment(instruction, 'graph_runtime_guidance')).toMatchObject({
+ wrapper: { attributes: { stage: 'plan' } },
+ });
+ expect(getFragment(instruction, 'graph_node_context')).toMatchObject({
+ wrapper: { tag: 'graph_node_context' },
+ });
});
});
@@ -643,7 +831,9 @@ describe('GraphAgent', () => {
expect(getGraphStore(state)?.[AGENT_GRAPH_ROOT_NODE_ID]).toEqual({
query: '/goal refactor graph agent runtime',
});
- expect(getLastPrompt(planInstruction)).toContain('/goal refactor graph agent runtime');
+ expect(getGraphNodeContextText(planInstruction)).toContain(
+ '/goal refactor graph agent runtime',
+ );
const goals = [
{ desc: 'Define the graph schema for goal loops.', name: 'design schema' },
@@ -659,8 +849,8 @@ describe('GraphAgent', () => {
const workCall = expectCallLlm(workInstruction);
expect(workCall.stepLabel).toBe('work');
expect(workCall.payload.allowedToolNames).toBeUndefined();
- expect(getLastPrompt(workInstruction)).toContain('design schema');
- expect(getLastPrompt(workInstruction)).toContain(
+ expect(getGraphNodeContextText(workInstruction)).toContain('design schema');
+ expect(getGraphNodeContextText(workInstruction)).toContain(
'Cover the plan-work-verify loop with tests.',
);
@@ -676,8 +866,8 @@ describe('GraphAgent', () => {
expect(verifyCall.stepLabel).toBe('verify');
expect(verifyCall.payload.allowedToolNames).toEqual([]);
expect(verifyCall.payload.tools).toEqual([]);
- expect(getLastPrompt(verifyInstruction)).toContain('design schema');
- expect(getLastPrompt(verifyInstruction)).toContain(firstSummary);
+ expect(getGraphNodeContextText(verifyInstruction)).toContain('design schema');
+ expect(getGraphNodeContextText(verifyInstruction)).toContain(firstSummary);
const unfinishedGoal = {
desc: 'The goal-loop E2E still needs a passing verification branch.',
@@ -703,8 +893,8 @@ describe('GraphAgent', () => {
});
expect(getGraphState(state)).toMatchObject({ currentNode: 'work', phase: 'node_in' });
expect(expectCallLlm(reworkInstruction).stepLabel).toBe('work');
- expect(getLastPrompt(reworkInstruction)).toContain('finish tests');
- expect(getLastPrompt(reworkInstruction)).toContain(
+ expect(getGraphNodeContextText(reworkInstruction)).toContain('finish tests');
+ expect(getGraphNodeContextText(reworkInstruction)).toContain(
'The goal-loop E2E still needs a passing verification branch.',
);
@@ -717,7 +907,7 @@ describe('GraphAgent', () => {
expect(getGraphStore(state)?.work).toEqual({ summary: finalSummary });
expect(getGraphState(state)).toMatchObject({ currentNode: 'verify', phase: 'node_in' });
expect(expectCallLlm(finalVerifyInstruction).stepLabel).toBe('verify');
- expect(getLastPrompt(finalVerifyInstruction)).toContain(finalSummary);
+ expect(getGraphNodeContextText(finalVerifyInstruction)).toContain(finalSummary);
const result = await agent.runner(
createLlmResultContext(
@@ -1053,8 +1243,8 @@ describe('GraphAgent', () => {
);
expect(expectCallLlm(matchedInstruction).stepLabel).toBe('matched');
- expect(getLastPrompt(matchedInstruction)).toContain('Matched route instruction.');
- expect(getLastPrompt(matchedInstruction)).toContain('go');
+ expect(getGraphNodeContextText(matchedInstruction)).toContain('Matched route instruction.');
+ expect(getGraphNodeContextText(matchedInstruction)).toContain('go');
const fallbackAgent = new GraphAgent({
agentConfig: { maxSteps: 100 },
@@ -1072,8 +1262,8 @@ describe('GraphAgent', () => {
);
expect(expectCallLlm(fallbackInstruction).stepLabel).toBe('fallback');
- expect(getLastPrompt(fallbackInstruction)).toContain('Fallback route instruction.');
- expect(getLastPrompt(fallbackInstruction)).toContain('stop');
+ expect(getGraphNodeContextText(fallbackInstruction)).toContain('Fallback route instruction.');
+ expect(getGraphNodeContextText(fallbackInstruction)).toContain('stop');
});
it('should treat invalid condition schemas as no match and use the default edge', async () => {
@@ -1137,10 +1327,12 @@ describe('GraphAgent', () => {
);
expect(expectCallLlm(fallbackInstruction).stepLabel).toBe('fallback');
- expect(getLastPrompt(fallbackInstruction)).toContain(
+ expect(getGraphNodeContextText(fallbackInstruction)).toContain(
'Default route after invalid condition.',
);
- expect(getLastPrompt(fallbackInstruction)).not.toContain('Invalid condition route.');
+ expect(getGraphNodeContextText(fallbackInstruction)).not.toContain(
+ 'Invalid condition route.',
+ );
});
it('should retry extraction when parsed JSON does not match the edge output schema', async () => {
@@ -1181,7 +1373,9 @@ describe('GraphAgent', () => {
expect(getGraphStore(state)?.plan).toEqual({ goals });
expect(expectCallLlm(workInstruction).stepLabel).toBe('work');
- expect(getLastPrompt(workInstruction)).toContain('Recovered with a valid goal description.');
+ expect(getGraphNodeContextText(workInstruction)).toContain(
+ 'Recovered with a valid goal description.',
+ );
});
it('should request fenced json extraction and commit recovered node output', async () => {
@@ -1224,7 +1418,7 @@ describe('GraphAgent', () => {
expect(getGraphStore(state)?.plan).toEqual({ goals });
expect(getGraphState(state)).toMatchObject({ currentNode: 'work', phase: 'node_in' });
expect(expectCallLlm(workInstruction).stepLabel).toBe('work');
- expect(getLastPrompt(workInstruction)).toContain('Cover graph extraction retry.');
+ expect(getGraphNodeContextText(workInstruction)).toContain('Cover graph extraction retry.');
});
it('should stop the verify-to-work loop when maxTraversals is reached', async () => {
diff --git a/packages/agent-runtime/src/agents/__tests__/fixtures/goal-loop.graph.json b/packages/agent-runtime/src/agents/graph/__tests__/fixtures/goal-loop.graph.json
similarity index 100%
rename from packages/agent-runtime/src/agents/__tests__/fixtures/goal-loop.graph.json
rename to packages/agent-runtime/src/agents/graph/__tests__/fixtures/goal-loop.graph.json
diff --git a/packages/agent-runtime/src/agents/graph/graphPromptContext.ts b/packages/agent-runtime/src/agents/graph/graphPromptContext.ts
new file mode 100644
index 00000000000..965d76bfc16
--- /dev/null
+++ b/packages/agent-runtime/src/agents/graph/graphPromptContext.ts
@@ -0,0 +1,112 @@
+import type {
+ AgentGraphNode,
+ RuntimeAdditionalContextFragment,
+ RuntimeAdditionalContextValue,
+} from '@lobechat/types';
+
+type GraphPromptTrigger =
+ | { type: 'after_compression' }
+ | { type: 'every_n_node_steps'; interval: number }
+ | { type: 'stage_start' };
+
+interface GraphPromptMaterializerInput {
+ allowedToolApiNames?: readonly string[];
+ budgetStatus: GraphBudgetStatus;
+ inputContext: RuntimeAdditionalContextValue;
+ outputContract: RuntimeAdditionalContextValue;
+ stage: string;
+ taskInstruction: string;
+ trigger?: GraphPromptTrigger;
+}
+
+type GraphBudgetStatus = 'near_exhaustion' | 'normal';
+
+const NORMAL_GUIDANCE_INTERVAL = 8;
+const NEAR_EXHAUSTION_GUIDANCE_INTERVAL = 4;
+
+export const getGraphBudgetStatus = (
+ node: Readonly<AgentGraphNode>,
+ usedNodeRuntimeSteps: number,
+): GraphBudgetStatus => {
+ if (node.type !== 'agent' || node.maxAgentSteps === undefined) return 'normal';
+
+ const warningWindow = Math.max(1, Math.ceil(node.maxAgentSteps * 0.2));
+ const remainingSteps = Math.max(0, node.maxAgentSteps - usedNodeRuntimeSteps);
+
+ return remainingSteps <= warningWindow ? 'near_exhaustion' : 'normal';
+};
+
+export const evaluateGraphPromptTrigger = (input: {
+ budgetStatus: GraphBudgetStatus;
+ isAfterCompression: boolean;
+ usedNodeRuntimeSteps: number;
+}): GraphPromptTrigger | undefined => {
+ if (input.isAfterCompression) return { type: 'after_compression' };
+ if (input.usedNodeRuntimeSteps === 0) return { type: 'stage_start' };
+
+ const interval =
+ input.budgetStatus === 'near_exhaustion'
+ ? NEAR_EXHAUSTION_GUIDANCE_INTERVAL
+ : NORMAL_GUIDANCE_INTERVAL;
+
+ return input.usedNodeRuntimeSteps % interval === 0
+ ? { interval, type: 'every_n_node_steps' }
+ : undefined;
+};
+
+const createGuidanceFragment = (
+ stage: string,
+ budgetStatus: GraphBudgetStatus,
+): RuntimeAdditionalContextFragment => ({
+ content: {
+ text:
+ budgetStatus === 'near_exhaustion'
+ ? [
+ 'The current Graph stage budget is nearly exhausted. Begin finalization now.',
+ 'Do not start new exploratory branches. Consolidate the evidence already gathered,',
+ 'and complete the remaining actions required by graph_node_context. Once those actions',
+ 'are complete, stop making tool calls and produce the stage result matching its output_contract.',
+ ].join('\n')
+ : 'The current Graph stage remains active. Continue following the constraints and output contract in graph_node_context.',
+ type: 'text',
+ },
+ placement: 'virtual_tail',
+ wrapper: {
+ attributes: {
+ stage,
+ ...(budgetStatus === 'near_exhaustion' && { budget_status: 'near_exhaustion' }),
+ },
+ tag: 'graph_runtime_guidance',
+ },
+});
+
+export const materializeGraphPromptContext = (
+ input: GraphPromptMaterializerInput,
+): readonly RuntimeAdditionalContextFragment[] => {
+ const nodeContextFragment: RuntimeAdditionalContextFragment = {
+ content: {
+ sections: [
+ { format: 'json', tag: 'input_context', value: input.inputContext },
+ { format: 'text', tag: 'task_instruction', value: input.taskInstruction },
+ ...(input.allowedToolApiNames === undefined
+ ? []
+ : [
+ {
+ format: 'compact_json' as const,
+ tag: 'allowed_tool_api_names',
+ value: input.allowedToolApiNames,
+ },
+ ]),
+ { format: 'json', tag: 'output_contract', value: input.outputContract },
+ ],
+ type: 'sections',
+ },
+ placement: 'stable_prefix',
+ wrapper: { tag: 'graph_node_context' },
+ };
+
+ return [
+ nodeContextFragment,
+ ...(input.trigger ? [createGuidanceFragment(input.stage, input.budgetStatus)] : []),
+ ];
+};
diff --git a/packages/agent-runtime/src/agents/graph/index.ts b/packages/agent-runtime/src/agents/graph/index.ts
new file mode 100644
index 00000000000..a6a9a689340
--- /dev/null
+++ b/packages/agent-runtime/src/agents/graph/index.ts
@@ -0,0 +1 @@
+export * from './GraphAgent';
diff --git a/packages/agent-runtime/src/agents/index.ts b/packages/agent-runtime/src/agents/index.ts
index f938f09c070..256e7078eed 100644
--- a/packages/agent-runtime/src/agents/index.ts
+++ b/packages/agent-runtime/src/agents/index.ts
@@ -1,2 +1,2 @@
export * from './GeneralChatAgent';
-export * from './GraphAgent';
+export * from './graph';
diff --git a/packages/agent-runtime/src/types/generalAgent.ts b/packages/agent-runtime/src/types/generalAgent.ts
index 9384b89ce33..4c4fb750889 100644
--- a/packages/agent-runtime/src/types/generalAgent.ts
+++ b/packages/agent-runtime/src/types/generalAgent.ts
@@ -3,9 +3,11 @@ import {
type DynamicInterventionResolver,
type GlobalInterventionAuditConfig,
type MessageToolCall,
+ type RuntimeAdditionalContextFragment,
} from '@lobechat/types';
export interface GeneralAgentCallLLMInstructionPayload {
+ additionalContexts?: readonly RuntimeAdditionalContextFragment[];
allowedToolNames?: string[];
/**
* Reuse an existing assistant message instead of creating a new one. Set when
diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.ts
index 7319f52da84..382c99f9eb7 100644
--- a/packages/agent-runtime/src/types/instruction.ts
+++ b/packages/agent-runtime/src/types/instruction.ts
@@ -1,6 +1,7 @@
import type {
ChatToolPayload,
ModelUsage,
+ RuntimeAdditionalContextFragment,
RuntimeInitialContext,
RuntimeStepContext,
} from '@lobechat/types';
@@ -119,6 +120,7 @@ export interface Agent {
// ── Payloads ──────────────────────────────────────────────
export interface CallLLMPayload {
+ additionalContexts?: readonly RuntimeAdditionalContextFragment[];
allowedToolNames?: string[];
isFirstMessage?: boolean;
messages: any[];
diff --git a/packages/context-engine/src/engine/messages/MessagesEngine.ts b/packages/context-engine/src/engine/messages/MessagesEngine.ts
index edaed62e818..548ec450029 100644
--- a/packages/context-engine/src/engine/messages/MessagesEngine.ts
+++ b/packages/context-engine/src/engine/messages/MessagesEngine.ts
@@ -52,6 +52,7 @@ import {
PageEditorContextInjector,
PageSelectionsInjector,
PlanInjector,
+ RuntimeAdditionalContextProvider,
selectActivatedSkills,
SelectedSkillInjector,
selectToolPromptManifests,
@@ -171,6 +172,7 @@ export class MessagesEngine {
onboardingContext,
agentManagementContext,
groupAgentBuilderContext,
+ additionalContexts,
agentGroup,
agentDocuments,
planTodo,
@@ -439,6 +441,7 @@ export class MessagesEngine {
enabled: !!onboardingContext?.phaseGuidance,
onboardingContext,
}),
+ new RuntimeAdditionalContextProvider({ additionalContexts }),
// =============================================
// Phase 5: Message Transformation
diff --git a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
index 677068ebaf4..9da16f07c5a 100644
--- a/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
+++ b/packages/context-engine/src/engine/messages/__tests__/MessagesEngine.test.ts
@@ -1316,5 +1316,48 @@ Document content here.
expect(result.messages).toEqual([{ content: 'Question', role: 'user' }]);
});
+
+ it('should place additional contexts at the stable prefix and virtual tail', async () => {
+ const result = await new MessagesEngine(
+ createBasicParams({
+ additionalContexts: [
+ {
+ content: { text: 'Stable context.', type: 'text' },
+ placement: 'stable_prefix',
+ wrapper: { tag: 'stable_context' },
+ },
+ {
+ content: { text: 'Tail guidance.', type: 'text' },
+ placement: 'virtual_tail',
+ wrapper: { tag: 'tail_guidance' },
+ },
+ ],
+ }),
+ ).process();
+
+ expect(result.messages).toEqual([
+ {
+ content: '<stable_context>\nStable context.\n</stable_context>',
+ role: 'user',
+ },
+ { content: 'Hello', role: 'user' },
+ { content: 'Hi there!', role: 'assistant' },
+ {
+ content: '<tail_guidance>\nTail guidance.\n</tail_guidance>',
+ role: 'user',
+ },
+ ]);
+ });
+
+ it('should leave non-Graph output unchanged when Graph context is omitted', async () => {
+ const params = createBasicParams();
+ const baseline = await new MessagesEngine(params).process();
+ const withoutGraph = await new MessagesEngine({
+ ...params,
+ additionalContexts: undefined,
+ }).process();
+
+ expect(withoutGraph.messages).toEqual(baseline.messages);
+ });
});
});
diff --git a/packages/context-engine/src/engine/messages/types.ts b/packages/context-engine/src/engine/messages/types.ts
index 17ba835bdba..4b820dfb5b9 100644
--- a/packages/context-engine/src/engine/messages/types.ts
+++ b/packages/context-engine/src/engine/messages/types.ts
@@ -1,6 +1,7 @@
/* eslint-disable perfectionist/sort-interfaces */
import type { FileContent, KnowledgeBaseInfo, PageContentContext } from '@lobechat/prompts';
import type {
+ RuntimeAdditionalContextFragment,
RuntimeInitialContext,
RuntimeSelectedSkill,
RuntimeSelectedTool,
@@ -250,6 +251,8 @@ export interface MessagesEngineParams {
inputTemplate?: string;
/** System role */
systemRole?: string;
+ /** Agent-materialized presentation contexts for this LLM call */
+ additionalContexts?: readonly RuntimeAdditionalContextFragment[];
// ========== Capability injection (dependency injection) ==========
/** Model capability checker */
diff --git a/packages/context-engine/src/providers/RuntimeAdditionalContextProvider.ts b/packages/context-engine/src/providers/RuntimeAdditionalContextProvider.ts
new file mode 100644
index 00000000000..5083074cad4
--- /dev/null
+++ b/packages/context-engine/src/providers/RuntimeAdditionalContextProvider.ts
@@ -0,0 +1,134 @@
+import { escapeXmlAttr, escapeXmlContent } from '@lobechat/prompts';
+import type { RuntimeAdditionalContextFragment } from '@lobechat/types';
+
+import { BaseProcessor } from '../base/BaseProcessor';
+import type { PipelineContext, ProcessorOptions } from '../types';
+
+export interface RuntimeAdditionalContextProviderConfig {
+ additionalContexts?: readonly RuntimeAdditionalContextFragment[];
+}
+
+export class RuntimeAdditionalContextProvider extends BaseProcessor {
+ readonly name = 'RuntimeAdditionalContextProvider';
+
+ constructor(
+ private config: RuntimeAdditionalContextProviderConfig,
+ options: ProcessorOptions = {},
+ ) {
+ super(options);
+ }
+
+ protected async doProcess(context: PipelineContext): Promise<PipelineContext> {
+ const fragments = this.config.additionalContexts;
+ if (!fragments?.length) return this.markAsExecuted(context);
+
+ const render = (placement: RuntimeAdditionalContextFragment['placement']) =>
+ fragments
+ .filter((fragment) => fragment.placement === placement)
+ .map((fragment) => {
+ const attributes = Object.entries(fragment.wrapper.attributes ?? {})
+ .map(([key, value]) => ` ${key}="${escapeXmlAttr(value)}"`)
+ .join('');
+ const content =
+ fragment.content.type === 'text'
+ ? escapeXmlContent(fragment.content.text)
+ : fragment.content.sections
+ .map((section) => {
+ const value =
+ section.format === 'text'
+ ? escapeXmlContent(String(section.value))
+ : JSON.stringify(
+ section.value,
+ null,
+ section.format === 'compact_json' ? undefined : 2,
+ )
+ .replaceAll('<', '\\u003c')
+ .replaceAll('>', '\\u003e');
+
+ return [`<${section.tag}>`, value, `</${section.tag}>`].join(
+ section.format === 'text' ? '' : '\n',
+ );
+ })
+ .join('\n');
+
+ return [
+ `<${fragment.wrapper.tag}${attributes}>`,
+ content,
+ `</${fragment.wrapper.tag}>`,
+ ].join('\n');
+ })
+ .join('\n\n');
+
+ const stableContent = render('stable_prefix');
+ const tailContent = render('virtual_tail');
+ if (!stableContent && !tailContent) return this.markAsExecuted(context);
+
+ const clonedContext = this.cloneContext(context);
+
+ if (stableContent) {
+ const injectionIndex = clonedContext.messages.findIndex(
+ (message) => message.meta?.systemInjection === true,
+ );
+
+ if (injectionIndex === -1) {
+ const firstUserIndex = clonedContext.messages.findIndex(
+ (message) =>
+ message.role === 'user' &&
+ message.meta?.systemInjection !== true &&
+ message.meta?.virtualLastUser !== true,
+ );
+
+ if (firstUserIndex !== -1) {
+ const now = Date.now();
+ clonedContext.messages.splice(firstUserIndex, 0, {
+ content: stableContent,
+ createdAt: now,
+ id: `system-injection-${now}`,
+ meta: { systemInjection: true },
+ role: 'user',
+ updatedAt: now,
+ });
+ }
+ } else {
+ const message = clonedContext.messages[injectionIndex];
+
+ clonedContext.messages[injectionIndex] = {
+ ...message,
+ content:
+ typeof message.content === 'string'
+ ? `${stableContent}\n\n${message.content}`
+ : [{ text: stableContent, type: 'text' }, ...message.content],
+ updatedAt: Date.now(),
+ };
+ }
+ }
+
+ if (tailContent) {
+ const lastIndex = clonedContext.messages.length - 1;
+ const lastMessage = clonedContext.messages[lastIndex];
+
+ if (lastMessage?.role === 'user' && lastMessage.meta?.virtualLastUser === true) {
+ clonedContext.messages[lastIndex] = {
+ ...lastMessage,
+ content:
+ typeof lastMessage.content === 'string'
+ ? `${lastMessage.content}\n\n${tailContent}`
+ : [...lastMessage.content, { text: tailContent, type: 'text' }],
+ updatedAt: Date.now(),
+ };
+ } else {
+ const now = Date.now();
+ clonedContext.messages.push({
+ content: tailContent,
+ createdAt: now,
+ id: `virtual-last-user-${this.name}-${now}`,
+ meta: { injectType: this.name, virtualLastUser: true },
+ role: 'user',
+ updatedAt: now,
+ });
+ }
+ }
+
+ return this.markAsExecuted(clonedContext);
+ }
+}
diff --git a/packages/context-engine/src/providers/__tests__/RuntimeAdditionalContextProvider.test.ts b/packages/context-engine/src/providers/__tests__/RuntimeAdditionalContextProvider.test.ts
new file mode 100644
index 00000000000..0c521e05722
--- /dev/null
+++ b/packages/context-engine/src/providers/__tests__/RuntimeAdditionalContextProvider.test.ts
@@ -0,0 +1,160 @@
+import type { RuntimeAdditionalContextFragment } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import type { PipelineContext } from '../../types';
+import { RuntimeAdditionalContextProvider } from '../RuntimeAdditionalContextProvider';
+
+const createContext = (): PipelineContext => ({
+ initialState: { messages: [], model: 'test-model', provider: 'test-provider' },
+ isAborted: false,
+ messages: [{ content: 'Hello', role: 'user' }],
+ metadata: { maxTokens: 4000, model: 'test-model' },
+});
+
+describe('RuntimeAdditionalContextProvider', () => {
+ it('renders ordered sections with format-specific escaping', async () => {
+ const fragments: RuntimeAdditionalContextFragment[] = [
+ {
+ content: {
+ sections: [
+ { format: 'json', tag: 'data', value: { markup: '<value>' } },
+ { format: 'compact_json', tag: 'tools', value: ['read', 'write'] },
+ { format: 'text', tag: 'instruction', value: 'Use <data> & finish.' },
+ ],
+ type: 'sections',
+ },
+ placement: 'virtual_tail',
+ wrapper: {
+ attributes: { label: 'a"<&>' },
+ tag: 'context',
+ },
+ },
+ {
+ content: { text: 'Second & final.', type: 'text' },
+ placement: 'virtual_tail',
+ wrapper: { tag: 'note' },
+ },
+ ];
+
+ const result = await new RuntimeAdditionalContextProvider({
+ additionalContexts: fragments,
+ }).process(createContext());
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[0]).toEqual({ content: 'Hello', role: 'user' });
+ expect(result.messages.at(-1)?.content).toBe(
+ [
+ '<context label="a&quot;&lt;&amp;&gt;">',
+ '<data>',
+ '{',
+ ' "markup": "\\u003cvalue\\u003e"',
+ '}',
+ '</data>',
+ '<tools>',
+ '["read","write"]',
+ '</tools>',
+ '<instruction>Use &lt;data&gt; &amp; finish.</instruction>',
+ '</context>',
+ '',
+ '<note>',
+ 'Second &amp; final.',
+ '</note>',
+ ].join('\n'),
+ );
+ });
+
+ it('preserves fragment order and skips injection without fragments', async () => {
+ const fragments: RuntimeAdditionalContextFragment[] = [
+ {
+ content: { text: 'tail-one', type: 'text' },
+ placement: 'virtual_tail',
+ wrapper: { tag: 'one' },
+ },
+ {
+ content: { text: 'stable', type: 'text' },
+ placement: 'stable_prefix',
+ wrapper: { tag: 'stable' },
+ },
+ {
+ content: { text: 'tail-two', type: 'text' },
+ placement: 'virtual_tail',
+ wrapper: { tag: 'two' },
+ },
+ ];
+
+ const result = await new RuntimeAdditionalContextProvider({
+ additionalContexts: fragments,
+ }).process(createContext());
+ const emptyResult = await new RuntimeAdditionalContextProvider({
+ additionalContexts: [],
+ }).process(createContext());
+ const undefinedResult = await new RuntimeAdditionalContextProvider({}).process(createContext());
+
+ expect(result.messages).toHaveLength(3);
+ expect(result.messages[0]).toMatchObject({
+ content: '<stable>\nstable\n</stable>',
+ meta: { systemInjection: true },
+ role: 'user',
+ });
+ expect(result.messages[1]).toEqual({ content: 'Hello', role: 'user' });
+ expect(result.messages.at(-1)?.content).toBe(
+ '<one>\ntail-one\n</one>\n\n<two>\ntail-two\n</two>',
+ );
+ expect(emptyResult.messages).toEqual(createContext().messages);
+ expect(undefinedResult.messages).toEqual(createContext().messages);
+ });
+
+ it('reuses an existing synthetic tail user message', async () => {
+ const result = await new RuntimeAdditionalContextProvider({
+ additionalContexts: [
+ {
+ content: { text: 'Current stage.', type: 'text' },
+ placement: 'virtual_tail',
+ wrapper: { tag: 'stage_context' },
+ },
+ ],
+ }).process({
+ ...createContext(),
+ messages: [
+ { content: 'Hello', role: 'user' },
+ {
+ content: 'Existing hint',
+ meta: { injectType: 'OtherProvider', virtualLastUser: true },
+ role: 'user',
+ },
+ ],
+ });
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages.at(-1)?.content).toBe(
+ 'Existing hint\n\n<stage_context>\nCurrent stage.\n</stage_context>',
+ );
+ });
+
+ it('prepends stable content to the shared system injection message', async () => {
+ const result = await new RuntimeAdditionalContextProvider({
+ additionalContexts: [
+ {
+ content: { text: 'Graph contract.', type: 'text' },
+ placement: 'stable_prefix',
+ wrapper: { tag: 'graph_node_context' },
+ },
+ ],
+ }).process({
+ ...createContext(),
+ messages: [
+ {
+ content: 'Existing stable context',
+ meta: { systemInjection: true },
+ role: 'user',
+ },
+ { content: 'Hello', role: 'user' },
+ ],
+ });
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.messages[0].content).toBe(
+ '<graph_node_context>\nGraph contract.\n</graph_node_context>\n\nExisting stable context',
+ );
+ });
+});
diff --git a/packages/context-engine/src/providers/index.ts b/packages/context-engine/src/providers/index.ts
index 4a2a77db5b0..11c8c90f551 100644
--- a/packages/context-engine/src/providers/index.ts
+++ b/packages/context-engine/src/providers/index.ts
@@ -27,6 +27,7 @@ export { OnboardingSyntheticStateInjector } from './OnboardingSyntheticStateInje
export { PageEditorContextInjector } from './PageEditorContextInjector';
export { PageSelectionsInjector } from './PageSelectionsInjector';
export { PlanInjector } from './PlanInjector';
+export { RuntimeAdditionalContextProvider } from './RuntimeAdditionalContextProvider';
export {
formatSelectedSkills,
formatSelectedSkillsContext,
@@ -102,6 +103,7 @@ export type {
export type { PageEditorContextInjectorConfig } from './PageEditorContextInjector';
export type { PageSelectionsInjectorConfig } from './PageSelectionsInjector';
export type { Plan, PlanInjectorConfig } from './PlanInjector';
+export type { RuntimeAdditionalContextProviderConfig } from './RuntimeAdditionalContextProvider';
export type { SelectedSkillInjectorConfig } from './SelectedSkillInjector';
export type { SelectedToolInjectorConfig } from './SelectedToolInjector';
export type { SkillContextProviderConfig, SkillMeta } from './SkillContextProvider';
diff --git a/packages/types/src/agent/index.ts b/packages/types/src/agent/index.ts
index a08753b8178..2b071b24b43 100644
--- a/packages/types/src/agent/index.ts
+++ b/packages/types/src/agent/index.ts
@@ -8,4 +8,5 @@ export * from './heterogeneousAgent';
export * from './item';
export * from './modelSelection';
export * from './pluginConfig';
+export * from './runtimeAdditionalContext';
export * from './tts';
diff --git a/packages/types/src/agent/runtimeAdditionalContext.ts b/packages/types/src/agent/runtimeAdditionalContext.ts
new file mode 100644
index 00000000000..b47abc8aaba
--- /dev/null
+++ b/packages/types/src/agent/runtimeAdditionalContext.ts
@@ -0,0 +1,34 @@
+export type RuntimeAdditionalContextValue =
+ | boolean
+ | null
+ | number
+ | string
+ | readonly RuntimeAdditionalContextValue[]
+ | RuntimeAdditionalContextObject;
+
+export interface RuntimeAdditionalContextObject {
+ readonly [key: string]: RuntimeAdditionalContextValue;
+}
+
+export interface RuntimeAdditionalContextSection {
+ readonly format: 'compact_json' | 'json' | 'text';
+ readonly tag: string;
+ readonly value: RuntimeAdditionalContextValue;
+}
+
+export interface RuntimeAdditionalContextFragment {
+ readonly content:
+ | {
+ readonly sections: readonly RuntimeAdditionalContextSection[];
+ readonly type: 'sections';
+ }
+ | {
+ readonly text: string;
+ readonly type: 'text';
+ };
+ readonly placement: 'stable_prefix' | 'virtual_tail';
+ readonly wrapper: {
+ readonly attributes?: Readonly<Record<string, string>>;
+ readonly tag: string;
+ };
+}
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 25b7db22877..70895da8703 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -12,6 +12,7 @@ export * from './format';
export * from './imageMimeType';
export * from './imageToBase64';
export * from './jina';
+export * from './json';
export * from './keyboard';
export * from './merge';
export * from './mimeType';
diff --git a/packages/utils/src/json.test.ts b/packages/utils/src/json.test.ts
new file mode 100644
index 00000000000..87b36e1d1f8
--- /dev/null
+++ b/packages/utils/src/json.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+
+import { safeJsonStringify, toJsonSafe } from './json';
+
+describe('json utilities', () => {
+ it('stringifies bigint and circular references', () => {
+ const value: Record<string, unknown> = { count: 1n };
+ value.self = value;
+
+ expect(safeJsonStringify(value)).toBe('{"count":"1","self":"[Circular]"}');
+ });
+
+ it('converts unknown values to plain JSON-safe data', () => {
+ expect(
+ toJsonSafe({
+ dropped: undefined,
+ items: [undefined, () => {}, Symbol('value'), Number.NaN, Number.POSITIVE_INFINITY],
+ nested: { count: 1n },
+ }),
+ ).toEqual({
+ items: [null, null, null, null, null],
+ nested: { count: '1' },
+ });
+ expect(toJsonSafe(undefined)).toBeNull();
+ });
+
+ it('returns a JSON-safe fallback when serialization fails', () => {
+ const value = {};
+ Object.defineProperty(value, 'broken', {
+ enumerable: true,
+ get: () => {
+ throw new Error('broken getter');
+ },
+ });
+
+ expect(toJsonSafe(value)).toEqual({
+ message: 'Failed to serialize JSON value',
+ name: 'JsonSerializationFailure',
+ });
+ });
+});
diff --git a/packages/utils/src/json.ts b/packages/utils/src/json.ts
new file mode 100644
index 00000000000..38a2bda79cf
--- /dev/null
+++ b/packages/utils/src/json.ts
@@ -0,0 +1,36 @@
+export type JsonSafeValue =
+ boolean | null | number | string | readonly JsonSafeValue[] | JsonSafeObject;
+
+export interface JsonSafeObject {
+ readonly [key: string]: JsonSafeValue;
+}
+
+export const safeJsonStringify = (value: unknown): string => {
+ const seen = new WeakSet<object>();
+
+ try {
+ return (
+ JSON.stringify(value, (_key, item) => {
+ if (typeof item === 'bigint') return item.toString();
+ if (typeof item === 'object' && item !== null) {
+ if (seen.has(item as object)) return '[Circular]';
+ seen.add(item as object);
+ }
+ return item;
+ }) ?? 'null'
+ );
+ } catch {
+ return JSON.stringify({
+ message: 'Failed to serialize JSON value',
+ name: 'JsonSerializationFailure',
+ });
+ }
+};
+
+export const toJsonSafe = (value: unknown): JsonSafeValue => {
+ try {
+ return JSON.parse(safeJsonStringify(value)) as JsonSafeValue;
+ } catch {
+ return String(value);
+ }
+};
diff --git a/src/services/chat/index.ts b/src/services/chat/index.ts
index 7fcc5da408b..19ba6a65c82 100644
--- a/src/services/chat/index.ts
+++ b/src/services/chat/index.ts
@@ -15,6 +15,7 @@ import { AgentRuntimeError } from '@lobechat/model-runtime/utils/createError';
import {
ChatErrorType,
getDisabledPluginIds,
+ type RuntimeAdditionalContextFragment,
type RuntimeInitialContext,
type RuntimeStepContext,
type TracePayload,
@@ -73,6 +74,7 @@ const providersWithDeploymentName = new Set<string>([
ModelProvider.VolcengineCodingPlan,
]);
export interface GetChatCompletionPayload extends Partial<Omit<ChatStreamPayload, 'messages'>> {
+ additionalContexts?: readonly RuntimeAdditionalContextFragment[];
agentId?: string;
groupId?: string;
messages: UIChatMessage[];
@@ -137,6 +139,7 @@ class ChatService {
messages,
agentId,
groupId,
+ additionalContexts,
topicId,
resolvedAgentConfig,
...params
@@ -300,6 +303,7 @@ class ChatService {
enableHistoryCount: chatConfig.enableHistoryCount,
enableUserMemories,
groupId,
+ additionalContexts,
// historyCount is number of history messages; add 1 for current user message
historyCount: (chatConfig.historyCount ?? 20) + 1,
// Page editor context from agent runtime
diff --git a/src/services/chat/mecha/contextEngineering.ts b/src/services/chat/mecha/contextEngineering.ts
index 7d54fd272f8..f263aa441bd 100644
--- a/src/services/chat/mecha/contextEngineering.ts
+++ b/src/services/chat/mecha/contextEngineering.ts
@@ -41,6 +41,7 @@ import { historySummaryPrompt } from '@lobechat/prompts';
import {
getActivePluginIds,
type OpenAIChatMessage,
+ type RuntimeAdditionalContextFragment,
type RuntimeInitialContext,
type RuntimeStepContext,
type UIChatMessage,
@@ -85,6 +86,8 @@ import { resolveClientSkills } from './skillEngineering';
const log = debug('context-engine:contextEngineering');
interface ContextEngineeringContext {
+ /** Agent-materialized presentation contexts for this LLM call */
+ additionalContexts?: readonly RuntimeAdditionalContextFragment[];
/** Agent Builder context for injecting current agent info */
agentBuilderContext?: AgentBuilderContext;
agentDocuments?: AgentContextDocument[];
@@ -137,6 +140,7 @@ interface ContextEngineeringContext {
// REVIEW: Maybe we can constrain identity, preference, exp to reorder or trim the context instead of passing everything in
export const contextEngineering = async ({
+ additionalContexts,
messages = [],
manifests,
tools,
@@ -696,6 +700,7 @@ export const contextEngineering = async ({
// Create MessagesEngine with injected dependencies
const engine = new MessagesEngine({
+ additionalContexts,
// Agent configuration
enableHistoryCount,
formatHistorySummary: historySummaryPrompt,
diff --git a/src/store/chat/agents/transports/ClientContextBuilder.test.ts b/src/store/chat/agents/transports/ClientContextBuilder.test.ts
index 9b9c18d1c64..550bff5dc76 100644
--- a/src/store/chat/agents/transports/ClientContextBuilder.test.ts
+++ b/src/store/chat/agents/transports/ClientContextBuilder.test.ts
@@ -88,6 +88,13 @@ describe('ClientContextBuilder', () => {
});
const userMessage = { content: 'Question', id: 'user-1', role: 'user' as const };
const assistantMessage = { content: '', id: 'assistant-1', role: 'assistant' as const };
+ const additionalContexts = [
+ {
+ content: { text: 'Inspect the question.', type: 'text' as const },
+ placement: 'stable_prefix' as const,
+ wrapper: { tag: 'inspection' },
+ },
+ ];
const state = AgentRuntime.createInitialState({
messages: [userMessage],
operationId: 'operation-1',
@@ -106,6 +113,7 @@ describe('ClientContextBuilder', () => {
messages: [userMessage, assistantMessage],
model: 'test-model',
provider: 'test-provider',
+ additionalContexts,
tools: [],
} as any,
provider: 'test-provider',
@@ -122,6 +130,7 @@ describe('ClientContextBuilder', () => {
enabledToolIds: ['dynamic-search'],
tools: [activatedTool],
}),
+ additionalContexts,
}),
expect.any(Object),
);
@@ -132,5 +141,8 @@ describe('ClientContextBuilder', () => {
expect(result.modelParameters).toMatchObject({
params: { model: 'test-model', provider: 'test-provider', tools: [activatedTool] },
});
+ expect(
+ (result.modelParameters as { params: Record<string, unknown> }).params,
+ ).not.toHaveProperty('additionalContexts');
});
});
diff --git a/src/store/chat/agents/transports/ClientContextBuilder.ts b/src/store/chat/agents/transports/ClientContextBuilder.ts
index 23ac3c255ad..c0d6487b541 100644
--- a/src/store/chat/agents/transports/ClientContextBuilder.ts
+++ b/src/store/chat/agents/transports/ClientContextBuilder.ts
@@ -76,6 +76,7 @@ export class ClientContextBuilder implements ContextBuilder {
const prepared = await chatService.buildAssistantMessageContext(
{
agentId: effectiveAgentId || undefined,
+ additionalContexts: input.payload.additionalContexts,
groupId,
messages,
model: input.model,