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(agent): move Graph Agent config from chatConfig to agencyConfig (#18419)

Arvin Xu9396a5b31567
diff --git a/apps/cli/src/commands/agent.test.ts b/apps/cli/src/commands/agent.test.ts
index d6a7fa7244f..4094c0bcb52 100644
--- a/apps/cli/src/commands/agent.test.ts
+++ b/apps/cli/src/commands/agent.test.ts
@@ -346,7 +346,7 @@ describe('agent command', () => {
expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({
agentId: 'a1',
value: {
- chatConfig: {
+ agencyConfig: {
enableGraphMode: true,
graph,
},
@@ -386,7 +386,7 @@ describe('agent command', () => {
await program.parseAsync(['node', 'test', 'agent', 'edit', 'a1', '--graph-file', graphFile]);
expect(log.error).toHaveBeenCalledWith(
- expect.stringContaining('Failed to read graph JSON: Invalid ReasoningGraph'),
+ expect.stringContaining('Failed to read graph JSON: Invalid AgentGraph'),
);
expect(exitSpy).toHaveBeenCalledWith(1);
expect(mockTrpcClient.agent.updateAgentConfig.mutate).not.toHaveBeenCalled();
@@ -509,9 +509,11 @@ describe('agent command', () => {
});
});
- it('should merge graph flags into a chatConfig supplied by --config-file', async () => {
+ it('should merge graph flags into an agencyConfig supplied by --config-file', async () => {
mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});
- const configFile = await writeGraphFixture({ chatConfig: { historyCount: 12 } });
+ const configFile = await writeGraphFixture({
+ agencyConfig: { modelSelectionPolicy: 'member' },
+ });
const program = createProgram();
await program.parseAsync([
@@ -527,7 +529,45 @@ describe('agent command', () => {
expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({
agentId: 'a1',
- value: { chatConfig: { enableGraphMode: true, historyCount: 12 } },
+ value: { agencyConfig: { enableGraphMode: true, modelSelectionPolicy: 'member' } },
+ });
+ });
+
+ it('should merge graph flags into an agencyConfig supplied by --agency-config-file', async () => {
+ mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});
+ const agencyConfigFile = await writeGraphFixture({
+ executionTarget: 'local',
+ });
+
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'agent',
+ 'edit',
+ 'a1',
+ '--agency-config-file',
+ agencyConfigFile,
+ '--graph-file',
+ await writeGraphFixture({
+ edges: [{ from: '__root__', instruction: 'Write the final answer.', to: 'answer' }],
+ fields: {},
+ name: 'answer-graph',
+ nodes: { answer: { type: 'llm' } },
+ terminal: 'answer',
+ }),
+ '--enable-graph',
+ ]);
+
+ expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({
+ agentId: 'a1',
+ value: {
+ agencyConfig: {
+ executionTarget: 'local',
+ enableGraphMode: true,
+ graph: expect.any(Object),
+ },
+ },
});
});
diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.ts
index 6d2fcb37658..b4143ef749c 100644
--- a/apps/cli/src/commands/agent.ts
+++ b/apps/cli/src/commands/agent.ts
@@ -1,6 +1,6 @@
import { readFile } from 'node:fs/promises';
-import { ReasoningGraphSchema } from '@lobechat/types';
+import { AgentGraphSchema } from '@lobechat/types';
import { type Command, InvalidArgumentError } from 'commander';
import pc from 'picocolors';
@@ -21,12 +21,12 @@ import { registerAgentSpaceFsCommand } from './agent/spaceFs';
const readGraphConfig = async (graphFile: string): Promise<unknown> => {
const content = await readFile(graphFile, 'utf8');
const graph = JSON.parse(content);
- const result = ReasoningGraphSchema.safeParse(graph);
+ const result = AgentGraphSchema.safeParse(graph);
if (!result.success) {
const issue = result.error.issues[0];
const path = issue?.path.length ? `${issue.path.join('.')}: ` : '';
- throw new Error(`Invalid ReasoningGraph: ${path}${issue?.message ?? 'unknown error'}`);
+ throw new Error(`Invalid AgentGraph: ${path}${issue?.message ?? 'unknown error'}`);
}
return result.data;
@@ -186,7 +186,7 @@ export function registerAgentCommand(program: Command) {
.option('-m, --model <model>', 'New model ID')
.option('-p, --provider <provider>', 'New provider ID')
.option('-s, --system-role <role>', 'New system role prompt')
- .option('--graph-file <path>', 'ReasoningGraph JSON file')
+ .option('--graph-file <path>', 'AgentGraph JSON file')
.option('--enable-graph', 'Enable graph runtime')
.option('--disable-graph', 'Disable graph runtime')
.option(
@@ -242,35 +242,40 @@ export function registerAgentCommand(program: Command) {
return;
}
- const chatConfig: Record<string, any> = {};
- if (options.enableGraph) chatConfig.enableGraphMode = true;
- if (options.disableGraph) chatConfig.enableGraphMode = false;
- if (options.graphFile) {
+ // agencyConfig is deep-merged server-side, so a nested key is removed by
+ // sending it as `null` (e.g. `{ "heterogeneousProvider": null }`); omitted keys are kept.
+ if (options.agencyConfigFile) {
try {
- chatConfig.graph = await readGraphConfig(options.graphFile);
+ value.agencyConfig = await readAgencyConfig(options.agencyConfigFile);
} catch (error) {
- log.error(`Failed to read graph JSON: ${(error as Error).message}`);
+ log.error(`Failed to read agencyConfig JSON: ${(error as Error).message}`);
process.exit(1);
return;
}
}
- // Merged, not replaced: `--config-file` may carry other chatConfig keys
- // and the graph flags should only override the ones they own.
- if (Object.keys(chatConfig).length > 0) {
- value.chatConfig = { ...(value.chatConfig as object | undefined), ...chatConfig };
- }
- // agencyConfig is deep-merged server-side, so a nested key is removed by
- // sending it as `null` (e.g. `{ "heterogeneousProvider": null }`); omitted keys are kept.
- if (options.agencyConfigFile) {
+ // Graph Agent flags live on the agency config (the agent's behavior
+ // body), not the chat config. Merged, not replaced: `--config-file` /
+ // `--agency-config-file` may carry other agencyConfig keys and the
+ // graph flags should only override the ones they own.
+ const graphAgencyConfig: Record<string, any> = {};
+ if (options.enableGraph) graphAgencyConfig.enableGraphMode = true;
+ if (options.disableGraph) graphAgencyConfig.enableGraphMode = false;
+ if (options.graphFile) {
try {
- value.agencyConfig = await readAgencyConfig(options.agencyConfigFile);
+ graphAgencyConfig.graph = await readGraphConfig(options.graphFile);
} catch (error) {
- log.error(`Failed to read agencyConfig JSON: ${(error as Error).message}`);
+ log.error(`Failed to read graph JSON: ${(error as Error).message}`);
process.exit(1);
return;
}
}
+ if (Object.keys(graphAgencyConfig).length > 0) {
+ value.agencyConfig = {
+ ...(value.agencyConfig as object | undefined),
+ ...graphAgencyConfig,
+ };
+ }
if (Object.keys(value).length === 0) {
log.error(
diff --git a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
index 6bd81ff5af0..250318b73e3 100644
--- a/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
+++ b/apps/server/src/services/agentRuntime/__tests__/executeStep.test.ts
@@ -1,6 +1,6 @@
// @vitest-environment node
import { GeneralChatAgent, GraphAgent } from '@lobechat/agent-runtime';
-import type { ReasoningGraph } from '@lobechat/types';
+import type { AgentGraph } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
import { createRuntimeExecutors } from '@/server/modules/AgentRuntime/RuntimeExecutors';
@@ -226,7 +226,7 @@ describe('AgentRuntimeService.executeStep - early exit on terminal state', () =>
name: 'answer-graph',
nodes: { answer: { type: 'llm' } },
terminal: 'answer',
- } satisfies ReasoningGraph;
+ } satisfies AgentGraph;
const service = new AgentRuntimeService({} as any, 'user-1', {
agentFactory: (config) => new GraphAgent({ ...config, graph }),
queueService: null,
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
index 2329946bfd9..52f7410cb33 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
@@ -250,7 +250,7 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
const agent = getLatestAgentFactory()({
agentConfig: {
- chatConfig: {
+ agencyConfig: {
enableGraphMode: true,
graph: minimalGraph,
},
@@ -266,7 +266,7 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
const agent = getLatestAgentFactory()({
agentConfig: {
- chatConfig: {
+ agencyConfig: {
enableGraphMode: true,
graph: { ...minimalGraph, edges: [] },
},
@@ -277,6 +277,22 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
expect(agent).toBeInstanceOf(GeneralChatAgent);
});
+ it('falls back to a legacy chatConfig graph snapshot', () => {
+ service = new AiAgentService(mockDb, userId);
+
+ const agent = getLatestAgentFactory()({
+ agentConfig: {
+ chatConfig: {
+ enableGraphMode: true,
+ graph: minimalGraph,
+ },
+ },
+ operationId: 'op-legacy-graph',
+ });
+
+ expect(agent).toBeInstanceOf(GraphAgent);
+ });
+
it('keeps an upstream runtime agent factory authoritative', () => {
const upstreamAgent = { runner: vi.fn() };
const upstreamFactory = vi.fn(() => upstreamAgent);
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index ace3261c783..6d50b76c4a6 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -77,12 +77,12 @@ import type {
WorkspaceInitResult,
} from '@lobechat/types';
import {
+ AgentGraphSchema,
buildHeteroExecArgs,
ChatErrorType,
getActivePluginIds,
getDisabledPluginIds,
getWorkingDirEffectivePath,
- ReasoningGraphSchema,
RequestTrigger,
resolveAgentAgencyConfig,
resolveAgentModelConfig,
@@ -224,9 +224,17 @@ const createGraphAwareAgentFactory =
}
const runtimeAgentConfig = config.agentConfig as LobeAgentConfig | undefined;
- const graph = runtimeAgentConfig?.chatConfig?.graph;
- if (runtimeAgentConfig?.chatConfig?.enableGraphMode && graph) {
- const graphResult = ReasoningGraphSchema.safeParse(graph);
+ // Graph Agent is an agency-level behavior: read from `agencyConfig`.
+ // Legacy rows stored the graph on `chatConfig` β€” fall back so existing
+ // agents keep running until their next write migrates them.
+ const agencyConfig = runtimeAgentConfig?.agencyConfig;
+ const legacyChatConfig = runtimeAgentConfig?.chatConfig as
+ (LobeAgentChatConfig & { enableGraphMode?: boolean; graph?: unknown }) | undefined;
+ const graph = agencyConfig?.graph ?? legacyChatConfig?.graph;
+ const graphEnabled =
+ (agencyConfig?.enableGraphMode ?? legacyChatConfig?.enableGraphMode) === true;
+ if (graphEnabled && graph) {
+ const graphResult = AgentGraphSchema.safeParse(graph);
if (graphResult.success) {
return new GraphAgent({ ...config, graph: graphResult.data });
diff --git a/packages/agent-runtime/src/agents/graph/GraphAgent.ts b/packages/agent-runtime/src/agents/graph/GraphAgent.ts
index 732d1f0c7f1..4f5642817ac 100644
--- a/packages/agent-runtime/src/agents/graph/GraphAgent.ts
+++ b/packages/agent-runtime/src/agents/graph/GraphAgent.ts
@@ -1,5 +1,5 @@
import { ToolNameResolver } from '@lobechat/context-engine';
-import type { AgentGraphEdge, AgentGraphNode, ReasoningGraph } from '@lobechat/types';
+import type { AgentGraph, AgentGraphEdge, AgentGraphNode } 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';
@@ -161,9 +161,9 @@ interface PromptObject {
*/
export class GraphAgent implements Agent {
private generalConfig: GeneralAgentConfig;
- private graph: ReasoningGraph;
+ private graph: AgentGraph;
- constructor(config: GeneralAgentConfig & { graph: ReasoningGraph }) {
+ constructor(config: GeneralAgentConfig & { graph: AgentGraph }) {
const { graph, ...generalConfig } = config;
this.graph = graph;
this.generalConfig = generalConfig;
diff --git a/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts b/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts
index 48ae23173e2..733792311d8 100644
--- a/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts
+++ b/packages/agent-runtime/src/agents/graph/__tests__/GraphAgent.test.ts
@@ -3,8 +3,8 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { ToolNameResolver } from '@lobechat/context-engine';
-import type { ReasoningGraph, RuntimeAdditionalContextFragment } from '@lobechat/types';
-import { AGENT_GRAPH_ROOT_NODE_ID, ReasoningGraphSchema } from '@lobechat/types';
+import type { AgentGraph, RuntimeAdditionalContextFragment } from '@lobechat/types';
+import { AGENT_GRAPH_ROOT_NODE_ID, AgentGraphSchema } from '@lobechat/types';
import { describe, expect, it } from 'vitest';
import type { AgentInstruction, AgentRuntimeContext, AgentState } from '../../../types';
@@ -129,11 +129,11 @@ const getGraphNodeSection = (instruction: AgentInstruction | AgentInstruction[],
const getGraphNodeContextText = (instruction: AgentInstruction | AgentInstruction[]) =>
JSON.stringify(getGraphNodeContext(instruction));
-const loadGoalLoopGraph = (): ReasoningGraph => {
+const loadGoalLoopGraph = (): AgentGraph => {
const graph = JSON.parse(
readFileSync(path.join(TEST_DIR, 'fixtures/goal-loop.graph.json'), 'utf8'),
);
- const result = ReasoningGraphSchema.safeParse(graph);
+ const result = AgentGraphSchema.safeParse(graph);
if (!result.success) {
throw new Error(JSON.stringify(result.error.format(), null, 2));
@@ -142,7 +142,7 @@ const loadGoalLoopGraph = (): ReasoningGraph => {
return result.data;
};
-const parseGraph = (graph: unknown) => ReasoningGraphSchema.safeParse(graph);
+const parseGraph = (graph: unknown) => AgentGraphSchema.safeParse(graph);
describe('GraphAgent', () => {
describe('schema', () => {
@@ -623,7 +623,7 @@ describe('GraphAgent', () => {
it('should render raw fallback context once when declared input fields are missing', async () => {
const goalLoopGraph = loadGoalLoopGraph();
- const graph: ReasoningGraph = {
+ const graph: AgentGraph = {
...goalLoopGraph,
edges: goalLoopGraph.edges.map((edge) =>
edge.from === 'plan'
@@ -1179,7 +1179,7 @@ describe('GraphAgent', () => {
});
it('should route by matching condition before default and fall back when condition misses', async () => {
- const graph: ReasoningGraph = {
+ const graph: AgentGraph = {
edges: [
{
from: AGENT_GRAPH_ROOT_NODE_ID,
@@ -1267,7 +1267,7 @@ describe('GraphAgent', () => {
});
it('should treat invalid condition schemas as no match and use the default edge', async () => {
- const graph: ReasoningGraph = {
+ const graph: AgentGraph = {
edges: [
{
from: AGENT_GRAPH_ROOT_NODE_ID,
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.ts
index 9200c55c7f4..e7807e26350 100644
--- a/packages/database/src/models/__tests__/agent.test.ts
+++ b/packages/database/src/models/__tests__/agent.test.ts
@@ -2826,7 +2826,7 @@ describe('AgentModel', () => {
});
});
- it('should replace an explicitly supplied reasoning graph', async () => {
+ it('should replace an explicitly supplied reasoning graph on agencyConfig', async () => {
const oldGraph = {
edges: [],
entry: 'legacy',
@@ -2846,17 +2846,78 @@ describe('AgentModel', () => {
const [agent] = await serverDB
.insert(agents)
.values({
- chatConfig: { enableGraphMode: true, graph: oldGraph },
+ agencyConfig: { enableGraphMode: true, graph: oldGraph },
title: 'Graph Agent',
userId,
} as NewAgent)
.returning();
- await agentModel.updateConfig(agent.id, { chatConfig: { graph } } as any);
+ await agentModel.updateConfig(agent.id, { agencyConfig: { graph } } as any);
const result = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
- expect(result?.chatConfig).toEqual({ enableGraphMode: true, graph });
+ expect(result?.agencyConfig).toEqual({ enableGraphMode: true, graph });
+ });
+
+ it('should migrate a legacy chatConfig graph to agencyConfig on write', async () => {
+ const graph = {
+ edges: [{ from: '__root__', instruction: 'Complete the task.', to: 'work' }],
+ fields: {},
+ name: 'compiled-graph',
+ nodes: { work: { type: 'agent' } },
+ terminal: 'work',
+ };
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ chatConfig: { enableGraphMode: true, graph },
+ title: 'Legacy Graph Agent',
+ userId,
+ } as NewAgent)
+ .returning();
+
+ // A legacy client still writing graph through chatConfig must be
+ // forwarded onto agencyConfig so the row migrates on the next write.
+ await agentModel.updateConfig(agent.id, {
+ chatConfig: { enableGraphMode: true, graph } as any,
+ } as any);
+
+ const result = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
+
+ expect(result?.agencyConfig).toEqual({ enableGraphMode: true, graph });
+ expect(result?.chatConfig).not.toHaveProperty('graph');
+ expect(result?.chatConfig).not.toHaveProperty('enableGraphMode');
+ });
+
+ it('should let an explicit null agency graph clear a legacy chatConfig graph', async () => {
+ const graph = {
+ edges: [{ from: '__root__', instruction: 'Complete the task.', to: 'work' }],
+ fields: {},
+ name: 'compiled-graph',
+ nodes: { work: { type: 'agent' } },
+ terminal: 'work',
+ };
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ chatConfig: { enableGraphMode: true, graph },
+ title: 'Legacy Graph Agent',
+ userId,
+ } as NewAgent)
+ .returning();
+
+ // An explicit agency-level null must be authoritative: it clears the
+ // graph AND removes the legacy chatConfig fields, otherwise the runtime
+ // fallback would resurrect the old snapshot.
+ await agentModel.updateConfig(agent.id, {
+ agencyConfig: { graph: null },
+ } as any);
+
+ const result = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });
+
+ expect(result?.agencyConfig?.graph).toBeNull();
+ expect(result?.chatConfig).not.toHaveProperty('graph');
+ expect(result?.chatConfig).not.toHaveProperty('enableGraphMode');
});
it('should delete params field when value is undefined', async () => {
diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.ts
index e953a73b974..f39929324e3 100644
--- a/packages/database/src/models/agent.ts
+++ b/packages/database/src/models/agent.ts
@@ -1444,12 +1444,42 @@ export class AgentModel {
}
}
- // A ReasoningGraph is a complete executable document, not a partial chatConfig patch.
- if (data.chatConfig && Object.hasOwn(data.chatConfig, 'graph')) {
- mergedValue.chatConfig = {
- ...mergedValue.chatConfig,
- graph: data.chatConfig.graph,
- } as AgentItem['chatConfig'];
+ // A AgentGraph is a complete executable document, not a partial config
+ // patch β€” replace it wholesale instead of deep-merging. The Graph Agent
+ // (agencyConfig.graph) is the agent's behavior body; legacy clients may
+ // still send `chatConfig.graph`, so write it through to `agencyConfig.graph`
+ // (and forward the switch) to migrate the row on the next write.
+ if (data.agencyConfig && Object.hasOwn(data.agencyConfig, 'graph')) {
+ mergedValue.agencyConfig = {
+ ...mergedValue.agencyConfig,
+ graph: data.agencyConfig.graph,
+ } as AgentItem['agencyConfig'];
+ // An explicit agency-level graph β€” including `null` to clear it β€” takes
+ // ownership of the graph: drop the legacy chatConfig fields so the
+ // runtime's `??` fallback cannot resurrect an old snapshot.
+ if (mergedValue.chatConfig) {
+ const {
+ graph: _legacyGraph,
+ enableGraphMode: _legacyEnableGraphMode,
+ ...restChatConfig
+ } = mergedValue.chatConfig as Record<string, unknown>;
+ mergedValue.chatConfig = restChatConfig as AgentItem['chatConfig'];
+ }
+ } else if (data.chatConfig && Object.hasOwn(data.chatConfig, 'graph')) {
+ const legacyChatConfig = data.chatConfig as Record<string, unknown>;
+ mergedValue.agencyConfig = {
+ ...mergedValue.agencyConfig,
+ graph: legacyChatConfig.graph,
+ ...(Object.hasOwn(legacyChatConfig, 'enableGraphMode') && {
+ enableGraphMode: legacyChatConfig.enableGraphMode,
+ }),
+ } as AgentItem['agencyConfig'];
+ const {
+ graph: _legacyGraph,
+ enableGraphMode: _legacyEnableGraphMode,
+ ...restChatConfig
+ } = (mergedValue.chatConfig ?? {}) as Record<string, unknown>;
+ mergedValue.chatConfig = restChatConfig as AgentItem['chatConfig'];
}
// Apply the processed parameters
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 7f98888f9af..53c42bd3803 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -1138,9 +1138,9 @@ export default {
'Route this agent through the graph runtime using the snapshot stored below.',
'settingGraphRuntime.enabled.title': 'Enable Graph Runtime',
'settingGraphRuntime.snapshot.desc':
- 'Paste the complete ReasoningGraph JSON snapshot. It is stored with this agent and used directly at runtime.',
+ 'Paste the complete AgentGraph JSON snapshot. It is stored with this agent and used directly at runtime.',
'settingGraphRuntime.snapshot.placeholder':
- 'Paste a ReasoningGraph JSON snapshot, for example: {"name":"...","nodes":{...},"terminal":"...","edges":[]}',
+ 'Paste a AgentGraph JSON snapshot, for example: {"name":"...","nodes":{...},"terminal":"...","edges":[]}',
'settingGraphRuntime.snapshot.title': 'Graph Snapshot',
'settingGraphRuntime.validation.invalidGraph': 'Invalid graph snapshot: {{error}}',
'settingGraphRuntime.validation.invalidJson': 'Graph snapshot must be valid JSON.',
diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.yml
index 52be945369a..482112ac5db 100644
--- a/packages/openapi/openapi.yml
+++ b/packages/openapi/openapi.yml
@@ -1542,49 +1542,14 @@ paths:
schema:
type: object
properties:
- avatar:
- anyOf:
- - type: string
- - type: "null"
- chatConfig:
+ agencyConfig:
anyOf:
- type: object
properties:
- disableContextCaching:
- anyOf:
- - type: boolean
- - type: "null"
- displayMode:
- anyOf:
- - type: string
- enum:
- - chat
- - docs
- - type: "null"
- enableCompressHistory:
- anyOf:
- - type: boolean
- - type: "null"
enableGraphMode:
anyOf:
- type: boolean
- type: "null"
- enableHistoryCount:
- anyOf:
- - type: boolean
- - type: "null"
- enableMaxTokens:
- anyOf:
- - type: boolean
- - type: "null"
- enableReasoning:
- anyOf:
- - type: boolean
- - type: "null"
- enableReasoningEffort:
- anyOf:
- - type: boolean
- - type: "null"
graph:
anyOf:
- type: object
@@ -1723,6 +1688,46 @@ paths:
- terminal
- edges
- type: "null"
+ - type: "null"
+ avatar:
+ anyOf:
+ - type: string
+ - type: "null"
+ chatConfig:
+ anyOf:
+ - type: object
+ properties:
+ disableContextCaching:
+ anyOf:
+ - type: boolean
+ - type: "null"
+ displayMode:
+ anyOf:
+ - type: string
+ enum:
+ - chat
+ - docs
+ - type: "null"
+ enableCompressHistory:
+ anyOf:
+ - type: boolean
+ - type: "null"
+ enableHistoryCount:
+ anyOf:
+ - type: boolean
+ - type: "null"
+ enableMaxTokens:
+ anyOf:
+ - type: boolean
+ - type: "null"
+ enableReasoning:
+ anyOf:
+ - type: boolean
+ - type: "null"
+ enableReasoningEffort:
+ anyOf:
+ - type: boolean
+ - type: "null"
historyCount:
anyOf:
- type: number
@@ -1941,49 +1946,14 @@ paths:
schema:
type: object
properties:
- avatar:
- anyOf:
- - type: string
- - type: "null"
- chatConfig:
+ agencyConfig:
anyOf:
- type: object
properties:
- disableContextCaching:
- anyOf:
- - type: boolean
- - type: "null"
- displayMode:
- anyOf:
- - type: string
- enum:
- - chat
- - docs
- - type: "null"
- enableCompressHistory:
- anyOf:
- - type: boolean
- - type: "null"
enableGraphMode:
anyOf:
- type: boolean
- type: "null"
- enableHistoryCount:
- anyOf:
- - type: boolean
- - type: "null"
- enableMaxTokens:
- anyOf:
- - type: boolean
- - type: "null"
- enableReasoning:
- anyOf:
- - type: boolean
- - type: "null"
- enableReasoningEffort:
- anyOf:
- - type: boolean
- - type: "null"
graph:
anyOf:
- type: object
@@ -2122,6 +2092,46 @@ paths:
- terminal
- edges
- type: "null"
+ - type: "null"
+ avatar:
+ anyOf:
+ - type: string
+ - type: "null"
+ chatConfig:
+ anyOf:
+ - type: object
+ properties:
+ disableContextCaching:
+ anyOf:
+ - type: boolean
+ - type: "null"
+ displayMode:
+ anyOf:
+ - type: string
+ enum:
+ - chat
+ - docs
+ - type: "null"
+ enableCompressHistory:
+ anyOf:
+ - type: boolean
+ - type: "null"
+ enableHistoryCount:
+ anyOf:
+ - type: boolean
+ - type: "null"
+ enableMaxTokens:
+ anyOf:
+ - type: boolean
+ - type: "null"
+ enableReasoning:
+ anyOf:
+ - type: boolean
+ - type: "null"
+ enableReasoningEffort:
+ anyOf:
+ - type: boolean
+ - type: "null"
historyCount:
anyOf:
- type: number
diff --git a/packages/openapi/src/helpers/public-fields.test.ts b/packages/openapi/src/helpers/public-fields.test.ts
index 3c7f30210c2..6924966fdd3 100644
--- a/packages/openapi/src/helpers/public-fields.test.ts
+++ b/packages/openapi/src/helpers/public-fields.test.ts
@@ -11,8 +11,9 @@ import {
} from './public-fields';
describe('public response field projections', () => {
- it('keeps the Agent contract at the documented 12-field allowlist', () => {
+ it('keeps the Agent contract at the documented 13-field allowlist', () => {
const projected = projectPublicAgent({
+ agencyConfig: null,
avatar: null,
chatConfig: null,
clientId: 'internal-client',
diff --git a/packages/openapi/src/helpers/public-fields.ts b/packages/openapi/src/helpers/public-fields.ts
index e2397728612..5022c9d97d0 100644
--- a/packages/openapi/src/helpers/public-fields.ts
+++ b/packages/openapi/src/helpers/public-fields.ts
@@ -27,6 +27,7 @@ const pickPublicFields = <T extends object, K extends readonly (keyof T)[]>(
};
export const PUBLIC_AGENT_FIELDS = [
+ 'agencyConfig',
'avatar',
'chatConfig',
'createdAt',
diff --git a/packages/openapi/src/services/agent.service.ts b/packages/openapi/src/services/agent.service.ts
index 897583105c9..53398b50637 100644
--- a/packages/openapi/src/services/agent.service.ts
+++ b/packages/openapi/src/services/agent.service.ts
@@ -87,6 +87,7 @@ export class AgentService extends BaseService {
// Prepare creation data
const newAgentData: NewAgent = {
accessedAt: new Date(),
+ agencyConfig: request.agencyConfig || null,
avatar: request.avatar || null,
chatConfig: request.chatConfig || null,
createdAt: new Date(),
@@ -154,6 +155,9 @@ export class AgentService extends BaseService {
// Only update fields actually provided in the request to avoid overwriting existing values with undefined
const updateData: Record<string, unknown> = { updatedAt: new Date() };
+ if (request.agencyConfig !== undefined) {
+ updateData.agencyConfig = request.agencyConfig ?? null;
+ }
if (request.avatar !== undefined) updateData.avatar = request.avatar ?? null;
if (request.chatConfig !== undefined) updateData.chatConfig = request.chatConfig ?? null;
if (request.description !== undefined) updateData.description = request.description ?? null;
diff --git a/packages/openapi/src/types/agent.type.ts b/packages/openapi/src/types/agent.type.ts
index d94b94b7ff7..576bfea5f05 100644
--- a/packages/openapi/src/types/agent.type.ts
+++ b/packages/openapi/src/types/agent.type.ts
@@ -1,5 +1,5 @@
-import type { LobeAgentChatConfig } from '@lobechat/types';
-import { ReasoningGraphSchema } from '@lobechat/types';
+import type { LobeAgentAgencyConfig, LobeAgentChatConfig } from '@lobechat/types';
+import { AgentGraphSchema } from '@lobechat/types';
import { z } from 'zod';
import type { PublicAgent, PublicFile, PublicKnowledgeBase } from '../helpers/public-fields';
@@ -11,6 +11,7 @@ import type { IPaginationQuery, PaginationQueryResponse } from './common.type';
* Create Agent request parameters
*/
export interface CreateAgentRequest {
+ agencyConfig?: Pick<LobeAgentAgencyConfig, 'enableGraphMode' | 'graph'>;
avatar?: string;
chatConfig?: LobeAgentChatConfig;
description?: string;
@@ -24,18 +25,22 @@ export interface CreateAgentRequest {
export type GetAgentsRequest = IPaginationQuery;
export const CreateAgentRequestSchema = z.object({
+ agencyConfig: z
+ .object({
+ enableGraphMode: z.boolean().nullish(),
+ graph: AgentGraphSchema.nullish(),
+ })
+ .nullish(),
avatar: z.string().nullish(),
chatConfig: z
.object({
disableContextCaching: z.boolean().nullish(),
displayMode: z.enum(['chat', 'docs']).nullish(),
enableCompressHistory: z.boolean().nullish(),
- enableGraphMode: z.boolean().nullish(),
enableHistoryCount: z.boolean().nullish(),
enableMaxTokens: z.boolean().nullish(),
enableReasoning: z.boolean().nullish(),
enableReasoningEffort: z.boolean().nullish(),
- graph: ReasoningGraphSchema.nullish(),
historyCount: z.number().nullish(),
reasoningBudgetToken: z.number().nullish(),
reasoningEffort: z.enum(['low', 'medium', 'high']).nullish(),
diff --git a/packages/sdk/src/generated/types.gen.ts b/packages/sdk/src/generated/types.gen.ts
index 5401d3bc45b..32e5a48389f 100644
--- a/packages/sdk/src/generated/types.gen.ts
+++ b/packages/sdk/src/generated/types.gen.ts
@@ -725,16 +725,8 @@ export type GetApiV1AgentsResponse = GetApiV1AgentsResponses[keyof GetApiV1Agent
export type PostApiV1AgentsData = {
body: {
- avatar?: string | null;
- chatConfig?: {
- disableContextCaching?: boolean | null;
- displayMode?: 'chat' | 'docs' | null;
- enableCompressHistory?: boolean | null;
+ agencyConfig?: {
enableGraphMode?: boolean | null;
- enableHistoryCount?: boolean | null;
- enableMaxTokens?: boolean | null;
- enableReasoning?: boolean | null;
- enableReasoningEffort?: boolean | null;
graph?: {
description?: string;
fields: {
@@ -783,6 +775,16 @@ export type PostApiV1AgentsData = {
to: string;
}>;
} | null;
+ } | null;
+ avatar?: string | null;
+ chatConfig?: {
+ disableContextCaching?: boolean | null;
+ displayMode?: 'chat' | 'docs' | null;
+ enableCompressHistory?: boolean | null;
+ enableHistoryCount?: boolean | null;
+ enableMaxTokens?: boolean | null;
+ enableReasoning?: boolean | null;
+ enableReasoningEffort?: boolean | null;
historyCount?: number | null;
reasoningBudgetToken?: number | null;
reasoningEffort?: 'low' | 'medium' | 'high' | null;
@@ -967,16 +969,8 @@ export type GetApiV1AgentsByIdResponse = GetApiV1AgentsByIdResponses[keyof GetAp
export type PatchApiV1AgentsByIdData = {
body: {
- avatar?: string | null;
- chatConfig?: {
- disableContextCaching?: boolean | null;
- displayMode?: 'chat' | 'docs' | null;
- enableCompressHistory?: boolean | null;
+ agencyConfig?: {
enableGraphMode?: boolean | null;
- enableHistoryCount?: boolean | null;
- enableMaxTokens?: boolean | null;
- enableReasoning?: boolean | null;
- enableReasoningEffort?: boolean | null;
graph?: {
description?: string;
fields: {
@@ -1025,6 +1019,16 @@ export type PatchApiV1AgentsByIdData = {
to: string;
}>;
} | null;
+ } | null;
+ avatar?: string | null;
+ chatConfig?: {
+ disableContextCaching?: boolean | null;
+ displayMode?: 'chat' | 'docs' | null;
+ enableCompressHistory?: boolean | null;
+ enableHistoryCount?: boolean | null;
+ enableMaxTokens?: boolean | null;
+ enableReasoning?: boolean | null;
+ enableReasoningEffort?: boolean | null;
historyCount?: number | null;
reasoningBudgetToken?: number | null;
reasoningEffort?: 'low' | 'medium' | 'high' | null;
diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.ts
index c1850c117e9..73c5be9bd48 100644
--- a/packages/types/src/agent/agencyConfig.ts
+++ b/packages/types/src/agent/agencyConfig.ts
@@ -1,5 +1,6 @@
import type { WorkingDirConfigValue } from '../device';
import type { LobeAgentChatConfig } from './chatConfig';
+import type { AgentGraph } from './graph';
import { hasAnyCliFlag, hasCliConfigKey, hasCliFlag } from './heteroCliArgs';
import type { HeterogeneousAgentType, LocalHeterogeneousAgentType } from './heterogeneousAgent';
import {
@@ -601,6 +602,17 @@ export interface LobeAgentAgencyConfig {
* Required when `executionTarget === 'device'`.
*/
boundDeviceId?: string;
+ /**
+ * Whether to route this agent through a graph-style orchestration runtime
+ * (Graph Agent). Undefined means the agent uses the default runtime path.
+ *
+ * The graph is the agent's behavior definition β€” node policies, routing
+ * conditions and data contracts β€” so it lives on the agency config (how the
+ * agent behaves and executes) rather than the chat config (per-session
+ * preferences). This lets an agent evolve its own behavior by evolving its
+ * graph nodes.
+ */
+ enableGraphMode?: boolean;
/**
* Execution target for the hetero agent. When omitted, resolves to a
* platform default: `'local'` on desktop and `'none'` on web.
@@ -612,6 +624,13 @@ export interface LobeAgentAgencyConfig {
* a device.
*/
executionTargetSelectionPolicy?: ExecutionTargetSelectionPolicy;
+ /**
+ * Graph Agent behavior definition. The `AgentGraph` snapshot describing
+ * nodes, edges, field contracts and routing conditions for graph-style
+ * orchestration. Together with `enableGraphMode`, this is the agent's
+ * behavior body β€” one graph is one agent.
+ */
+ graph?: null | AgentGraph;
heterogeneousProvider?: HeterogeneousProviderConfig;
/**
* Confine the run's shell commands to the device sandbox. A *modifier* on
diff --git a/packages/types/src/agent/chatConfig.ts b/packages/types/src/agent/chatConfig.ts
index 4fd5f1231e2..f0fe2ad5881 100644
--- a/packages/types/src/agent/chatConfig.ts
+++ b/packages/types/src/agent/chatConfig.ts
@@ -4,8 +4,6 @@ import type { SearchMode } from '../search';
import type { TopicGroupMode } from '../topic';
import type { UserMemoryEffort } from '../user/settings/memory';
import type { RuntimeEnvConfig } from './agentConfig';
-import type { ReasoningGraph } from './graph';
-import { ReasoningGraphSchema } from './graph';
export interface WorkingModel {
model: string;
@@ -72,11 +70,6 @@ export interface LobeAgentChatConfig extends AgentMemoryChatConfig, AgentSelfIte
*/
enableContextCompression?: boolean;
enableFollowUpChips?: boolean;
- /**
- * Whether to route this agent through a graph-style orchestration runtime.
- * Undefined means the agent uses the default runtime path.
- */
- enableGraphMode?: boolean;
/**
* Enable historical message count
*/
@@ -101,11 +94,6 @@ export interface LobeAgentChatConfig extends AgentMemoryChatConfig, AgentSelfIte
gpt5_2ReasoningEffort?: 'none' | 'low' | 'medium' | 'high' | 'xhigh';
gpt5_6ReasoningEffort?: 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
gpt5ReasoningEffort?: 'minimal' | 'low' | 'medium' | 'high';
- /**
- * Graph-style orchestration runtime definition. Stored in chat config to avoid
- * a dedicated agent table column while keeping eval-run snapshots intact.
- */
- graph?: null | ReasoningGraph;
grok4_3ReasoningEffort?: 'none' | 'low' | 'medium' | 'high';
grok4_5ReasoningEffort?: 'low' | 'medium' | 'high';
grok4_6ReasoningEffort?: 'low' | 'medium' | 'high' | 'xhigh';
@@ -252,9 +240,7 @@ export const AgentChatConfigSchema = z
enableAutoScrollOnStreaming: z.boolean().optional(),
enableCompressHistory: z.boolean().optional(),
enableContextCompression: z.boolean().optional(),
- enableGraphMode: z.boolean().optional(),
enableFollowUpChips: z.boolean().optional(),
- graph: ReasoningGraphSchema.nullish(),
enableHistoryCount: z.boolean().optional(),
enableMaxTokens: z.boolean().optional(),
enableReasoning: z.boolean().optional(),
diff --git a/packages/types/src/agent/graph.ts b/packages/types/src/agent/graph.ts
index bc44bd0398f..52175559a5a 100644
--- a/packages/types/src/agent/graph.ts
+++ b/packages/types/src/agent/graph.ts
@@ -4,7 +4,9 @@ import { z } from 'zod';
export const AGENT_GRAPH_ROOT_NODE_ID = '__root__';
/**
- * Serializable reasoning graph snapshot stored on agent config.
+ * Serializable Agent Graph snapshot stored on agent config.
+ * One graph is one Graph Agent: the behavior body (node policies, routing
+ * conditions and data contracts) that the graph runtime executes.
* Kept package-local so shared config types don't depend on runtime packages.
*/
export type AgentGraphNode =
@@ -53,7 +55,7 @@ export interface AgentGraphEdge {
to: string;
}
-export interface ReasoningGraph {
+export interface AgentGraph {
description?: string;
edges: AgentGraphEdge[];
fields: Record<string, AgentGraphField>;
@@ -136,7 +138,7 @@ const findSchemaDescriptionPath = (
}
};
-export const ReasoningGraphSchema: z.ZodType<ReasoningGraph> = z
+export const AgentGraphSchema: z.ZodType<AgentGraph> = z
.object({
description: z.string().optional(),
fields: z.record(z.string(), AgentGraphFieldSchema),
diff --git a/src/features/AgentSetting/AgentGraphRuntime/index.tsx b/src/features/AgentSetting/AgentGraphRuntime/index.tsx
index d99c845ee7f..436e932cbad 100644
--- a/src/features/AgentSetting/AgentGraphRuntime/index.tsx
+++ b/src/features/AgentSetting/AgentGraphRuntime/index.tsx
@@ -1,7 +1,7 @@
'use client';
-import type { ReasoningGraph } from '@lobechat/types';
-import { ReasoningGraphSchema } from '@lobechat/types';
+import type { AgentGraph, LobeAgentChatConfig } from '@lobechat/types';
+import { AgentGraphSchema } from '@lobechat/types';
import { Flexbox, TextArea } from '@lobehub/ui';
import { Alert, Button, Switch } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar } from 'antd-style';
@@ -39,17 +39,23 @@ const styles = createStaticStyles(({ css }) => ({
`,
}));
-const formatGraph = (graph?: ReasoningGraph | null) =>
- graph ? JSON.stringify(graph, null, 2) : '';
+const formatGraph = (graph?: AgentGraph | null) => (graph ? JSON.stringify(graph, null, 2) : '');
const AgentGraphRuntime = memo(() => {
const { t } = useTranslation('setting');
const config = useStore(selectors.currentAgentConfig, isEqual);
const [disabled, updateConfig] = useStore((s) => [s.disabled, s.setAgentConfig]);
- const initialEnabled = config.chatConfig?.enableGraphMode === true;
+ // Legacy rows may still store the graph on chatConfig until their next write
+ // migrates it. The server keeps running those via the legacy fallback, so the
+ // editor must show the effective config β€” otherwise an actively-running graph
+ // agent would render as disabled with an empty snapshot.
+ const legacyChatConfig = config.chatConfig as
+ (LobeAgentChatConfig & { enableGraphMode?: boolean; graph?: AgentGraph | null }) | undefined;
+ const initialEnabled =
+ config.agencyConfig?.enableGraphMode === true || legacyChatConfig?.enableGraphMode === true;
const initialGraphText = useMemo(
- () => formatGraph(config.chatConfig?.graph),
- [config.chatConfig?.graph],
+ () => formatGraph(config.agencyConfig?.graph ?? legacyChatConfig?.graph),
+ [config.agencyConfig?.graph, legacyChatConfig?.graph],
);
const [enabled, setEnabled] = useState(initialEnabled);
@@ -74,7 +80,7 @@ const AgentGraphRuntime = memo(() => {
return;
}
- let graph: ReasoningGraph | undefined;
+ let graph: AgentGraph | undefined;
if (trimmedGraphText) {
let parsedGraph: unknown;
@@ -86,7 +92,7 @@ const AgentGraphRuntime = memo(() => {
return;
}
- const graphResult = ReasoningGraphSchema.safeParse(parsedGraph);
+ const graphResult = AgentGraphSchema.safeParse(parsedGraph);
if (!graphResult.success) {
setError(
@@ -106,7 +112,7 @@ const AgentGraphRuntime = memo(() => {
try {
await updateConfig({
- chatConfig: { enableGraphMode: enabled, graph: graph ?? null },
+ agencyConfig: { enableGraphMode: enabled, graph: graph ?? null },
});
} finally {
setSaving(false);