🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(Agent): Configurable graph agent (#16944)
Rylan Caie8af5258a7df
diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex 3146b1e502d..35dd0eca134 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -35,6 +35,7 @@"@lobechat/heterogeneous-agents": "workspace:*","@lobechat/local-file-shell": "workspace:*","@lobechat/tool-runtime": "workspace:*",+ "@lobechat/types": "workspace:*","@trpc/client": "^11.18.0","@types/node": "^24.13.2","@types/semver": "^7.7.1",diff --git a/apps/cli/src/commands/agent.test.ts b/apps/cli/src/commands/agent.test.tsindex 90875920129..0e1e7e7977f 100644--- a/apps/cli/src/commands/agent.test.ts+++ b/apps/cli/src/commands/agent.test.ts@@ -1,3 +1,7 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { Command } from 'commander';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -93,6 +97,7 @@ vi.mock('../utils/logger', () => ({describe('agent command', () => {let exitSpy: ReturnType<typeof vi.spyOn>;let consoleSpy: ReturnType<typeof vi.spyOn>;+ let tempDir: string | undefined;beforeEach(() => {exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);@@ -135,9 +140,13 @@ describe('agent command', () => {}});- afterEach(() => {+ afterEach(async () => {exitSpy.mockRestore();consoleSpy.mockRestore();+ if (tempDir) {+ await rm(tempDir, { force: true, recursive: true });+ tempDir = undefined;+ }});function createProgram() {@@ -147,6 +156,14 @@ describe('agent command', () => {return program;}+ async function writeGraphFixture(graph: unknown) {+ tempDir = await mkdtemp(join(tmpdir(), 'lh-agent-graph-'));+ const graphFile = join(tempDir, 'graph.json');+ await writeFile(graphFile, JSON.stringify(graph), 'utf8');++ return graphFile;+ }+describe('list', () => {it('should display agents in table format', async () => {mockTrpcClient.agent.queryAgents.query.mockResolvedValue([@@ -301,6 +318,78 @@ describe('agent command', () => {value: { model: 'gemini-3-pro' },});});++ it('should update graph config from a validated graph file', async () => {+ mockTrpcClient.agent.updateAgentConfig.mutate.mockResolvedValue({});+ const graph = {+ edges: [{ from: '__root__', instruction: 'Write the final answer.', to: 'answer' }],+ fields: {},+ name: 'answer-graph',+ nodes: { answer: { type: 'llm' } },+ terminal: 'answer',+ };+ const graphFile = await writeGraphFixture(graph);++ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'edit',+ 'a1',+ '--enable-graph',+ '--graph-file',+ graphFile,+ ]);++ expect(mockTrpcClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith({+ agentId: 'a1',+ value: {+ chatConfig: {+ enableGraphMode: true,+ graph,+ },+ },+ });+ });++ it('should reject conflicting graph enable flags', async () => {+ const program = createProgram();+ await program.parseAsync([+ 'node',+ 'test',+ 'agent',+ 'edit',+ 'a1',+ '--enable-graph',+ '--disable-graph',+ ]);++ expect(log.error).toHaveBeenCalledWith(+ 'Use either --enable-graph or --disable-graph, not both.',+ );+ expect(exitSpy).toHaveBeenCalledWith(1);+ expect(mockTrpcClient.agent.updateAgentConfig.mutate).not.toHaveBeenCalled();+ });++ it('should reject invalid graph files before updating agent config', async () => {+ const graphFile = await writeGraphFixture({+ edges: [],+ fields: {},+ name: 'invalid-graph',+ nodes: { answer: { type: 'llm' } },+ terminal: 'answer',+ });++ const program = createProgram();+ 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(exitSpy).toHaveBeenCalledWith(1);+ expect(mockTrpcClient.agent.updateAgentConfig.mutate).not.toHaveBeenCalled();+ });});describe('delete', () => {diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.tsindex cbc6c518601..745b90c8501 100644--- a/apps/cli/src/commands/agent.ts+++ b/apps/cli/src/commands/agent.ts@@ -1,5 +1,6 @@-import { readFileSync } from 'node:fs';+import { readFile } from 'node:fs/promises';+import { ReasoningGraphSchema } from '@lobechat/types';import type { Command } from 'commander';import pc from 'picocolors';@@ -17,6 +18,20 @@ import { log, setVerbose } from '../utils/logger';import { resolveAgentId } from './agent/resolveAgentId';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);++ 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'}`);+ }++ return result.data;+};+export function registerAgentCommand(program: Command) {const agent = program.command('agent').description('Manage agents');registerAgentSpaceFsCommand(agent);@@ -154,11 +169,17 @@ 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('--enable-graph', 'Enable graph runtime')+ .option('--disable-graph', 'Disable graph runtime').action(async (agentIdArg: string | undefined,options: {description?: string;+ disableGraph?: boolean;+ enableGraph?: boolean;+ graphFile?: string;model?: string;provider?: string;slug?: string;@@ -173,11 +194,32 @@ export function registerAgentCommand(program: Command) {if (options.provider) value.provider = options.provider;if (options.systemRole) value.systemRole = options.systemRole;+ if (options.enableGraph && options.disableGraph) {+ log.error('Use either --enable-graph or --disable-graph, not both.');+ process.exit(1);+ return;+ }++ const chatConfig: Record<string, any> = {};+ if (options.enableGraph) chatConfig.enableGraphMode = true;+ if (options.disableGraph) chatConfig.enableGraphMode = false;+ if (options.graphFile) {+ try {+ chatConfig.graph = await readGraphConfig(options.graphFile);+ } catch (error) {+ log.error(`Failed to read graph JSON: ${(error as Error).message}`);+ process.exit(1);+ return;+ }+ }+ if (Object.keys(chatConfig).length > 0) value.chatConfig = chatConfig;+if (Object.keys(value).length === 0) {log.error(- 'No changes specified. Use --title, --description, --model, --provider, or --system-role.',+ 'No changes specified. Use --title, --description, --model, --provider, --system-role, --graph-file, --enable-graph, or --disable-graph.',);process.exit(1);+ return;}const client = await getTrpcClient();diff --git a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsindex 8e24de0a331..7e399b2b574 100644--- a/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts+++ b/apps/server/src/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -1,5 +1,6 @@import { type AgentState } from '@lobechat/agent-runtime';import { BRANDING_PROVIDER } from '@lobechat/business-const';+import { ToolNameResolver } from '@lobechat/context-engine';import { consumeStreamUntilDone, ModelEmptyError } from '@lobechat/model-runtime';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -314,6 +315,181 @@ describe('RuntimeExecutors', { timeout: 60_000 }, () => {);});+ it('should restrict context tools and resolved tool calls to allowedToolNames', async () => {+ const toolNameResolver = new ToolNameResolver();+ const readToolName = toolNameResolver.generate('workspace', 'read', 'builtin');+ const writeToolName = toolNameResolver.generate('workspace', 'write', 'builtin');+ const mockChat = vi.fn().mockImplementation(async (_payload: any, options: any) => {+ await options?.callback?.onText?.('done');+ await options?.callback?.onToolsCalling?.({+ toolsCalling: [+ {+ function: { arguments: '{}', name: readToolName },+ id: 'read-call',+ type: 'function',+ },+ {+ function: { arguments: '{}', name: writeToolName },+ id: 'write-call',+ type: 'function',+ },+ ],+ });+ return new Response('done');+ });+ vi.mocked(initModelRuntimeFromDB).mockResolvedValueOnce({ chat: mockChat } as any);+ const engineSpy = vi.spyOn(ContextEngineering, 'serverMessagesEngine');+ const executors = createRuntimeExecutors({+ ...ctx,+ agentConfig: { plugins: [], systemRole: 'test' },+ });+ const state = createMockState({+ operationToolSet: {+ enabledToolIds: ['workspace'],+ manifestMap: {+ workspace: {+ api: [+ {+ description: 'Read workspace files',+ name: 'read',+ parameters: { type: 'object' },+ },+ {+ description: 'Write workspace files',+ name: 'write',+ parameters: { type: 'object' },+ },+ ],+ identifier: 'workspace',+ meta: { title: 'Workspace' },+ systemRole: 'Workspace tools include read and write.',+ type: 'builtin',+ },+ },+ sourceMap: { workspace: 'builtin' as const },+ tools: [+ { function: { name: readToolName }, type: 'function' },+ { function: { name: writeToolName }, type: 'function' },+ ],+ },+ });++ try {+ const result = await executors.call_llm!(+ {+ payload: {+ allowedToolNames: [readToolName],+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4',+ provider: 'openai',+ },+ type: 'call_llm' as const,+ },+ state,+ );++ expect(engineSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ toolsConfig: {+ manifests: [+ expect.objectContaining({+ api: [expect.objectContaining({ name: 'read' })],+ systemRole: undefined,+ }),+ ],+ tools: ['workspace'],+ },+ }),+ );+ expect(mockChat).toHaveBeenCalledWith(+ expect.objectContaining({+ tools: [{ function: { name: readToolName }, type: 'function' }],+ }),+ expect.anything(),+ );+ const nextPayload = result.nextContext?.payload as { toolsCalling: unknown[] };+ expect(nextPayload.toolsCalling).toEqual([+ expect.objectContaining({+ apiName: 'read',+ id: 'read-call',+ identifier: 'workspace',+ }),+ ]);+ } finally {+ engineSpy.mockRestore();+ }+ });++ it('should keep step-activated tools when allowedToolNames is not set', async () => {+ const toolNameResolver = new ToolNameResolver();+ const readToolName = toolNameResolver.generate('workspace', 'read', 'builtin');+ const calculateToolName = toolNameResolver.generate('calculator', 'calculate', 'builtin');+ const mockChat = vi.fn().mockImplementation(async (_payload: any, options: any) => {+ await options?.callback?.onText?.('done');+ return new Response('done');+ });+ vi.mocked(initModelRuntimeFromDB).mockResolvedValueOnce({ chat: mockChat } as any);+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState({+ activatedStepTools: [+ {+ activatedAtStep: 0,+ id: 'calculator',+ manifest: {+ api: [+ {+ description: 'Calculate an expression',+ name: 'calculate',+ parameters: { type: 'object' },+ },+ ],+ identifier: 'calculator',+ meta: { title: 'Calculator' },+ type: 'builtin',+ },+ source: 'discovery',+ },+ ],+ operationToolSet: {+ enabledToolIds: ['workspace'],+ manifestMap: {+ workspace: {+ api: [+ {+ description: 'Read workspace files',+ name: 'read',+ parameters: { type: 'object' },+ },+ ],+ identifier: 'workspace',+ meta: { title: 'Workspace' },+ type: 'builtin',+ },+ },+ sourceMap: { workspace: 'builtin' as const },+ tools: [{ function: { name: readToolName }, type: 'function' }],+ },+ });++ await executors.call_llm!(+ {+ payload: {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4',+ provider: 'openai',+ },+ type: 'call_llm' as const,+ },+ state,+ );++ expect(+ mockChat.mock.calls[0][0].tools.map((tool: { function: { name: string } }) => {+ return tool.function.name;+ }),+ ).toEqual([readToolName, calculateToolName]);+ });+it('should pass parentId from payload.parentMessageId to messageModel.create', async () => {const executors = createRuntimeExecutors(ctx);const state = createMockState();diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.tsindex 377753129e9..5d6c200a89d 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts@@ -36,7 +36,11 @@ export class ServerLLMTransport implements LLMTransport {parentId: input.parentId,provider: input.provider,stepLabel: input.stepLabel,- tooling: resolveServerCallLlmTooling(this.ctx, input.state),+ tooling: resolveServerCallLlmTooling(+ this.ctx,+ input.state,+ input.instruction.payload.allowedToolNames,+ ),})(input.instruction, input.state);}diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.tsindex b57ccdb9b45..f45794417b0 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmContextBuilder.ts@@ -487,7 +487,7 @@ export const buildServerCallLlmContext = async ({systemRole: agentConfig.systemRole ?? undefined,toolDiscoveryConfig,toolsConfig: {- manifests: Object.values(resolved.manifestMap),+ manifests: Object.values(resolved.promptManifestMap),tools: resolved.enabledToolIds,},userMemory: state.metadata?.userMemory,diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.tsindex a272f029aae..675362a7c6f 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmExecutor.ts@@ -74,7 +74,8 @@ export const callLlm =const model = prepared?.model ?? llmPayload.model ?? state.modelRuntimeConfig?.model;const provider =prepared?.provider ?? llmPayload.provider ?? state.modelRuntimeConfig?.provider;- const tooling = prepared?.tooling ?? resolveServerCallLlmTooling(ctx, state);+ const tooling =+ prepared?.tooling ?? resolveServerCallLlmTooling(ctx, state, llmPayload.allowedToolNames);const { resolved, tools } = tooling;if (!model || !provider) {@@ -575,7 +576,11 @@ export const callLlm =}},onToolsCalling: async ({ toolsCalling: raw }) => {- const resolvedCalls = new ToolNameResolver().resolve(raw, resolved.manifestMap);+ const resolvedCalls = new ToolNameResolver().resolve(+ raw,+ resolved.promptManifestMap,+ resolved.tools.map((tool) => tool.function.name),+ );// Attach source (origin) and executor (dispatch target) for routing.// `arguments` are kept RAW here on purpose so the tool executor can// still detect malformed JSON and return an `INVALID_JSON_ARGUMENTS`diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.tsindex 488225d5448..2d50131159a 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts@@ -26,6 +26,7 @@ export interface ServerCallLlmTooling {export const resolveServerCallLlmTooling = (ctx: Pick<RuntimeExecutorContext, 'operationId' | 'stepIndex'>,state: AgentState,+ allowedToolNames?: string[],): ServerCallLlmTooling => {// Resolve tools via ToolResolver (unified tool injection).//@@ -56,6 +57,7 @@ export const resolveServerCallLlmTooling = (operationToolSet,stepDelta,state.activatedStepTools ?? [],+ allowedToolNames,);const tools = resolved.tools.length > 0 ? resolved.tools : undefined;diff --git a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.tsindex 2808cae754c..11a30618801 100644--- a/apps/server/src/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts+++ b/apps/server/src/routers/lambda/__tests__/integration/aiAgent/multiRoundTools.integration.test.ts@@ -103,7 +103,7 @@ const createMockResponseWithMultipleTools = (roundNum: number) => {item: {type: 'function_call',call_id: toolCallId2,- name: 'lobe-web-browsing____crawl',+ name: 'lobe-web-browsing____crawlSinglePage',arguments: JSON.stringify({ url: `https://example.com/page${roundNum}` }),},},@@ -137,7 +137,7 @@ const createMockResponseWithMultipleTools = (roundNum: number) => {{type: 'function_call',call_id: toolCallId2,- name: 'lobe-web-browsing____crawl',+ name: 'lobe-web-browsing____crawlSinglePage',arguments: JSON.stringify({ url: `https://example.com/page${roundNum}` }),},],diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.tsindex 3d6c6319501..90048ab8c4f 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts@@ -1,3 +1,4 @@+import { GeneralChatAgent, GraphAgent } from '@lobechat/agent-runtime';import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';import { SELF_FEEDBACK_INTENT_IDENTIFIER } from '@lobechat/builtin-tool-self-iteration';import { RequestTrigger } from '@lobechat/types';@@ -5,6 +6,7 @@ import type * as ModelBankModule from 'model-bank';import { beforeEach, describe, expect, it, vi } from 'vitest';import { createServerAgentToolsEngine } from '@/server/modules/Mecha';+import { AgentRuntimeService } from '@/server/services/agentRuntime';import { AiAgentService } from '../index';@@ -197,6 +199,13 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {let service: AiAgentService;const mockDb = {} as any;const userId = 'test-user-id';+ const minimalGraph = {+ edges: [{ from: '__root__', instruction: 'Answer with the graph runtime.', to: 'answer' }],+ fields: {},+ name: 'answer-graph',+ nodes: { answer: { type: 'llm' } },+ terminal: 'answer',+ };beforeEach(() => {vi.clearAllMocks();@@ -220,6 +229,73 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {service = new AiAgentService(mockDb, userId);});+ describe('graph runtime factory', () => {+ const getLatestAgentFactory = () => {+ const options = vi.mocked(AgentRuntimeService).mock.calls.at(-1)?.[2] as any;+ const agentFactory = options?.agentFactory;++ expect(agentFactory).toEqual(expect.any(Function));++ return agentFactory as (config: any) => unknown;+ };++ it('creates GraphAgent when graph mode is enabled with a valid graph snapshot', () => {+ service = new AiAgentService(mockDb, userId);++ const agent = getLatestAgentFactory()({+ agentConfig: {+ chatConfig: {+ enableGraphMode: true,+ graph: minimalGraph,+ },+ },+ operationId: 'op-graph',+ });++ expect(agent).toBeInstanceOf(GraphAgent);+ });++ it('falls back to GeneralChatAgent when the graph snapshot is invalid', () => {+ service = new AiAgentService(mockDb, userId);++ const agent = getLatestAgentFactory()({+ agentConfig: {+ chatConfig: {+ enableGraphMode: true,+ graph: { ...minimalGraph, edges: [] },+ },+ },+ operationId: 'op-invalid-graph',+ });++ expect(agent).toBeInstanceOf(GeneralChatAgent);+ });++ it('keeps an upstream runtime agent factory authoritative', () => {+ const upstreamAgent = { runner: vi.fn() };+ const upstreamFactory = vi.fn(() => upstreamAgent);+ service = new AiAgentService(mockDb, userId, {+ runtimeOptions: {+ agentFactory: upstreamFactory,+ },+ } as any);++ const config = {+ agentConfig: {+ chatConfig: {+ enableGraphMode: true,+ graph: minimalGraph,+ },+ },+ operationId: 'op-upstream',+ };+ const agent = getLatestAgentFactory()(config);++ expect(agent).toBe(upstreamAgent);+ expect(upstreamFactory).toHaveBeenCalledWith(config);+ });+ });+it('materializes a builtin agent addressed by slug when no row exists yet', async () => {// Background self-iteration runs dispatch via execAgent({ slug }) before any// persisted row exists. The first resolve (by slug) misses; execAgent mustdiff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 2aca04d767c..664d2f42d73 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -1,4 +1,10 @@-import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';+import type {+ Agent,+ AgentRuntimeContext,+ AgentState,+ GeneralAgentConfig,+} from '@lobechat/agent-runtime';+import { GeneralChatAgent, GraphAgent } from '@lobechat/agent-runtime';import { BUILTIN_AGENT_SLUGS, getAgentRuntimeConfig } from '@lobechat/builtin-agents';import { builtinSkills } from '@lobechat/builtin-skills';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';@@ -40,6 +46,7 @@ import type {ExecSubAgentResult,ExecVirtualSubAgentParams,LobeAgentAgencyConfig,+ LobeAgentConfig,MessagePluginItem,RuntimeMentionedAgent,UserInterventionConfig,@@ -50,11 +57,13 @@ import {getActivePluginIds,getDisabledPluginIds,getWorkingDirEffectivePath,+ ReasoningGraphSchema,RequestTrigger,ThreadStatus,ThreadType,} from '@lobechat/types';import { nanoid } from '@lobechat/utils';+import { isRecord } from '@lobechat/utils/object';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -148,6 +157,32 @@ import { isWorkspaceCacheFresh, upsertWorkspaceScan } from './workspaceInitCacheconst log = debug('lobe-server:ai-agent-service');+const createGraphAwareAgentFactory =+ (+ upstreamFactory?: AgentRuntimeServiceOptions['agentFactory'],+ ): ((config: GeneralAgentConfig) => Agent) =>+ (config) => {+ if (upstreamFactory) {+ return upstreamFactory(config);+ }++ const runtimeAgentConfig = isRecord(config.agentConfig)+ ? (config.agentConfig as LobeAgentConfig)+ : undefined;+ const graph = runtimeAgentConfig?.chatConfig?.graph;+ if (runtimeAgentConfig?.chatConfig?.enableGraphMode && graph) {+ const graphResult = ReasoningGraphSchema.safeParse(graph);++ if (graphResult.success) {+ return new GraphAgent({ ...config, graph: graphResult.data });+ }++ log('Invalid graph agent snapshot, falling back to default runtime: %O', graphResult.error);+ }++ return new GeneralChatAgent(config);+ };+/*** Format error for storage in thread metadata* Handles Error objects which don't serialize properly with JSON.stringify@@ -466,6 +501,7 @@ export class AiAgentService {this.topicModel = new TopicModel(db, userId, wsId);this.agentRuntimeService = new AgentRuntimeService(db, userId, {...options?.runtimeOptions,+ agentFactory: createGraphAwareAgentFactory(options?.runtimeOptions?.agentFactory),// ── Runtime delegate ─────────────────────────────────────────────────// Operations the runtime delegates back UP to this layer. The dependency// arrow is one-way (AiAgentService → AgentRuntimeService), so the runtimediff --git a/locales/en-US/labs.json b/locales/en-US/labs.jsonindex a19c2a913f9..3c254e4d07f 100644--- a/locales/en-US/labs.json+++ b/locales/en-US/labs.json@@ -1,6 +1,8 @@{"features.agentDocumentFloatingChatPanel.desc": "Show the floating chat panel in agent document preview only when this lab feature is enabled.","features.agentDocumentFloatingChatPanel.title": "Agent Document Floating Chat Panel",+ "features.agentGraphConfig.desc": "Show graph runtime configuration in an agent profile advanced settings.",+ "features.agentGraphConfig.title": "Agent Graph Runtime Configuration","features.agentSelfIteration.desc": "Allow the agent to reflect, build self-awareness, and continuously iterate through ongoing attempts and interactions.","features.agentSelfIteration.title": "Agent Self-iteration","features.assistantMessageGroup.desc": "Group agent messages and their tool call results together for display",diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 616a9329207..6d346bd8d17 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -190,6 +190,7 @@"agentSkillModal.url.title": "Import from URL","agentSkillModal.url.urlPlaceholder": "https://example.com/path/to/SKILL.md","agentSkillTag": "Agent Skill",+ "agentTab.graph": "Graph Runtime","agentTab.opening": "Opening Settings","agentTab.plugin": "Skill Settings","agentTab.prompt": "Agent Profile",@@ -647,6 +648,15 @@"settingCommon.themeMode.light": "Light","settingCommon.themeMode.title": "Theme","settingCommon.title": "General Settings",+ "settingGraphRuntime.enabled.desc": "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.",+ "settingGraphRuntime.snapshot.placeholder": "Paste a ReasoningGraph JSON snapshot, for example: {\"name\":\"...\",\"entry\":\"...\",\"states\":{...},\"terminal\":\"...\",\"transitions\":[]}",+ "settingGraphRuntime.snapshot.title": "Graph Snapshot",+ "settingGraphRuntime.validation.invalidGraph": "Invalid graph snapshot: {{error}}",+ "settingGraphRuntime.validation.invalidJson": "Graph snapshot must be valid JSON.",+ "settingGraphRuntime.validation.required": "A graph snapshot is required before enabling graph runtime.",+ "settingGraphRuntime.validation.unknown": "Unknown graph validation error","settingGroup.description.placeholder": "Enter Group description","settingGroup.description.title": "Group description","settingGroup.name.placeholder": "Enter Group name",diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.jsonindex 1c36d535d1d..27512aab172 100644--- a/locales/zh-CN/labs.json+++ b/locales/zh-CN/labs.json@@ -1,6 +1,8 @@{"features.agentDocumentFloatingChatPanel.desc": "仅当启用此实验功能时,在代理文档预览中显示浮动聊天面板。","features.agentDocumentFloatingChatPanel.title": "代理文档浮动聊天面板",+ "features.agentGraphConfig.desc": "在助理档案的进阶设置中显示 Graph 运行时配置。",+ "features.agentGraphConfig.title": "Agent Graph 运行时配置","features.agentSelfIteration.desc": "允许助理自我反思、自我感知,并在持续的尝试与交互中不断自我迭代。","features.agentSelfIteration.title": "Agent 自我迭代","features.assistantMessageGroup.desc": "将代理消息及其工具调用结果组合在一起显示",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex a746ea00006..e2ac0f72fb1 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -190,6 +190,7 @@"agentSkillModal.url.title": "从 URL 导入","agentSkillModal.url.urlPlaceholder": "https://example.com/path/to/SKILL.md","agentSkillTag": "Agent 技能",+ "agentTab.graph": "Graph 运行时","agentTab.opening": "开场设置","agentTab.plugin": "技能设置","agentTab.prompt": "助理档案",@@ -647,6 +648,15 @@"settingCommon.themeMode.light": "浅色","settingCommon.themeMode.title": "主题","settingCommon.title": "通用设置",+ "settingGraphRuntime.enabled.desc": "使用下方保存的快照,让该助理通过 Graph 运行时执行。",+ "settingGraphRuntime.enabled.title": "启用 Graph 运行时",+ "settingGraphRuntime.snapshot.desc": "粘贴完整的 ReasoningGraph JSON 快照。它会随当前助理保存,并在运行时直接使用。",+ "settingGraphRuntime.snapshot.placeholder": "粘贴 ReasoningGraph JSON 快照,例如:{\"name\":\"...\",\"entry\":\"...\",\"states\":{...},\"terminal\":\"...\",\"transitions\":[]}",+ "settingGraphRuntime.snapshot.title": "Graph 快照",+ "settingGraphRuntime.validation.invalidGraph": "Graph 快照无效:{{error}}",+ "settingGraphRuntime.validation.invalidJson": "Graph 快照必须是合法 JSON。",+ "settingGraphRuntime.validation.required": "启用 Graph 运行时前必须提供 Graph 快照。",+ "settingGraphRuntime.validation.unknown": "未知 Graph 校验错误","settingGroup.description.placeholder": "请输入群组描述","settingGroup.description.title": "群组描述","settingGroup.name.placeholder": "请输入群组名称",diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.jsonindex ec5446987ca..cff07a89c83 100644--- a/packages/agent-runtime/package.json+++ b/packages/agent-runtime/package.json@@ -9,6 +9,7 @@"test:coverage": "vitest --coverage --silent='passed-only'"},"dependencies": {+ "ajv": "^8.20.0","p-map": "^7.0.5"},"devDependencies": {diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex 655929a4b9b..5d8eead1f70 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -46,6 +46,16 @@ export class GeneralChatAgent implements Agent {this.config = config;}+ private getTools(state: AgentState, fallbackTools?: any[]): any[] | undefined {+ return this.config.tools ?? state.tools ?? state.operationToolSet?.tools ?? fallbackTools;+ }++ private getAllowedToolNamesPayload() {+ return this.config.allowedToolNames === undefined+ ? {}+ : { allowedToolNames: this.config.allowedToolNames };+ }+/*** Get intervention configuration for a specific tool call*/@@ -375,6 +385,10 @@ export class GeneralChatAgent implements Agent {payload: GeneralAgentCallLLMInstructionPayload,state: AgentState,): AgentInstruction {+ const payloadWithAllowedToolNames = {+ ...payload,+ ...this.getAllowedToolNamesPayload(),+ };const compressionEnabled = this.config.compressionConfig?.enabled ?? true;// Mirror RuntimeExecutors.callLlm: when state.forceFinish is set, the// executor strips all tools via buildStepToolDelta (deactivatedToolIds: ['*']),@@ -383,11 +397,11 @@ export class GeneralChatAgent implements Agent {const compressionOptions = {maxWindowToken: this.config.compressionConfig?.maxWindowToken,thresholdRatio: this.config.compressionConfig?.thresholdRatio,- tools: state.forceFinish ? undefined : payload.tools,+ tools: state.forceFinish ? undefined : payloadWithAllowedToolNames.tools,};if (compressionEnabled) {- const messages = payload.messages;+ const messages = payloadWithAllowedToolNames.messages;const compressionCheck = shouldCompress(messages, compressionOptions);if (compressionCheck.needsCompression) {@@ -403,7 +417,7 @@ export class GeneralChatAgent implements Agent {}return {- payload,+ payload: payloadWithAllowedToolNames,type: 'call_llm',};}@@ -456,7 +470,7 @@ export class GeneralChatAgent implements Agent {const compressionOptions = {maxWindowToken: this.config.compressionConfig?.maxWindowToken,thresholdRatio: this.config.compressionConfig?.thresholdRatio,- tools: state.forceFinish ? undefined : state.tools,+ tools: state.forceFinish ? undefined : this.getTools(state),};if (compressionEnabled) {@@ -477,10 +491,14 @@ export class GeneralChatAgent implements Agent {// User input received, call LLM to generate response// At this point, messages may have been preprocessed with RAG/Search+ const basePayload = context.payload as any;+ const tools = this.getTools(state, basePayload?.tools);return {payload: {- ...(context.payload as any),+ ...basePayload,+ ...this.getAllowedToolNamesPayload(),messages: state.messages,+ tools,} as GeneralAgentCallLLMInstructionPayload,type: 'call_llm',};@@ -659,7 +677,7 @@ export class GeneralChatAgent implements Agent {model: this.config.modelRuntimeConfig?.model,parentMessageId,provider: this.config.modelRuntimeConfig?.provider,- tools: state.tools,+ tools: this.getTools(state),} as GeneralAgentCallLLMInstructionPayload,state,);@@ -701,7 +719,7 @@ export class GeneralChatAgent implements Agent {model: this.config.modelRuntimeConfig?.model,parentMessageId,provider: this.config.modelRuntimeConfig?.provider,- tools: state.tools,+ tools: this.getTools(state),} as GeneralAgentCallLLMInstructionPayload,state,);@@ -718,7 +736,7 @@ export class GeneralChatAgent implements Agent {model: this.config.modelRuntimeConfig?.model,parentMessageId,provider: this.config.modelRuntimeConfig?.provider,- tools: state.tools,+ tools: this.getTools(state),} as GeneralAgentCallLLMInstructionPayload,state,);@@ -751,7 +769,7 @@ export class GeneralChatAgent implements Agent {model: this.config.modelRuntimeConfig?.model,parentMessageId,provider: this.config.modelRuntimeConfig?.provider,- tools: state.tools,+ tools: this.getTools(state),} as GeneralAgentCallLLMInstructionPayload,state,);@@ -760,6 +778,7 @@ export class GeneralChatAgent implements Agent {case 'compression_result': {// Context compression completed, continue to call LLMconst compressionPayload = context.payload as GeneralAgentCompressionResultPayload;+ const tools = this.getTools(state);// A tool-first resume seeds an assistant placeholder that the first// post-tool LLM turn must fill. When that turn is large enough to@@ -783,7 +802,8 @@ export class GeneralChatAgent implements Agent {model: this.config.modelRuntimeConfig?.model,parentMessageId: compressionPayload.parentMessageId,provider: this.config.modelRuntimeConfig?.provider,- tools: state.tools,+ tools,+ ...this.getAllowedToolNamesPayload(),} as GeneralAgentCallLLMInstructionPayload,type: 'call_llm',};diff --git a/packages/agent-runtime/src/agents/GraphAgent.ts b/packages/agent-runtime/src/agents/GraphAgent.tsindex e191e0f4133..224205540a2 100644--- a/packages/agent-runtime/src/agents/GraphAgent.ts+++ b/packages/agent-runtime/src/agents/GraphAgent.ts@@ -1,363 +1,1012 @@+import { ToolNameResolver } from '@lobechat/context-engine';+import type { AgentGraphEdge, AgentGraphNode, ReasoningGraph } from '@lobechat/types';+import { AGENT_GRAPH_ROOT_NODE_ID } from '@lobechat/types';+import type { UnknownRecord } from '@lobechat/utils/object';+import { isRecord } from '@lobechat/utils/object';+import Ajv from 'ajv';+import type {Agent,AgentInstruction,AgentRuntimeContext,AgentState,+ FinishReason,GeneralAgentCallLLMInstructionPayload,GeneralAgentConfig,- GraphContext,- ReasoningGraph,} from '../types';import { GeneralChatAgent } from './GeneralChatAgent';-const GRAPH_CONTEXT_KEY = '__graphContext';+const GRAPH_RUNTIME_STATE_KEY = '__graphRuntimeState';+const DEFAULT_MAX_GRAPH_INSTRUCTION_COUNT = 256;+const MAX_GRAPH_INSTRUCTION_COUNT_LIMIT = 1024;+const MAX_GRAPH_INTERNAL_TRANSITIONS = 4;+const MAX_NODE_OUTPUT_EXTRACTION_ATTEMPTS = 3;+const DEFAULT_NODE_OUTPUT_EXTRACTION_INSTRUCTION =+ 'The current graph node has completed its work. Extract and submit the node deliverable from the conversation.';+const NODE_OUTPUT_EXTRACTION_FORMAT =+ 'Return exactly one markdown fenced code block tagged json, containing a single JSON object that matches output_schema. Do not include any text outside the code block.';+const ajv = new Ajv({ allErrors: true, strict: false });+const conditionAjv = new Ajv({ allErrors: false, strict: true });++type GraphState =+ | {+ phase: 'init';+ }+ | {+ active: boolean;+ currentNode: string;+ incomingEdge: AgentGraphEdge;+ nodeStartStepCount?: number;+ phase: 'node_in';+ }+ | {+ active: boolean;+ attempts: number;+ currentNode: string;+ incomingEdge: AgentGraphEdge;+ nodeStepLimitExceeded?: boolean;+ phase: 'node_out';+ }+ | {+ currentNode: string;+ phase: 'transit';+ }+ | {+ reason: FinishReason;+ reasonDetail?: string;+ phase: 'fin';+ };++/**+ * Data store for graph reducers.+ *+ * Nodes only write their own completed output into store[nodeId]. Node-in resolves+ * its incoming edge input before starting execution. Node reducers consume that+ * resolved input for the current instruction instead of freely reading store,+ * otherwise graph dependencies become invisible prompt-side globals.+ *+ * Reading or writing store data must not advance GraphState by itself or create+ * side effects outside the returned orchestration.+ */+interface GraphContext {+ edgeTraversalCounts: Record<string, number>;+ store: UnknownRecord;+}++interface GraphRuntimeState {+ graphContext: GraphContext;+ graphState: GraphState;+ instructionCount: number;+}++interface ReducerInput {+ context: AgentRuntimeContext;+ graphContext: GraphContext;+ graphState: GraphState;+ state: AgentState;+}++interface GraphOrchestration {+ graphContext: GraphContext;+ graphState: GraphState;+ instruction?: AgentInstruction | AgentInstruction[];+}++type NodeOutputExtraction =+ | {+ ok: true;+ output: UnknownRecord;+ raw: string;+ }+ | {+ error: string;+ ok: false;+ raw: string;+ };++type EdgeSelection =+ | {+ edge: AgentGraphEdge;+ reason: 'blocked_by_limit';+ }+ | {+ edge: AgentGraphEdge;+ reason: 'matched';+ }+ | {+ reason: 'no_match';+ };++interface OutputValidation {+ error?: string;+ ok: boolean;+}++type PromptValue = PromptArray | PromptObject | boolean | null | number | string | undefined;++interface PromptArray extends Array<PromptValue> {}++interface PromptObject {+ [key: string]: PromptValue;+}/**- * GraphAgent — A graph-driven Agent that decorates GeneralChatAgent.+ * GraphAgent is a graph-level orchestrator over the normal AgentRuntime loop.*- * Instead of the default phase-driven loop (LLM decides flow),- * GraphAgent uses a declarative ReasoningGraph to drive execution:+ * The runtime still executes concrete instructions.+ * This class only keeps the graph routing state:*- * 1. Each graph node maps to one or more AgentRuntime steps- * 2. 'agent' nodes delegate to GeneralChatAgent for full tool-calling loops- * 3. 'llm' nodes do a single LLM call with structured output- * 4. Transitions are evaluated programmatically (not by LLM)- * 5. Backtracking is supported with configurable limits+ * init -> node_in -> node_out -> transit -> fin*- * Key mechanism: intercept GeneralChatAgent's 'finish' instruction.- * When the inner agent finishes, GraphAgent checks if the graph has more- * nodes to execute. Only when the terminal node completes does GraphAgent- * return a real 'finish'.+ * - init: validate graph root edge and move to its target node.+ * - node_in: let the current node run; node internals may forward to another agent policy.+ * - node_out: collect the completed node's result.+ * - transit: choose the next graph node or finish.+ * - fin: terminal graph state.*- * Agent vs LLM nodes:- * - 'agent' nodes: prompt sent WITHOUT JSON schema → agent loop with tools →- * on finish, extra LLM call to extract structured output- * - 'llm' nodes: prompt sent WITH JSON schema → single structured LLM call+ * Handlers return GraphOrchestration, not just GraphState, because some states can already produce+ * a runtime instruction to forward. GraphState must remain routing state only; runtime instructions+ * are per-step output and must not be stored in metadata.+ *+ * Only the state handlers (onInit/onNodeIn/onNodeOut/onTransit/onFin) may advance GraphState.+ * All other methods are adapters: runner commits the handler result, and resolveRuntimeInstruction only+ * forwards the runtime instruction or terminal finish. Non-handler methods may only return finish for+ * out-of-band safety failures; they must not introduce normal graph transitions.*/export class GraphAgent implements Agent {- private innerAgent: GeneralChatAgent;+ private generalConfig: GeneralAgentConfig;private graph: ReasoningGraph;constructor(config: GeneralAgentConfig & { graph: ReasoningGraph }) {const { graph, ...generalConfig } = config;this.graph = graph;- this.innerAgent = new GeneralChatAgent(generalConfig);+ this.generalConfig = generalConfig;}+ // observation -> orchestration -> instructionasync runner(context: AgentRuntimeContext,state: AgentState,): Promise<AgentInstruction | AgentInstruction[]> {- const gc = this.getGraphContext(state);-- // First call — initialize graph and start entry node- if (!gc) {- return this.initGraph(context, state);- }+ let { graphContext, graphState, instructionCount } = this.loadGraphRuntimeState(state);+ const maxInstructionCount = Math.min(+ this.graph.maxInstructionCount ?? DEFAULT_MAX_GRAPH_INSTRUCTION_COUNT,+ MAX_GRAPH_INSTRUCTION_COUNT_LIMIT,+ );++ if (graphState.phase !== 'fin' && instructionCount >= maxInstructionCount) {+ this.updateGraphRuntimeState(state, {+ graphContext,+ graphState: {+ reason: 'error_recovery',+ reasonDetail:+ `graph_instruction_limit_reached: Graph "${this.graph.name}" reached ` ++ `maxInstructionCount ${maxInstructionCount}`,+ phase: 'fin',+ },+ instructionCount,+ });- const node = this.graph.states[gc.currentNode];- if (!node) {return {reason: 'error_recovery',- reasonDetail: `Graph node "${gc.currentNode}" not found`,+ reasonDetail:+ `graph_instruction_limit_reached: Graph "${this.graph.name}" reached ` ++ `maxInstructionCount ${maxInstructionCount}`,type: 'finish',};}- // Agent node: delegate to GeneralChatAgent for the tool-calling loop- if (gc.nodeActive && node.type === 'agent') {- // If we're in the extraction phase, handle the extraction result- if (gc.extracting) {- if (context.phase === 'llm_result') {- gc.extracting = false;- return this.onNodeComplete(state, gc);+ // A runtime work frame does not map 1:1 to a graph phase.+ // Some graph phases only update graph state/store and cannot produce a runtime instruction.+ // Advance a bounded number of internal graph phases until one lowers to a runtime instruction+ // or the graph reaches fin.+ for (let index = 0; index < MAX_GRAPH_INTERNAL_TRANSITIONS; index++) {+ const orchestration = await this.orchestrate({ context, graphContext, graphState, state });++ graphContext = orchestration.graphContext;+ graphState = orchestration.graphState;+ this.updateGraphRuntimeState(state, { graphContext, graphState, instructionCount });++ const instruction = this.resolveRuntimeInstruction(orchestration);++ // If the graph state machine lowers to a runtime instruction or reaches fin,+ // we can return the instruction to the runtime.+ if (instruction) {+ if (!this.hasFinishInstruction(instruction)) {+ instructionCount += 1;+ this.updateGraphRuntimeState(state, { graphContext, graphState, instructionCount });}- return this.innerAgent.runner(context, state);++ return instruction;}+ }- const instruction = await this.innerAgent.runner(context, state);+ // That should not happen; the graph should always yield an instruction or reach fin within a few transitions.+ // If it does, force a finish to avoid infinite loops.+ this.updateGraphRuntimeState(state, {+ graphContext,+ graphState: {+ reason: 'error_recovery',+ reasonDetail: `graph_internal_transition_limit_reached: ${MAX_GRAPH_INTERNAL_TRANSITIONS}`,+ phase: 'fin',+ },+ instructionCount,+ });- // Intercept finish — agent loop done, now extract structured output- if (!Array.isArray(instruction) && instruction.type === 'finish') {- return this.startExtraction(state, gc);+ return {+ reason: 'error_recovery',+ reasonDetail: `graph_internal_transition_limit_reached: ${MAX_GRAPH_INTERNAL_TRANSITIONS}`,+ type: 'finish',+ };+ }++ /**+ * Dispatches the current graph phase to its reducer.+ *+ * This method does not choose the next phase. Each phase handler returns the+ * next GraphState/GraphContext, and runner commits that returned state after+ * every internal graph step.+ */+ private async orchestrate(input: ReducerInput): Promise<GraphOrchestration> {+ switch (input.graphState.phase) {+ case 'init': {+ return this.onInit(input);}- if (Array.isArray(instruction)) {- const hasFinish = instruction.some((i) => i.type === 'finish');- if (hasFinish) {- return this.startExtraction(state, gc);- }+ case 'node_in': {+ return this.onNodeIn(input);}- // Otherwise pass through (call_llm, call_tool, etc.)- return instruction;- }+ case 'node_out': {+ return this.onNodeOut(input);+ }- // LLM node: after the LLM result comes back, extract output and advance- if (gc.nodeActive && node.type === 'llm') {- if (context.phase === 'llm_result') {- return this.onNodeComplete(state, gc);+ case 'transit': {+ return this.onTransit(input);}- // Delegate other phases (like compression_result) to inner agent- return this.innerAgent.runner(context, state);- }- // nodeActive is false — we're at a graph transition point, start the next node- return this.startNode(gc, state);+ case 'fin': {+ return this.onFin(input);+ }+ }}- /**- * Initialize the graph: set up context, start entry node- */- private initGraph(_context: AgentRuntimeContext, state: AgentState): AgentInstruction {- const lastUserMessage = [...state.messages].reverse().find((m: any) => m.role === 'user');- const input =+ private onInit(input: ReducerInput): GraphOrchestration {+ const [rootEdge] = this.getEdgesFrom(AGENT_GRAPH_ROOT_NODE_ID);++ if (!rootEdge) {+ return {+ graphContext: input.graphContext,+ graphState: {+ reason: 'error_recovery',+ reasonDetail:+ `graph_root_transition_missing: Graph "${this.graph.name}" must define ` ++ `one "${AGENT_GRAPH_ROOT_NODE_ID}" outgoing edge with an instruction`,+ phase: 'fin',+ },+ };+ }++ if (!this.getNodeById(rootEdge.to)) {+ return {+ graphContext: input.graphContext,+ graphState: {+ reason: 'error_recovery',+ reasonDetail: `graph_node_missing: Graph node "${rootEdge.to}" not found`,+ phase: 'fin',+ },+ };+ }++ const lastUserMessage = [...input.state.messages]+ .reverse()+ .find((message) => message.role === 'user');+ const query =typeof lastUserMessage?.content === 'string'? lastUserMessage.content- : JSON.stringify(lastUserMessage?.content ?? '');-- const gc: GraphContext = {- currentNode: this.graph.entry,- nodeActive: false,- store: {},- backtrackCount: 0,- visitCount: {},- input,+ : (JSON.stringify(lastUserMessage?.content ?? '') ?? '');++ return {+ graphContext: this.storeReducers.nodeStore(input.graphContext, AGENT_GRAPH_ROOT_NODE_ID, {+ query,+ }),+ graphState: {+ active: false,+ currentNode: rootEdge.to,+ incomingEdge: rootEdge,+ phase: 'node_in',+ },};-- this.saveGraphContext(state, gc);- return this.startNode(gc, state);}- /**- * Start executing a graph node.- *- * - agent nodes: send task prompt WITH tools, WITHOUT JSON schema- * (let the agent use tools freely, extract structured output later)- * - llm nodes: send prompt WITH JSON schema, WITHOUT tools- * (single structured generation call)- */- private startNode(gc: GraphContext, state: AgentState): AgentInstruction {- const node = this.graph.states[gc.currentNode];+ private async onNodeIn(input: ReducerInput): Promise<GraphOrchestration> {+ const graphState = input.graphState as Extract<GraphState, { phase: 'node_in' }>;+ const { context, state } = input;+ const node = this.getNodeById(graphState.currentNode);+if (!node) {return {- reason: 'error_recovery',- reasonDetail: `Graph node "${gc.currentNode}" not found in states`,- type: 'finish',+ graphContext: input.graphContext,+ graphState: {+ reason: 'error_recovery',+ reasonDetail: `graph_node_missing: Graph node "${graphState.currentNode}" not found`,+ phase: 'fin',+ },+ };+ }++ const tools = node.type === 'agent' ? this.getNodeTools(node, state) : [];+ const allowedToolNames =+ node.type === 'agent' && !node.allowedToolApiNames+ ? undefined+ : tools+ .map((tool) => tool?.function?.name)+ .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',+ };+ };++ return {+ graphContext: input.graphContext,+ graphState: {+ ...graphState,+ active: true,+ nodeStartStepCount: state.stepCount,+ },+ instruction: callLlm(prompt),+ };+ }++ if (node.type === 'llm' && context.phase === 'llm_result') {+ return {+ graphContext: input.graphContext,+ graphState: {+ active: false,+ attempts: 0,+ currentNode: graphState.currentNode,+ incomingEdge: graphState.incomingEdge,+ phase: 'node_out',+ },+ };+ }++ if (+ node.type === 'agent' &&+ node.maxAgentSteps !== undefined &&+ node.maxAgentSteps > 0 &&+ graphState.nodeStartStepCount !== undefined &&+ state.stepCount - graphState.nodeStartStepCount >= node.maxAgentSteps+ ) {+ return {+ graphContext: input.graphContext,+ graphState: {+ active: false,+ attempts: 0,+ currentNode: graphState.currentNode,+ incomingEdge: graphState.incomingEdge,+ nodeStepLimitExceeded: true,+ phase: 'node_out',+ },};}- const visits = (gc.visitCount[gc.currentNode] ?? 0) + 1;- gc.visitCount[gc.currentNode] = visits;+ const instruction = await new GeneralChatAgent({+ ...this.generalConfig,+ allowedToolNames,+ tools,+ }).runner(context, state);- if (visits > 1) {- gc.backtrackCount++;+ if (this.hasFinishInstruction(instruction)) {+ return {+ graphContext: input.graphContext,+ graphState: {+ active: false,+ attempts: 0,+ currentNode: graphState.currentNode,+ incomingEdge: graphState.incomingEdge,+ phase: 'node_out',+ },+ };}- const renderedPrompt = this.renderPrompt(node.prompt, gc);+ return {+ graphContext: input.graphContext,+ graphState,+ instruction,+ };+ }- let fullPrompt: string;- let tools: any[];+ private onNodeOut(input: ReducerInput): GraphOrchestration {+ const graphState = input.graphState as Extract<GraphState, { phase: 'node_out' }>;+ if (graphState.active && input.context.phase !== 'llm_result') {+ return {+ graphContext: input.graphContext,+ graphState: {+ reason: 'error_recovery',+ reasonDetail: `graph_node_output_extraction_unexpected_phase: Expected llm_result for node "${graphState.currentNode}" output extraction, got "${input.context.phase}"`,+ phase: 'fin',+ },+ };+ }- if (node.type === 'agent') {- // Agent node: task prompt with tools, no JSON schema constraint- // The agent will use tools freely; structured output is extracted after the loop- fullPrompt =- renderedPrompt +- '\n\nIMPORTANT: You MUST use your available tools (web search, etc.) to research this. ' +- 'Do NOT answer from memory. Search for real evidence and data first, ' +- 'then provide your findings based on the tool results.';- tools = state.tools ?? [];- } else {- // LLM node: structured output, no tools- fullPrompt =- renderedPrompt +- `\n\nYou MUST respond with a JSON object that conforms to this schema:\n` +- `\`\`\`json\n${JSON.stringify(node.outputSchema, null, 2)}\n\`\`\`\n` +- `Only output valid JSON, no other text.`;- tools = [];+ if (!graphState.incomingEdge.output?.fields?.length) {+ return {+ graphContext: input.graphContext,+ graphState: {+ currentNode: graphState.currentNode,+ phase: 'transit',+ },+ };}- gc.nodeActive = true;- gc.extracting = false;- this.saveGraphContext(state, gc);+ const extraction = this.extractNodeOutput(input);- const messages = [...state.messages, { content: fullPrompt, role: 'user' as const }];+ if (extraction.ok) {+ const validation = this.validateNodeOutput(graphState.incomingEdge, extraction.output);+ if (!validation.ok) {+ return this.retryNodeOutputExtraction(input, graphState, {+ error:+ validation.error ?? 'The node output did not match the selected edge output schema.',+ ok: false,+ raw: extraction.raw,+ });+ }++ return {+ graphContext: this.storeReducers.nodeStore(+ input.graphContext,+ graphState.currentNode,+ extraction.output,+ ),+ graphState: {+ currentNode: graphState.currentNode,+ phase: 'transit',+ },+ };+ }++ return this.retryNodeOutputExtraction(input, graphState, extraction);+ }++ private retryNodeOutputExtraction(+ input: ReducerInput,+ graphState: Extract<GraphState, { phase: 'node_out' }>,+ extraction: Extract<NodeOutputExtraction, { ok: false }>,+ ): GraphOrchestration {+ if (graphState.attempts >= MAX_NODE_OUTPUT_EXTRACTION_ATTEMPTS) {+ return {+ graphContext: this.storeReducers.nodeStore(input.graphContext, graphState.currentNode, {+ _extractionError: extraction.error,+ _raw: extraction.raw,+ }),+ graphState: {+ currentNode: graphState.currentNode,+ phase: 'transit',+ },+ };+ }++ const nextAttempt = graphState.attempts + 1;+ const previousError = graphState.nodeStepLimitExceeded+ ? `The node reached its action budget. ${extraction.error}`+ : extraction.error;+ const extractionPrompt = this.renderPrompt({+ extraction_task: {+ instruction:+ graphState.incomingEdge.output?.instruction ?? DEFAULT_NODE_OUTPUT_EXTRACTION_INSTRUCTION,+ format_instruction: NODE_OUTPUT_EXTRACTION_FORMAT,+ output_schema: this.getOutputSchema(graphState.incomingEdge) as PromptObject,+ previous_error: previousError,+ },+ });const payload: GeneralAgentCallLLMInstructionPayload = {- messages,- model: state.modelRuntimeConfig?.model ?? '',- provider: state.modelRuntimeConfig?.provider ?? '',- tools,+ allowedToolNames: [],+ messages: [...input.state.messages, { content: extractionPrompt, role: 'user' as const }],+ model: input.state.modelRuntimeConfig?.model ?? '',+ provider: input.state.modelRuntimeConfig?.provider ?? '',+ tools: [],};- return { payload, stepLabel: gc.currentNode, type: 'call_llm' };+ return {+ graphContext: input.graphContext,+ graphState: {+ ...graphState,+ active: true,+ attempts: nextAttempt,+ },+ instruction: {+ payload,+ stepLabel: `${graphState.currentNode}:extract`,+ type: 'call_llm',+ },+ };}- /**- * After an agent node's tool loop finishes, do an extra LLM call- * to extract structured output from the conversation.- */- private startExtraction(state: AgentState, gc: GraphContext): AgentInstruction {- const node = this.graph.states[gc.currentNode];+ private onTransit(input: ReducerInput): GraphOrchestration {+ const graphState = input.graphState as Extract<GraphState, { phase: 'transit' }>;++ const output = this.storeSelectors.nodeStore(graphState.currentNode)(input.graphContext);+ const edgeSelection = this.selectNextEdge(graphState.currentNode, output, input.graphContext);- const extractionPrompt =- `Based on the research and information gathered above, ` +- `extract and summarize your findings into a JSON object that conforms to this schema:\n` +- `\`\`\`json\n${JSON.stringify(node.outputSchema, null, 2)}\n\`\`\`\n` +- `Only output valid JSON, no other text.`;+ if (edgeSelection.reason === 'blocked_by_limit') {+ return {+ graphContext: input.graphContext,+ graphState: {+ reason: 'error_recovery',+ reasonDetail:+ `graph_edge_limit_reached: Graph "${this.graph.name}" reached maxTraversals for edge ` ++ `"${edgeSelection.edge.from}" -> "${edgeSelection.edge.to}"`,+ phase: 'fin',+ },+ };+ }- gc.extracting = true;- this.saveGraphContext(state, gc);+ if (edgeSelection.reason === 'no_match') {+ if (graphState.currentNode === this.graph.terminal) {+ return {+ graphContext: input.graphContext,+ graphState: {+ reason: 'completed',+ reasonDetail: `graph_completed: Graph "${this.graph.name}" completed at terminal node "${graphState.currentNode}"`,+ phase: 'fin',+ },+ };+ }- const messages = [...state.messages, { content: extractionPrompt, role: 'user' as const }];+ return {+ graphContext: input.graphContext,+ graphState: {+ reason: 'error_recovery',+ reasonDetail: `graph_no_valid_edge: No valid edge from node "${graphState.currentNode}"`,+ phase: 'fin',+ },+ };+ }- const payload: GeneralAgentCallLLMInstructionPayload = {- messages,- model: state.modelRuntimeConfig?.model ?? '',- provider: state.modelRuntimeConfig?.provider ?? '',- tools: [], // No tools for extraction- };+ const { edge } = edgeSelection;- return { payload, stepLabel: `${gc.currentNode}:extract`, type: 'call_llm' };+ if (!this.getNodeById(edge.to)) {+ return {+ graphContext: input.graphContext,+ graphState: {+ reason: 'error_recovery',+ reasonDetail: `graph_node_missing: Graph edge target "${edge.to}" not found`,+ phase: 'fin',+ },+ };+ }++ return {+ graphContext: this.updateEdgeTraversalCount(input.graphContext, edge),+ graphState: {+ active: false,+ currentNode: edge.to,+ incomingEdge: edge,+ phase: 'node_in',+ },+ };}- /**- * Called when a node completes. Extract output, eval transitions, advance graph.- */- private onNodeComplete(state: AgentState, gc: GraphContext): AgentInstruction {- const currentNodeId = gc.currentNode;+ private onFin(input: ReducerInput): GraphOrchestration {+ return { graphContext: input.graphContext, graphState: input.graphState };+ }- const output = this.extractStructuredOutput(state);- gc.store[currentNodeId] = output;- gc.nodeActive = false;+ private resolveRuntimeInstruction(+ orchestration: GraphOrchestration,+ ): AgentInstruction | AgentInstruction[] | undefined {+ if (orchestration.instruction) return orchestration.instruction;+ const { graphState: nextGraphState } = orchestration;- // Terminal node → done- if (currentNodeId === this.graph.terminal) {- this.saveGraphContext(state, gc);+ if (nextGraphState.phase === 'fin') {return {- reason: 'completed',- reasonDetail: `Graph "${this.graph.name}" completed at terminal node "${currentNodeId}"`,+ reason: nextGraphState.reason,+ reasonDetail: nextGraphState.reasonDetail,type: 'finish',};}+ }++ private hasFinishInstruction(instruction: AgentInstruction | AgentInstruction[]): boolean {+ return Array.isArray(instruction)+ ? instruction.some((item) => item.type === 'finish')+ : instruction.type === 'finish';+ }- // Evaluate transitions- const nextNodeId = this.evaluateTransitions(gc, currentNodeId, output);+ private loadGraphRuntimeState(state: Readonly<AgentState>): GraphRuntimeState {+ const graphRuntimeState = state.metadata?.[GRAPH_RUNTIME_STATE_KEY] as+ GraphRuntimeState | undefined;- if (!nextNodeId) {- this.saveGraphContext(state, gc);+ if (!graphRuntimeState) {return {- reason: 'error_recovery',- reasonDetail: `No valid transition from node "${currentNodeId}"`,- type: 'finish',+ graphContext: {+ edgeTraversalCounts: {},+ store: {},+ },+ graphState: { phase: 'init' },+ instructionCount: 0,};}- // Move to next node- gc.currentNode = nextNodeId;+ return {+ graphContext: {+ edgeTraversalCounts: graphRuntimeState.graphContext.edgeTraversalCounts ?? {},+ store: graphRuntimeState.graphContext.store ?? {},+ },+ graphState: graphRuntimeState.graphState,+ instructionCount:+ graphRuntimeState.instructionCount ??+ ((graphRuntimeState.graphContext as GraphContext & { instructionCount?: number })+ .instructionCount ||+ 0),+ };+ }++ private updateGraphRuntimeState(state: AgentState, graphRuntimeState: GraphRuntimeState): void {+ state.metadata ??= {};+ state.metadata[GRAPH_RUNTIME_STATE_KEY] = graphRuntimeState;+ }++ private updateEdgeTraversalCount(+ graphContext: Readonly<GraphContext>,+ edge: Readonly<AgentGraphEdge>,+ ): GraphContext {+ const edgeKey = this.getEdgeKey(edge);++ return {+ ...graphContext,+ edgeTraversalCounts: {+ ...graphContext.edgeTraversalCounts,+ [edgeKey]: (graphContext.edgeTraversalCounts[edgeKey] ?? 0) + 1,+ },+ };+ }++ private storeReducers = {+ nodeStore: (+ graphContext: Readonly<GraphContext>,+ nodeId: string,+ value: UnknownRecord,+ ): GraphContext => {+ return {+ ...graphContext,+ store: {+ ...graphContext.store,+ [nodeId]: value,+ },+ };+ },+ };++ private storeSelectors = {+ nodeStore: (nodeId: string) => {+ return (graphContext: Readonly<GraphContext>): UnknownRecord | undefined => {+ const value = graphContext.store[nodeId];+ return isRecord(value) ? value : undefined;+ };+ },+ };++ private getNodeTools(node: Readonly<AgentGraphNode>, state: AgentState): any[] {+ if (node.type !== 'agent') return [];- // If backtracking, clear intermediate store entries- const nodeKeys = Object.keys(this.graph.states);- const fromIdx = nodeKeys.indexOf(currentNodeId);- const toIdx = nodeKeys.indexOf(nextNodeId);- if (toIdx < fromIdx) {- for (let i = toIdx; i <= fromIdx; i++) {- delete gc.store[nodeKeys[i]];+ const rootTools =+ this.generalConfig.tools ?? state.tools ?? state.operationToolSet?.tools ?? [];+ if (!node.allowedToolApiNames) return rootTools;++ const allowedApiNames = new Set(node.allowedToolApiNames);+ const manifestMap = state.operationToolSet?.manifestMap ?? state.toolManifestMap;+ const toolNameResolver = new ToolNameResolver();+ const allowedToolNames = new Set<string>();++ for (const [identifier, manifest] of Object.entries(manifestMap)) {+ for (const api of manifest.api ?? []) {+ if (allowedApiNames.has(api.name)) {+ allowedToolNames.add(toolNameResolver.generate(identifier, api.name, manifest.type));+ }}}- this.saveGraphContext(state, gc);- return this.startNode(gc, state);+ return rootTools.filter((tool) => allowedToolNames.has(tool?.function?.name));}- private evaluateTransitions(- gc: GraphContext,- currentNodeId: string,- output: Record<string, any>,- ): string | null {- const backtrackLimitReached = gc.backtrackCount >= this.graph.maxBacktracks;-- for (const t of this.graph.transitions) {- if (t.from !== currentNodeId) continue;- try {- const result = new Function('output', `return (${t.condition})`)(output);- if (result) {- // If the transition target is a backtrack (already visited), only allow it- // when within the backtrack limit. Otherwise fall through to linear advance.- const isBacktrack = (gc.visitCount[t.to] ?? 0) > 0;- if (isBacktrack && backtrackLimitReached) continue;- return t.to;- }- } catch {- // condition eval failed, skip+ private getNodeById(nodeId: string): AgentGraphNode | undefined {+ return this.graph.nodes[nodeId];+ }++ private getEdgesFrom(nodeId: string): AgentGraphEdge[] {+ return this.graph.edges.filter((edge) => edge.from === nodeId);+ }++ private getEdgeKey(edge: Readonly<AgentGraphEdge>): string {+ return `${edge.from}->${edge.to}`;+ }++ private toPromptValue(value: unknown, seen = new WeakSet<object>()): PromptValue {+ if (+ value === undefined ||+ value === null ||+ typeof value === 'string' ||+ typeof value === 'number' ||+ typeof value === 'boolean'+ ) {+ return value;+ }++ if (typeof value === 'bigint') return value.toString();++ if (Array.isArray(value)) {+ return value.map((item) => this.toPromptValue(item, seen));+ }++ if (!isRecord(value)) return undefined;++ if (seen.has(value)) return '[Circular]';+ seen.add(value);++ const promptObject: PromptObject = {};+ for (const [key, item] of Object.entries(value)) {+ promptObject[key] = this.toPromptValue(item, seen);+ }++ seen.delete(value);+ return promptObject;+ }++ private resolveNodeInputContext(+ edge: Readonly<AgentGraphEdge>,+ input: ReducerInput,+ ): PromptObject {+ const fields = edge.input?.fields;+ const sourceOutput = this.storeSelectors.nodeStore(edge.from)(input.graphContext);++ if (!fields || fields.length === 0) {+ return { value: this.toPromptValue(sourceOutput ?? {}) };+ }++ const inputFields: PromptObject = {};+ const rawFallback: PromptObject = {};++ for (const field of fields) {+ const source = this.storeSelectors.nodeStore(field.from)(input.graphContext);+ const value = this.readValue(source, field.field);+ const registeredField = this.graph.fields[field.field];++ if (value !== undefined) {+ inputFields[field.field] = {+ desc: field.desc ?? registeredField?.desc ?? field.field,+ value: this.toPromptValue(value),+ };+ continue;+ }++ if (source?._raw !== undefined && rawFallback[field.from] === undefined) {+ rawFallback[field.from] = {+ reason:+ 'Declared input fields were missing from this source output. Use this raw source output as fallback context.',+ value: this.toPromptValue(source._raw),+ };}}- return this.getNextState(currentNodeId);+ return {+ fields: inputFields,+ rawFallback: Object.keys(rawFallback).length > 0 ? rawFallback : undefined,+ };}- private getNextState(currentNodeId: string): string | null {- const keys = Object.keys(this.graph.states);- const idx = keys.indexOf(currentNodeId);- return idx >= 0 && idx + 1 < keys.length ? keys[idx + 1] : null;+ private validateNodeOutput(+ edge: Readonly<AgentGraphEdge>,+ output: Readonly<UnknownRecord>,+ ): OutputValidation {+ const fields = edge.output?.fields;++ if (!fields || fields.length === 0) return { ok: true };++ const outputSchema = this.getOutputSchema(edge);++ if (ajv.validate(outputSchema, output) === true) return { ok: true };++ const errors = ajv.errors ?? [];++ return {+ error:+ `The selected edge "${edge.from}" -> "${edge.to}" requires an output object that matches this schema:\n` ++ `\`\`\`json\n${JSON.stringify(outputSchema, null, 2)}\n\`\`\`\n` ++ (errors.length === 0+ ? 'The previous JSON object did not match the selected edge output schema.'+ : errors+ .slice(0, 8)+ .map((error) => {+ const path = error.instancePath || '/';+ return `${path} ${error.message ?? 'does not match the output schema'}`;+ })+ .join('\n')),+ ok: false,+ };}- private renderPrompt(template: string, gc: GraphContext): string {- return template.replaceAll(/\{\{(\w+)\.(\w+)\}\}/g, (_, stateId, field) => {- if (stateId === 'input' && field === 'question') {- return gc.input;+ private getOutputSchema(edge: Readonly<AgentGraphEdge>): UnknownRecord {+ const fields = edge.output?.fields ?? [];++ return {+ additionalProperties: true,+ properties: Object.fromEntries(+ fields.map((field) => {+ const registeredField = this.graph.fields[field.field];++ return [+ field.field,+ {+ ...registeredField?.schema,+ description: field.desc ?? registeredField?.desc ?? field.field,+ },+ ];+ }),+ ),+ required: fields.filter((field) => field.required !== false).map((field) => field.field),+ type: 'object',+ };+ }++ private readValue(source: UnknownRecord | undefined, path: string): unknown {+ if (!source) return undefined;++ return path.split('.').reduce<unknown>((value, key) => {+ return isRecord(value) ? value[key] : undefined;+ }, source);+ }++ private selectNextEdge(+ currentNode: string,+ output: UnknownRecord | undefined,+ graphContext: Readonly<GraphContext>,+ ): EdgeSelection {+ let blockedEdge: AgentGraphEdge | undefined;+ let defaultEdge: AgentGraphEdge | undefined;++ for (const edge of this.getEdgesFrom(currentNode)) {+ if (!edge.condition) {+ defaultEdge ??= edge;+ continue;}+ if (!this.evaluateEdgeCondition(edge, output)) continue;- const data = gc.store[stateId];- if (!data) return `(${stateId} has no data yet)`;- const val = data[field];- if (val === undefined) return `(${stateId}.${field} has no data)`;- return typeof val === 'string' ? val : JSON.stringify(val, null, 2);- });+ const edgeKey = this.getEdgeKey(edge);+ const traversalCount = graphContext.edgeTraversalCounts[edgeKey] ?? 0;++ if (edge.maxTraversals !== undefined && traversalCount >= edge.maxTraversals) {+ blockedEdge ??= edge;+ continue;+ }++ return { edge, reason: 'matched' };+ }++ if (defaultEdge) {+ const edgeKey = this.getEdgeKey(defaultEdge);+ const traversalCount = graphContext.edgeTraversalCounts[edgeKey] ?? 0;++ if (defaultEdge.maxTraversals !== undefined && traversalCount >= defaultEdge.maxTraversals) {+ return { edge: defaultEdge, reason: 'blocked_by_limit' };+ }++ return { edge: defaultEdge, reason: 'matched' };+ }++ if (blockedEdge) return { edge: blockedEdge, reason: 'blocked_by_limit' };++ return { reason: 'no_match' };}- private extractStructuredOutput(state: AgentState): Record<string, any> {- const lastAssistantMessage = [...state.messages]- .reverse()- .find((m: any) => m.role === 'assistant');+ private evaluateEdgeCondition(edge: Readonly<AgentGraphEdge>, output: UnknownRecord | undefined) {+ if (!edge.condition || !output) return false;- if (!lastAssistantMessage) return {};+ try {+ return conditionAjv.validate(edge.condition, output) === true;+ } catch {+ return false;+ }+ }+ private extractNodeOutput(input: ReducerInput): NodeOutputExtraction {+ const payload = input.context.payload;+ const payloadResult = isRecord(payload) ? payload.result : undefined;+ const contentFromPayload =+ isRecord(payloadResult) && typeof payloadResult.content === 'string'+ ? payloadResult.content+ : undefined;+ const lastAssistantMessage = [...input.state.messages]+ .reverse()+ .find((message) => message.role === 'assistant');const content =- typeof lastAssistantMessage.content === 'string' ? lastAssistantMessage.content : '';+ contentFromPayload ??+ (typeof lastAssistantMessage?.content === 'string'+ ? lastAssistantMessage.content+ : (JSON.stringify(lastAssistantMessage?.content ?? '') ?? ''));- // Extract JSON from markdown code blocks or raw contentconst fenceStart = content.indexOf('```');- let jsonStr: string;+ let jsonText = content.trim();+if (fenceStart !== -1) {const contentAfterFence = content.slice(fenceStart + 3);- // Skip optional language tag (e.g. "json\n")- const newlineIdx = contentAfterFence.indexOf('\n');- const bodyStart = newlineIdx !== -1 ? newlineIdx + 1 : 0;+ const newlineIndex = contentAfterFence.indexOf('\n');+ const bodyStart = newlineIndex === -1 ? 0 : newlineIndex + 1;const fenceEnd = contentAfterFence.indexOf('```', bodyStart);- jsonStr = (- fenceEnd !== -1- ? contentAfterFence.slice(bodyStart, fenceEnd)- : contentAfterFence.slice(bodyStart)+ jsonText = (+ fenceEnd === -1+ ? contentAfterFence.slice(bodyStart)+ : contentAfterFence.slice(bodyStart, fenceEnd)).trim();- } else {- jsonStr = content.trim();}try {- return JSON.parse(jsonStr);+ const parsed: unknown = JSON.parse(jsonText);++ if (isRecord(parsed)) return { ok: true, output: parsed, raw: content };} catch {- return { _raw: content };+ return {+ error: 'The node output is not valid JSON.',+ ok: false,+ raw: content,+ };}- }- private getGraphContext(state: AgentState): GraphContext | null {- return (state.metadata?.[GRAPH_CONTEXT_KEY] as GraphContext) ?? null;+ return {+ error: 'The node output JSON must be an object.',+ ok: false,+ raw: content,+ };}- private saveGraphContext(state: AgentState, gc: GraphContext): void {- if (!state.metadata) state.metadata = {};- state.metadata[GRAPH_CONTEXT_KEY] = gc;+ private renderPrompt(input: PromptObject, separator = '\n\n'): string {+ const escapeXmlContent = (value: string): string =>+ value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');++ const renderEntry = (key: string, value: PromptValue): string => {+ if (value === undefined || value === null || value === '') return '';++ const name = key.replaceAll(/[^\w.-]/g, '_');++ if (Array.isArray(value)) {+ return value+ .map((item) => renderEntry(name, item))+ .filter(Boolean)+ .join('\n');+ }++ if (value && typeof value === 'object') {+ const content = this.renderPrompt(value as PromptObject, '\n');+ return content ? `<${name}>\n${content}\n</${name}>` : '';+ }++ const content = typeof value === 'string' ? value : (JSON.stringify(value, null, 2) ?? '');++ return `<${name}>${escapeXmlContent(content)}</${name}>`;+ };++ return Object.entries(input)+ .map(([key, value]) => renderEntry(key, value))+ .filter(Boolean)+ .join(separator);}}diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 26f5327436d..3c91e25d118 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -94,6 +94,7 @@ describe('GeneralChatAgent', () => {messages: state.messages,model: 'gpt-4o-mini',provider: 'openai',+ tools: undefined,},});});@@ -119,10 +120,45 @@ describe('GeneralChatAgent', () => {payload: {messages: state.messages,message: { role: 'user', content: 'What is the weather?' },+ tools: undefined,},});});+ it('should not infer allowedToolNames from normal state tools', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });+ const state = createMockState({+ messages: [{ role: 'user', content: 'Use tools if needed' }] as any,+ tools: [{ function: { name: 'workspace____read' }, type: 'function' }] as any,+ });++ const result = await agent.runner(createMockContext('user_input'), state);++ expect((result as any).payload).not.toHaveProperty('allowedToolNames');+ expect((result as any).payload.tools).toBe(state.tools);+ });++ it('should pass explicit allowedToolNames from config', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ allowedToolNames: ['workspace____read'],+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ tools: [{ function: { name: 'workspace____read' }, type: 'function' }],+ });+ const state = createMockState({+ messages: [{ role: 'user', content: 'Use read only' }] as any,+ });++ const result = await agent.runner(createMockContext('user_input'), state);++ expect((result as any).payload.allowedToolNames).toEqual(['workspace____read']);+ });+it('should trigger compression using thresholdRatio from compressionConfig', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },@@ -667,6 +703,7 @@ describe('GeneralChatAgent', () => {expect(result).toEqual({type: 'call_llm',payload: {+ assistantMessageId: undefined,messages: state.messages,model: 'gpt-4o-mini',parentMessageId: 'tool-msg-1',@@ -702,6 +739,7 @@ describe('GeneralChatAgent', () => {expect(result).toEqual({type: 'call_llm',payload: {+ assistantMessageId: undefined,messages: state.messages,model: 'gpt-4o-mini',parentMessageId: 'tool-msg-1',@@ -737,6 +775,7 @@ describe('GeneralChatAgent', () => {expect(result).toEqual({type: 'call_llm',payload: {+ assistantMessageId: undefined,messages: state.messages,model: 'gpt-4o-mini',parentMessageId: 'tool-msg-1',@@ -1100,6 +1139,7 @@ describe('GeneralChatAgent', () => {expect(result).toEqual({type: 'call_llm',payload: {+ assistantMessageId: undefined,messages: state.messages,model: 'gpt-4o-mini',parentMessageId: 'tool-msg-2',diff --git a/packages/agent-runtime/src/agents/__tests__/GraphAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GraphAgent.test.tsnew file mode 100644index 00000000000..671c31d3920--- /dev/null+++ b/packages/agent-runtime/src/agents/__tests__/GraphAgent.test.ts@@ -0,0 +1,1279 @@+import { readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import { ToolNameResolver } from '@lobechat/context-engine';+import type { ReasoningGraph } 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 { GraphAgent } from '../GraphAgent';++const GRAPH_RUNTIME_STATE_KEY = '__graphRuntimeState';+const TEST_DIR = path.dirname(fileURLToPath(import.meta.url));++interface TestGraphRuntimeState {+ graphContext: {+ store: Record<PropertyKey, unknown>;+ };+ graphState: unknown;+ instructionCount: number;+}++const toolNameResolver = new ToolNameResolver();+const readToolName = toolNameResolver.generate('workspace', 'read', 'builtin');+const searchToolName = toolNameResolver.generate('workspace', 'search', 'builtin');+const writeToolName = toolNameResolver.generate('workspace', 'write', 'builtin');++const createMockState = (overrides?: Partial<AgentState>): AgentState => ({+ operationId: 'test-operation',+ status: 'running',+ messages: [],+ toolManifestMap: {+ workspace: {+ api: [{ name: 'read' }, { name: 'search' }, { name: 'write' }],+ type: 'builtin',+ },+ },+ tools: [+ { function: { name: readToolName }, type: 'function' },+ { function: { name: searchToolName }, type: 'function' },+ { function: { name: writeToolName }, type: 'function' },+ ],+ usage: {+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: { totalCalls: 0, totalTimeMs: 0, byTool: [] },+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ },+ cost: {+ calculatedAt: new Date().toISOString(),+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+ },+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ stepCount: 0,+ ...overrides,+});++const createContext = (+ phase: AgentRuntimeContext['phase'],+ payload?: AgentRuntimeContext['payload'],+): AgentRuntimeContext => ({ payload, phase });++const createLlmResultContext = (content: string): AgentRuntimeContext =>+ createContext('llm_result', {+ hasToolsCalling: false,+ result: { content, tool_calls: [] },+ toolsCalling: [],+ });++const getGraphRuntimeState = (state: AgentState) =>+ state.metadata?.[GRAPH_RUNTIME_STATE_KEY] as TestGraphRuntimeState | undefined;++const getGraphState = (state: AgentState) => getGraphRuntimeState(state)?.graphState;++const getGraphStore = (state: AgentState) => getGraphRuntimeState(state)?.graphContext.store;++const getInstructionCount = (state: AgentState) => getGraphRuntimeState(state)?.instructionCount;++const expectCallLlm = (instruction: AgentInstruction | AgentInstruction[]) => {+ expect(Array.isArray(instruction)).toBe(false);+ expect(instruction).toMatchObject({ type: 'call_llm' });++ return instruction as Extract<AgentInstruction, { type: 'call_llm' }>;+};++const getLastPrompt = (instruction: AgentInstruction | AgentInstruction[]) => {+ const callLlm = expectCallLlm(instruction);+ const lastMessage = callLlm.payload.messages.at(-1);++ return typeof lastMessage?.content === 'string' ? lastMessage.content : '';+};++const loadGoalLoopGraph = (): ReasoningGraph => {+ const graph = JSON.parse(+ readFileSync(path.join(TEST_DIR, 'fixtures/goal-loop.graph.json'), 'utf8'),+ );+ const result = ReasoningGraphSchema.safeParse(graph);++ if (!result.success) {+ throw new Error(JSON.stringify(result.error.format(), null, 2));+ }++ return result.data;+};++const parseGraph = (graph: unknown) => ReasoningGraphSchema.safeParse(graph);++describe('GraphAgent', () => {+ describe('schema', () => {+ it('should accept the goal-loop fixture', () => {+ expect(parseGraph(loadGoalLoopGraph()).success).toBe(true);+ });++ it('should require exactly one root edge', () => {+ const graph = loadGoalLoopGraph();+ const result = parseGraph({+ ...graph,+ edges: graph.edges.filter((edge) => edge.from !== AGENT_GRAPH_ROOT_NODE_ID),+ });++ expect(result.success).toBe(false);+ expect(result.error?.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ message: `Graph must define exactly one "${AGENT_GRAPH_ROOT_NODE_ID}" outgoing edge`,+ path: ['edges'],+ }),+ ]),+ );+ });++ it('should reject edge endpoints that do not reference graph nodes', () => {+ const graph = loadGoalLoopGraph();+ const result = parseGraph({+ ...graph,+ edges: [+ ...graph.edges,+ {+ from: 'missing-source',+ instruction: 'Invalid source',+ to: 'missing-target',+ },+ ],+ });++ expect(result.success).toBe(false);+ expect(result.error?.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ message: `Edge from must reference an existing node or "${AGENT_GRAPH_ROOT_NODE_ID}"`,+ path: ['edges', graph.edges.length, 'from'],+ }),+ expect.objectContaining({+ message: 'Edge to must reference an existing node',+ path: ['edges', graph.edges.length, 'to'],+ }),+ ]),+ );+ });++ it('should require edge field refs to point at registered graph fields', () => {+ const graph = loadGoalLoopGraph();+ const result = parseGraph({+ ...graph,+ edges: graph.edges.map((edge) =>+ edge.from === 'plan'+ ? {+ ...edge,+ input: {+ fields: [{ field: 'missing-field', from: 'plan' }],+ },+ }+ : edge,+ ),+ });++ expect(result.success).toBe(false);+ expect(result.error?.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ message: 'Edge input field "missing-field" must reference a registered graph field',+ }),+ ]),+ );+ });++ it('should reject duplicate default edges from the same source', () => {+ const graph = loadGoalLoopGraph();+ const planEdge = graph.edges.find((edge) => edge.from === 'plan');+ const result = parseGraph({+ ...graph,+ edges: [+ ...graph.edges,+ {+ ...planEdge,+ instruction: 'Another default plan edge',+ },+ ],+ });++ expect(result.success).toBe(false);+ expect(result.error?.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ message: 'Only one default edge without condition is allowed from "plan"',+ }),+ ]),+ );+ });++ it('should require condition to be a JSON schema object', () => {+ const graph = loadGoalLoopGraph();+ const result = parseGraph({+ ...graph,+ edges: graph.edges.map((edge) =>+ edge.from === 'verify'+ ? {+ ...edge,+ condition: 'output.review.fin === false',+ }+ : edge,+ ),+ });++ expect(result.success).toBe(false);+ expect(result.error?.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ path: ['edges', 3, 'condition'],+ }),+ ]),+ );+ });++ it('should reject invalid field JSON schemas', () => {+ const graph = loadGoalLoopGraph();+ const result = parseGraph({+ ...graph,+ fields: {+ ...graph.fields,+ goals: {+ ...graph.fields.goals,+ schema: {+ type: 1,+ },+ },+ },+ });++ expect(result.success).toBe(false);+ expect(result.error?.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ message: expect.stringContaining(+ 'Graph field "goals" schema must be a valid JSON Schema',+ ),+ path: ['fields', 'goals', 'schema'],+ }),+ ]),+ );+ });++ it('should reject descriptions inside field JSON schemas', () => {+ const graph = loadGoalLoopGraph();+ const result = parseGraph({+ ...graph,+ fields: {+ ...graph.fields,+ goals: {+ ...graph.fields.goals,+ schema: {+ ...graph.fields.goals.schema,+ items: {+ ...(graph.fields.goals.schema.items as Record<string, unknown>),+ properties: {+ desc: {+ description: 'Do not put prompt wording inside JSON Schema.',+ type: 'string',+ },+ name: {+ type: 'string',+ },+ },+ },+ },+ },+ },+ });++ expect(result.success).toBe(false);+ expect(result.error?.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ message:+ 'Graph field "goals" schema must not contain "description"; field schemas are only for validation. Use the graph field desc or edge field desc instead.',+ path: ['fields', 'goals', 'schema', 'items', 'properties', 'desc', 'description'],+ }),+ ]),+ );+ });++ it('should allow description as a schema property name', () => {+ const graph = loadGoalLoopGraph();+ const result = parseGraph({+ ...graph,+ fields: {+ ...graph.fields,+ goals: {+ ...graph.fields.goals,+ schema: {+ type: 'object',+ properties: {+ description: {+ type: 'string',+ },+ },+ required: ['description'],+ },+ },+ },+ });++ expect(result.success).toBe(true);+ });++ it('should reject invalid condition JSON schemas before runtime routing', () => {+ const graph = loadGoalLoopGraph();+ const result = parseGraph({+ ...graph,+ edges: graph.edges.map((edge) =>+ edge.from === 'verify'+ ? {+ ...edge,+ condition: {+ unknownKeyword: true,+ },+ }+ : edge,+ ),+ });++ expect(result.success).toBe(false);+ expect(result.error?.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ message: expect.stringContaining('Edge condition must be a valid JSON Schema'),+ path: ['edges', 3, 'condition'],+ }),+ ]),+ );+ });++ it('should reject terminal nodes that do not exist', () => {+ const graph = loadGoalLoopGraph();+ const result = parseGraph({+ ...graph,+ terminal: 'missing-terminal',+ });++ expect(result.success).toBe(false);+ expect(result.error?.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ message: 'Graph terminal must reference an existing node',+ path: ['terminal'],+ }),+ ]),+ );+ });++ it('should reject input fields whose source node does not exist', () => {+ const graph = loadGoalLoopGraph();+ const result = parseGraph({+ ...graph,+ edges: graph.edges.map((edge) =>+ edge.from === 'work'+ ? {+ ...edge,+ input: {+ fields: [{ field: 'summary', from: 'missing-node' }],+ },+ }+ : edge,+ ),+ });++ expect(result.success).toBe(false);+ expect(result.error?.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ message:+ 'Edge input source node "missing-node" must reference an existing node or "__root__"',+ }),+ ]),+ );+ });++ it('should reject duplicate input and output fields on the same edge', () => {+ const graph = loadGoalLoopGraph();+ const result = parseGraph({+ ...graph,+ edges: graph.edges.map((edge) =>+ edge.from === 'plan'+ ? {+ ...edge,+ input: {+ fields: [+ { field: 'goals', from: 'plan' },+ { field: 'goals', from: 'plan' },+ ],+ },+ output: {+ fields: [{ field: 'summary' }, { field: 'summary' }],+ },+ }+ : edge,+ ),+ });++ expect(result.success).toBe(false);+ expect(result.error?.issues).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ message: 'Edge input field "goals" is duplicated',+ }),+ expect.objectContaining({+ message: 'Edge output field "summary" is duplicated',+ }),+ ]),+ );+ });+ });++ describe('prompt', () => {+ it('should render node instruction, upstream field value, upstream field description, and deliverable target', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: loadGoalLoopGraph(),+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal verify prompt contract', role: 'user' }],+ });++ await agent.runner(createContext('init'), state);++ const goals = [+ {+ desc: 'Ensure prompt contains values and field semantics.',+ name: 'close prompt loop',+ },+ ];+ const workInstruction = await agent.runner(+ 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(+ '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.');+ });++ it('should render multi-source input context and verifier output contract', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: loadGoalLoopGraph(),+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal verify multi-source prompt', role: 'user' }],+ });++ await agent.runner(createContext('init'), state);++ const goals = [+ {+ desc: 'Render upstream plan fields and worker result together.',+ name: 'join context',+ },+ ];+ await agent.runner(createLlmResultContext(JSON.stringify({ goals })), state);++ const summary = 'The worker joined context from plan and work.';+ const verifyInstruction = await agent.runner(+ createLlmResultContext(JSON.stringify({ summary })),+ state,+ );+ const prompt = getLastPrompt(verifyInstruction);++ expect(prompt).toContain(+ '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.');+ });++ it('should render extraction instruction, format instruction, schema, and previous error', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: loadGoalLoopGraph(),+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal verify extraction prompt', role: 'user' }],+ });++ await agent.runner(createContext('init'), state);++ const extractionInstruction = await agent.runner(+ createLlmResultContext('planning notes without json'),+ state,+ );+ const prompt = getLastPrompt(extractionInstruction);++ expect(prompt).toContain('<extraction_task>');+ expect(prompt).toContain('<format_instruction>');+ expect(prompt).not.toContain('<output_format>');+ expect(prompt).toContain('Extract the planned goals.');+ expect(prompt).toContain('markdown fenced code block tagged json');+ expect(prompt).toContain('<output_schema>');+ 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.');+ });++ it('should render raw fallback context once when declared input fields are missing', async () => {+ const goalLoopGraph = loadGoalLoopGraph();+ const graph: ReasoningGraph = {+ ...goalLoopGraph,+ edges: goalLoopGraph.edges.map((edge) =>+ edge.from === 'plan'+ ? {+ ...edge,+ input: {+ fields: [+ { field: 'goals', from: 'plan' },+ { field: 'summary', from: 'plan' },+ ],+ },+ }+ : edge,+ ),+ };+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph,+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal verify raw fallback prompt', role: 'user' }],+ });++ await agent.runner(createContext('init'), state);++ let workInstruction: AgentInstruction | AgentInstruction[] | undefined;+ for (const content of [+ 'not json',+ 'still not json',+ 'nope',+ 'plan failed but left useful raw planning notes',+ ]) {+ workInstruction = await agent.runner(createLlmResultContext(content), state);+ }+ if (!workInstruction) throw new Error('Expected work instruction');+ const prompt = getLastPrompt(workInstruction);++ expect(prompt).toContain('rawFallback');+ expect(prompt).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);+ });+ });++ describe('e2e', () => {+ it('should keep the goal-loop fixture aligned with the graph schema', () => {+ const graph = loadGoalLoopGraph();++ expect(graph.terminal).toBe('verify');+ expect(graph.nodes).toMatchObject({+ plan: { allowedToolApiNames: ['read', 'search'], type: 'agent' },+ verify: { type: 'llm' },+ work: { type: 'agent' },+ });+ expect(graph.edges).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ from: AGENT_GRAPH_ROOT_NODE_ID,+ to: 'plan',+ }),+ expect.objectContaining({+ from: 'verify',+ maxTraversals: 3,+ to: 'work',+ }),+ ]),+ );+ });++ it('should execute the /goal plan-work-verify loop with mocked llm outputs', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: loadGoalLoopGraph(),+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal refactor graph agent runtime', role: 'user' }],+ });++ const planInstruction = await agent.runner(createContext('init'), state);+ const planCall = expectCallLlm(planInstruction);++ expect(planCall.stepLabel).toBe('plan');+ expect(planCall.payload.allowedToolNames).toEqual([readToolName, searchToolName]);+ const planTools = planCall.payload.tools as Array<{ function: { name: string } }> | undefined;+ expect(planTools?.map((tool) => tool.function.name)).toEqual([readToolName, searchToolName]);+ expect(getGraphStore(state)?.[AGENT_GRAPH_ROOT_NODE_ID]).toEqual({+ query: '/goal refactor graph agent runtime',+ });+ expect(getLastPrompt(planInstruction)).toContain('/goal refactor graph agent runtime');++ const goals = [+ { desc: 'Define the graph schema for goal loops.', name: 'design schema' },+ { desc: 'Cover the plan-work-verify loop with tests.', name: 'add tests' },+ ];+ const workInstruction = await agent.runner(+ createLlmResultContext(`\`\`\`json\n${JSON.stringify({ goals })}\n\`\`\``),+ state,+ );++ expect(getGraphStore(state)?.plan).toEqual({ goals });+ expect(getGraphState(state)).toMatchObject({ currentNode: 'work', phase: 'node_in' });+ const workCall = expectCallLlm(workInstruction);+ expect(workCall.stepLabel).toBe('work');+ expect(workCall.payload.allowedToolNames).toBeUndefined();+ expect(getLastPrompt(workInstruction)).toContain('design schema');+ expect(getLastPrompt(workInstruction)).toContain(+ 'Cover the plan-work-verify loop with tests.',+ );++ const firstSummary = 'Implemented the graph schema and started the test wiring.';+ const verifyInstruction = await agent.runner(+ createLlmResultContext(JSON.stringify({ summary: firstSummary })),+ state,+ );++ expect(getGraphStore(state)?.work).toEqual({ summary: firstSummary });+ expect(getGraphState(state)).toMatchObject({ currentNode: 'verify', phase: 'node_in' });+ const verifyCall = expectCallLlm(verifyInstruction);+ 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);++ const unfinishedGoal = {+ desc: 'The goal-loop E2E still needs a passing verification branch.',+ name: 'finish tests',+ };+ const reworkInstruction = await agent.runner(+ createLlmResultContext(+ JSON.stringify({+ review: {+ fin: false,+ unfinish: [unfinishedGoal],+ },+ }),+ ),+ state,+ );++ expect(getGraphStore(state)?.verify).toEqual({+ review: {+ fin: false,+ unfinish: [unfinishedGoal],+ },+ });+ 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(+ 'The goal-loop E2E still needs a passing verification branch.',+ );++ const finalSummary = 'Completed schema, runtime wiring, and goal-loop E2E tests.';+ const finalVerifyInstruction = await agent.runner(+ createLlmResultContext(JSON.stringify({ summary: finalSummary })),+ state,+ );++ 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);++ const result = await agent.runner(+ createLlmResultContext(+ JSON.stringify({+ review: {+ fin: true,+ unfinish: [],+ },+ }),+ ),+ state,+ );++ expect(getGraphStore(state)?.verify).toEqual({+ review: {+ fin: true,+ unfinish: [],+ },+ });+ expect(getGraphState(state)).toMatchObject({ phase: 'fin', reason: 'completed' });+ expect(result).toMatchObject({ reason: 'completed', type: 'finish' });+ });++ it('should preserve node tool allow-list when delegating to GeneralChatAgent', 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 inspect workspace', role: 'user' }],+ });++ expectCallLlm(await agent.runner(createContext('init'), state));++ const instruction = await agent.runner(+ createContext('tools_batch_result', { parentMessageId: 'tool-msg-1' }),+ state,+ );+ const call = expectCallLlm(instruction);++ expect(call.payload.allowedToolNames).toEqual([readToolName, searchToolName]);+ expect(+ call.payload.tools?.map((tool: { function: { name: string } }) => tool.function.name),+ ).toEqual([readToolName, searchToolName]);+ });++ it('should not add a tool allow-list when delegating an unrestricted agent node', async () => {+ const graph = loadGoalLoopGraph();+ const planNode = graph.nodes.plan;+ if (planNode.type !== 'agent') throw new Error('Expected plan to be an agent node');+ const { allowedToolApiNames: _, ...unrestrictedPlan } = planNode;+ graph.nodes.plan = unrestrictedPlan;+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph,+ modelRuntimeConfig: { model: 'gpt-4', provider: 'openai' },+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal inspect workspace', role: 'user' }],+ });++ const initialCall = expectCallLlm(await agent.runner(createContext('init'), state));+ expect(initialCall.payload.allowedToolNames).toBeUndefined();++ const instruction = await agent.runner(+ createContext('tools_batch_result', { parentMessageId: 'tool-msg-1' }),+ state,+ );+ const delegatedCall = expectCallLlm(instruction);++ expect(delegatedCall.payload.allowedToolNames).toBeUndefined();+ expect(+ delegatedCall.payload.tools?.map(+ (tool: { function: { name: string } }) => tool.function.name,+ ),+ ).toEqual([readToolName, searchToolName, writeToolName]);+ });++ it('should stop before producing more runtime instructions when maxInstructionCount is reached', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: {+ ...loadGoalLoopGraph(),+ maxInstructionCount: 1,+ },+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal stop after first instruction', role: 'user' }],+ });++ expectCallLlm(await agent.runner(createContext('init'), state));+ expect(getInstructionCount(state)).toBe(1);++ const result = await agent.runner(+ createLlmResultContext(+ JSON.stringify({+ goals: [{ desc: 'This output should not be consumed.', name: 'ignored' }],+ }),+ ),+ state,+ );++ expect(result).toMatchObject({+ reason: 'error_recovery',+ reasonDetail: expect.stringContaining('graph_instruction_limit_reached'),+ type: 'finish',+ });+ expect(getInstructionCount(state)).toBe(1);+ expect(getGraphStore(state)?.plan).toBeUndefined();+ });++ it('should not increment instructionCount for graph finish instructions', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: loadGoalLoopGraph(),+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal finish without extra instruction count', role: 'user' }],+ });++ expectCallLlm(await agent.runner(createContext('init'), state));+ expectCallLlm(+ await agent.runner(+ createLlmResultContext(+ JSON.stringify({+ goals: [{ desc: 'Finish counting should remain stable.', name: 'count' }],+ }),+ ),+ state,+ ),+ );+ expectCallLlm(+ await agent.runner(+ createLlmResultContext(JSON.stringify({ summary: 'Completed the count goal.' })),+ state,+ ),+ );+ expect(getInstructionCount(state)).toBe(3);++ const result = await agent.runner(+ createLlmResultContext(JSON.stringify({ review: { fin: true, unfinish: [] } })),+ state,+ );++ expect(result).toMatchObject({ reason: 'completed', type: 'finish' });+ expect(getInstructionCount(state)).toBe(3);+ });++ it('should skip output extraction when the incoming edge does not declare output fields', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: {+ edges: [+ {+ from: AGENT_GRAPH_ROOT_NODE_ID,+ instruction: 'Generate the final report.',+ to: 'report',+ },+ ],+ fields: {},+ name: 'report-only',+ nodes: {+ report: { type: 'llm' },+ },+ terminal: 'report',+ },+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: 'Write a final report without structured output.', role: 'user' }],+ });++ const reportInstruction = await agent.runner(createContext('init'), state);++ expect(expectCallLlm(reportInstruction).stepLabel).toBe('report');++ const result = await agent.runner(+ createLlmResultContext('## Final report\n\nThis is a natural language answer.'),+ state,+ );++ expect(result).toMatchObject({ reason: 'completed', type: 'finish' });+ expect(getGraphStore(state)?.report).toBeUndefined();+ expect(getGraphState(state)).toMatchObject({ phase: 'fin', reason: 'completed' });+ });++ it('should move an agent node to output extraction when maxAgentSteps is reached', async () => {+ const graph = loadGoalLoopGraph();+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: {+ ...graph,+ nodes: {+ ...graph.nodes,+ plan: { allowedToolApiNames: ['read', 'search'], maxAgentSteps: 1, type: 'agent' },+ },+ },+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal enforce node budget', role: 'user' }],+ });++ expectCallLlm(await agent.runner(createContext('init'), state));+ state.stepCount = 1;++ const extractionInstruction = await agent.runner(createContext('init'), state);+ const prompt = getLastPrompt(extractionInstruction);++ expect(expectCallLlm(extractionInstruction).stepLabel).toBe('plan:extract');+ expect(getGraphState(state)).toMatchObject({+ active: true,+ attempts: 1,+ currentNode: 'plan',+ nodeStepLimitExceeded: true,+ phase: 'node_out',+ });+ expect(prompt).toContain('The node reached its action budget.');+ expect(prompt).toContain('The node output JSON must be an object.');+ });++ it('should route by matching condition before default and fall back when condition misses', async () => {+ const graph: ReasoningGraph = {+ edges: [+ {+ from: AGENT_GRAPH_ROOT_NODE_ID,+ instruction: 'Produce a route value.',+ output: { fields: [{ field: 'route' }] },+ to: 'source',+ },+ {+ condition: {+ properties: {+ route: { const: 'go' },+ },+ required: ['route'],+ type: 'object',+ },+ from: 'source',+ input: { fields: [{ field: 'route', from: 'source' }] },+ instruction: 'Matched route instruction.',+ output: { fields: [{ field: 'result' }] },+ to: 'matched',+ },+ {+ from: 'source',+ input: { fields: [{ field: 'route', from: 'source' }] },+ instruction: 'Fallback route instruction.',+ output: { fields: [{ field: 'result' }] },+ to: 'fallback',+ },+ ],+ fields: {+ result: {+ desc: 'Terminal result.',+ schema: { type: 'string' },+ },+ route: {+ desc: 'Routing flag.',+ schema: { type: 'string' },+ },+ },+ name: 'condition-routing',+ nodes: {+ fallback: { type: 'llm' },+ matched: { type: 'llm' },+ source: { type: 'llm' },+ },+ terminal: 'fallback',+ };+ const matchedAgent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph,+ operationId: 'test-operation',+ });+ const matchedState = createMockState({+ messages: [{ content: '/goal route matched', role: 'user' }],+ });++ expectCallLlm(await matchedAgent.runner(createContext('init'), matchedState));+ const matchedInstruction = await matchedAgent.runner(+ createLlmResultContext(JSON.stringify({ route: 'go' })),+ matchedState,+ );++ expect(expectCallLlm(matchedInstruction).stepLabel).toBe('matched');+ expect(getLastPrompt(matchedInstruction)).toContain('Matched route instruction.');+ expect(getLastPrompt(matchedInstruction)).toContain('go');++ const fallbackAgent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph,+ operationId: 'test-operation',+ });+ const fallbackState = createMockState({+ messages: [{ content: '/goal route fallback', role: 'user' }],+ });++ expectCallLlm(await fallbackAgent.runner(createContext('init'), fallbackState));+ const fallbackInstruction = await fallbackAgent.runner(+ createLlmResultContext(JSON.stringify({ route: 'stop' })),+ fallbackState,+ );++ expect(expectCallLlm(fallbackInstruction).stepLabel).toBe('fallback');+ expect(getLastPrompt(fallbackInstruction)).toContain('Fallback route instruction.');+ expect(getLastPrompt(fallbackInstruction)).toContain('stop');+ });++ it('should treat invalid condition schemas as no match and use the default edge', async () => {+ const graph: ReasoningGraph = {+ edges: [+ {+ from: AGENT_GRAPH_ROOT_NODE_ID,+ instruction: 'Produce a route value.',+ output: { fields: [{ field: 'route' }] },+ to: 'source',+ },+ {+ condition: {+ unknownKeyword: true,+ },+ from: 'source',+ input: { fields: [{ field: 'route', from: 'source' }] },+ instruction: 'Invalid condition route.',+ output: { fields: [{ field: 'result' }] },+ to: 'matched',+ },+ {+ from: 'source',+ input: { fields: [{ field: 'route', from: 'source' }] },+ instruction: 'Default route after invalid condition.',+ output: { fields: [{ field: 'result' }] },+ to: 'fallback',+ },+ ],+ fields: {+ result: {+ desc: 'Terminal result.',+ schema: { type: 'string' },+ },+ route: {+ desc: 'Routing flag.',+ schema: { type: 'string' },+ },+ },+ name: 'invalid-condition-routing',+ nodes: {+ fallback: { type: 'llm' },+ matched: { type: 'llm' },+ source: { type: 'llm' },+ },+ terminal: 'fallback',+ };+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph,+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal invalid condition fallback', role: 'user' }],+ });++ expectCallLlm(await agent.runner(createContext('init'), state));+ const fallbackInstruction = await agent.runner(+ createLlmResultContext(JSON.stringify({ route: 'anything' })),+ state,+ );++ expect(expectCallLlm(fallbackInstruction).stepLabel).toBe('fallback');+ expect(getLastPrompt(fallbackInstruction)).toContain(+ 'Default route after invalid condition.',+ );+ expect(getLastPrompt(fallbackInstruction)).not.toContain('Invalid condition route.');+ });++ it('should retry extraction when parsed JSON does not match the edge output schema', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: loadGoalLoopGraph(),+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal validate planned output schema', role: 'user' }],+ });++ await agent.runner(createContext('init'), state);++ const extractionInstruction = await agent.runner(+ createLlmResultContext(JSON.stringify({ goals: [{ name: 'missing-desc' }] })),+ state,+ );+ const prompt = getLastPrompt(extractionInstruction);++ expect(getGraphStore(state)?.plan).toBeUndefined();+ expect(expectCallLlm(extractionInstruction).stepLabel).toBe('plan:extract');+ expect(getGraphState(state)).toMatchObject({+ active: true,+ attempts: 1,+ currentNode: 'plan',+ phase: 'node_out',+ });+ expect(prompt).toContain('requires an output object that matches this schema');+ expect(prompt).toContain('goals');+ expect(prompt).toContain('desc');++ const goals = [{ desc: 'Recovered with a valid goal description.', name: 'valid-goal' }];+ const workInstruction = await agent.runner(+ createLlmResultContext(JSON.stringify({ goals })),+ state,+ );++ expect(getGraphStore(state)?.plan).toEqual({ goals });+ expect(expectCallLlm(workInstruction).stepLabel).toBe('work');+ expect(getLastPrompt(workInstruction)).toContain('Recovered with a valid goal description.');+ });++ it('should request fenced json extraction and commit recovered node output', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: loadGoalLoopGraph(),+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal add graph tests', role: 'user' }],+ });++ await agent.runner(createContext('init'), state);++ const extractionInstruction = await agent.runner(+ createLlmResultContext('I found two goals, but I am not returning JSON yet.'),+ state,+ );++ expect(getGraphState(state)).toMatchObject({+ active: true,+ attempts: 1,+ currentNode: 'plan',+ phase: 'node_out',+ });+ expect(expectCallLlm(extractionInstruction).stepLabel).toBe('plan:extract');+ expect(getLastPrompt(extractionInstruction)).toContain(+ 'markdown fenced code block tagged json',+ );+ expect(getLastPrompt(extractionInstruction)).toContain('output_schema');+ expect(getLastPrompt(extractionInstruction)).toContain('format_instruction');+ expect(getLastPrompt(extractionInstruction)).toContain('previous_error');++ const goals = [{ desc: 'Cover graph extraction retry.', name: 'test extraction' }];+ const workInstruction = await agent.runner(+ createLlmResultContext(`\`\`\`json\n${JSON.stringify({ goals })}\n\`\`\``),+ state,+ );++ 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.');+ });++ it('should stop the verify-to-work loop when maxTraversals is reached', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: loadGoalLoopGraph(),+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal keep iterating until verified', role: 'user' }],+ });++ await agent.runner(createContext('init'), state);++ const goals = [{ desc: 'Iterate until the verifier accepts the work.', name: 'iterate' }];+ await agent.runner(createLlmResultContext(JSON.stringify({ goals })), state);++ for (let index = 1; index <= 3; index++) {+ await agent.runner(+ createLlmResultContext(JSON.stringify({ summary: `work attempt ${index}` })),+ state,+ );+ const reworkInstruction = await agent.runner(+ createLlmResultContext(+ JSON.stringify({+ review: {+ fin: false,+ unfinish: [{ desc: `attempt ${index} is still incomplete`, name: 'iterate' }],+ },+ }),+ ),+ state,+ );++ expect(getGraphStore(state)?.verify).toEqual({+ review: {+ fin: false,+ unfinish: [{ desc: `attempt ${index} is still incomplete`, name: 'iterate' }],+ },+ });+ expect(getGraphState(state)).toMatchObject({ currentNode: 'work', phase: 'node_in' });+ expect(expectCallLlm(reworkInstruction).stepLabel).toBe('work');+ }++ await agent.runner(+ createLlmResultContext(JSON.stringify({ summary: 'work attempt 4' })),+ state,+ );+ const result = await agent.runner(+ createLlmResultContext(+ JSON.stringify({+ review: {+ fin: false,+ unfinish: [{ desc: 'attempt 4 is still incomplete', name: 'iterate' }],+ },+ }),+ ),+ state,+ );++ expect(getGraphState(state)).toMatchObject({+ phase: 'fin',+ reason: 'error_recovery',+ reasonDetail: expect.stringContaining('graph_edge_limit_reached'),+ });+ expect(result).toMatchObject({+ reason: 'error_recovery',+ reasonDetail: expect.stringContaining('graph_edge_limit_reached'),+ type: 'finish',+ });+ });++ it('should commit raw output after extraction attempts are exhausted', async () => {+ const agent = new GraphAgent({+ agentConfig: { maxSteps: 100 },+ graph: loadGoalLoopGraph(),+ operationId: 'test-operation',+ });+ const state = createMockState({+ messages: [{ content: '/goal recover from bad planning output', role: 'user' }],+ });++ await agent.runner(createContext('init'), state);++ for (const content of ['not json', 'still not json', 'nope', 'final raw planning output']) {+ await agent.runner(createLlmResultContext(content), state);+ }++ expect(getGraphStore(state)?.plan).toEqual({+ _extractionError: 'The node output is not valid JSON.',+ _raw: 'final raw planning output',+ });+ expect(getGraphState(state)).toMatchObject({ currentNode: 'work', phase: 'node_in' });+ });+ });+});diff --git a/packages/agent-runtime/src/agents/__tests__/fixtures/goal-loop.graph.json b/packages/agent-runtime/src/agents/__tests__/fixtures/goal-loop.graph.jsonnew file mode 100644index 00000000000..2796e9045b5--- /dev/null+++ b/packages/agent-runtime/src/agents/__tests__/fixtures/goal-loop.graph.json@@ -0,0 +1,154 @@+{+ "description": "Plan, execute, and verify a /goal request until the verifier marks it complete.",+ "edges": [+ {+ "from": "__root__",+ "to": "plan",+ "instruction": "Read and search only. Convert the user /goal request into concrete goals. Do not modify files.",+ "input": {+ "fields": [{ "from": "__root__", "field": "query" }]+ },+ "output": {+ "instruction": "Extract the planned goals.",+ "fields": [{ "field": "goals" }]+ }+ },+ {+ "from": "plan",+ "to": "work",+ "instruction": "Complete the planned goals. Work through the provided goals and summarize what changed.",+ "input": {+ "fields": [{ "from": "plan", "field": "goals" }]+ },+ "output": {+ "instruction": "Extract a concise work summary.",+ "fields": [{ "field": "summary" }]+ }+ },+ {+ "from": "work",+ "to": "verify",+ "instruction": "Verify whether the work satisfies the planned goals. Return fin=true only when all goals are complete.",+ "input": {+ "fields": [+ { "from": "plan", "field": "goals" },+ { "from": "work", "field": "summary" }+ ]+ },+ "output": {+ "instruction": "Extract the verification review.",+ "fields": [{ "field": "review" }]+ }+ },+ {+ "from": "verify",+ "to": "work",+ "condition": {+ "type": "object",+ "properties": {+ "review": {+ "type": "object",+ "properties": {+ "fin": {+ "const": false+ }+ },+ "required": ["fin"]+ }+ },+ "required": ["review"]+ },+ "instruction": "Continue working on the unfinished goals from the verifier review. Focus only on review.unfinish.",+ "input": {+ "fields": [+ { "from": "verify", "field": "review" },+ { "from": "work", "field": "summary" }+ ]+ },+ "output": {+ "instruction": "Extract the updated work summary.",+ "fields": [{ "field": "summary" }]+ },+ "maxTraversals": 3+ }+ ],+ "fields": {+ "query": {+ "desc": "Original user /goal request.",+ "schema": {+ "type": "string"+ }+ },+ "goals": {+ "desc": "Concrete goals planned from the user request.",+ "schema": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "name": {+ "type": "string"+ },+ "desc": {+ "type": "string"+ }+ },+ "required": ["name", "desc"]+ }+ }+ },+ "summary": {+ "desc": "Worker summary describing completed work and remaining risk.",+ "schema": {+ "type": "string"+ }+ },+ "review": {+ "desc": "Verifier decision and unfinished goals.",+ "schema": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "fin": {+ "type": "boolean"+ },+ "unfinish": {+ "type": "array",+ "items": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "name": {+ "type": "string"+ },+ "desc": {+ "type": "string"+ }+ },+ "required": ["name", "desc"]+ }+ }+ },+ "required": ["fin", "unfinish"]+ }+ }+ },+ "maxInstructionCount": 64,+ "name": "goal-loop",+ "nodes": {+ "plan": {+ "type": "agent",+ "allowedToolApiNames": ["read", "search"],+ "maxAgentSteps": 8+ },+ "work": {+ "type": "agent",+ "maxAgentSteps": 24+ },+ "verify": {+ "type": "llm"+ }+ },+ "terminal": "verify"+}diff --git a/packages/agent-runtime/src/types/generalAgent.ts b/packages/agent-runtime/src/types/generalAgent.tsindex c0a0747eb99..9384b89ce33 100644--- a/packages/agent-runtime/src/types/generalAgent.ts+++ b/packages/agent-runtime/src/types/generalAgent.ts@@ -6,6 +6,7 @@ import {} from '@lobechat/types';export interface GeneralAgentCallLLMInstructionPayload {+ allowedToolNames?: string[];/*** Reuse an existing assistant message instead of creating a new one. Set when* resuming from a tool-first step (e.g. tools activator) whose seeded@@ -78,6 +79,8 @@ export interface GeneralAgentConfig {[key: string]: any;maxSteps?: number;};+ /** Explicit tool-name allow-list for agents that intentionally restrict tools. */+ allowedToolNames?: string[];/*** Context compression configuration* When enabled and triggered, ALL messages are compressed into a single MessageGroup summary.@@ -114,6 +117,8 @@ export interface GeneralAgentConfig {provider: string;};operationId: string;+ /** Phase-level tools exposed to this agent run. Falls back to AgentState.tools. */+ tools?: any[];userId?: string;}diff --git a/packages/agent-runtime/src/types/graph.ts b/packages/agent-runtime/src/types/graph.tsdeleted file mode 100644index b6e998373b0..00000000000--- a/packages/agent-runtime/src/types/graph.ts+++ /dev/null@@ -1,85 +0,0 @@-// ── Reasoning Graph Definition (declarative JSON) ──--/**- * A single state node in the reasoning graph- */-export interface StateNode {- /**- * JSON Schema for structured output. Forces LLM to produce conforming JSON.- */- outputSchema: Record<string, any>;- /**- * Prompt template. Use {{stateId.field}} to reference output fields from previous nodes.- * Special variable: {{input.question}} references the original user input.- */- prompt: string;- /**- * Node type:- * - 'agent': Has tool capabilities, delegates to GeneralChatAgent for multi-turn tool loop- * - 'llm': Pure generation, single LLM call with structured output- */- type: 'agent' | 'llm';-}--/**- * A transition rule between states- */-export interface Transition {- /**- * JS expression evaluated programmatically (NOT by LLM).- * The `output` variable is injected with the current node's structured output.- * Example: 'output.confidence < 0.4 && output.falsified.length > 0'- */- condition: string;- from: string;- to: string;-}--/**- * Declarative reasoning graph definition.- * Drives multi-stage agent execution with programmatic flow control.- */-export interface ReasoningGraph {- description?: string;- /** Entry node ID */- entry: string;- /** Maximum backtrack count before forcing forward progress */- maxBacktracks: number;- name: string;- /** State node definitions */- states: Record<string, StateNode>;- /** Terminal node ID — when this node finishes, the entire graph is done */- terminal: string;- /** Transition rules, evaluated in order — first match wins */- transitions: Transition[];-}--// ── Graph Runtime Context ──--/**- * Runtime context maintained by GraphAgent across steps.- * Stored in AgentState.metadata to survive across runner() calls.- */-export interface GraphContext {- /** Total backtrack count across the graph execution */- backtrackCount: number;- /** Current node ID being executed */- currentNode: string;- /**- * Whether an agent node is in the extraction phase.- * After the agent loop finishes, an extra LLM call extracts structured output.- */- extracting?: boolean;- /** The original user input/question */- input: string;- /**- * Whether the current node's inner agent loop is active.- * When true, phases like llm_result/tool_result are delegated to GeneralChatAgent.- * When false, we're at a graph-level transition point.- */- nodeActive: boolean;- /** Accumulated structured outputs from completed nodes: stateId → output */- store: Record<string, Record<string, any>>;- /** Visit count per node (for detecting backtracks) */- visitCount: Record<string, number>;-}diff --git a/packages/agent-runtime/src/types/index.ts b/packages/agent-runtime/src/types/index.tsindex c7c5e55008c..5a9ae301f4e 100644--- a/packages/agent-runtime/src/types/index.ts+++ b/packages/agent-runtime/src/types/index.ts@@ -1,6 +1,5 @@export * from './event';export * from './generalAgent';-export * from './graph';export * from './hooks';export * from './instruction';export * from './runtime';diff --git a/packages/agent-runtime/src/types/instruction.ts b/packages/agent-runtime/src/types/instruction.tsindex 649f7d2e7ff..b2deb4f9948 100644--- a/packages/agent-runtime/src/types/instruction.ts+++ b/packages/agent-runtime/src/types/instruction.ts@@ -115,6 +115,7 @@ export interface Agent {// ── Payloads ──────────────────────────────────────────────export interface CallLLMPayload {+ allowedToolNames?: string[];isFirstMessage?: boolean;messages: any[];model: string;@@ -271,6 +272,10 @@ export interface AgentInstructionResolveAbortedTools extends AgentInstructionBasexport interface AgentInstructionResolveBlockedTools extends AgentInstructionBase {payload: {+ /** Optional message to write into blocked tool result content */+ blockedContent?: string;+ /** Optional machine-readable blocked reason */+ blockedReason?: string;/** Parent message ID (assistant message) */parentMessageId: string;/** Tool calls that were blocked and need tool results */diff --git a/packages/const/src/user.ts b/packages/const/src/user.tsindex f4f71a22d82..1db47e6a5c3 100644--- a/packages/const/src/user.ts+++ b/packages/const/src/user.ts@@ -14,6 +14,7 @@ export const DEFAULT_PREFERENCE: UserPreference = {},lab: {enableAgentDocumentFloatingChatPanel: false,+ enableAgentGraphConfig: false,enableAgentSelfIteration: false,enableFleet: false,enableInputMarkdown: true,diff --git a/packages/context-engine/src/engine/tools/ToolNameResolver.ts b/packages/context-engine/src/engine/tools/ToolNameResolver.tsindex 173c3c1e58c..c2ad93dbc1f 100644--- a/packages/context-engine/src/engine/tools/ToolNameResolver.ts+++ b/packages/context-engine/src/engine/tools/ToolNameResolver.ts@@ -129,6 +129,8 @@ export class ToolNameResolver {} else {return null;}+ } else if (offeredSet && !offeredSet.has(toolCall.function.name)) {+ return null;}// Step 1: Resolve hashed identifier if neededdiff --git a/packages/context-engine/src/engine/tools/ToolResolver.ts b/packages/context-engine/src/engine/tools/ToolResolver.tsindex 4b6f48c6d24..f48464ad6bc 100644--- a/packages/context-engine/src/engine/tools/ToolResolver.ts+++ b/packages/context-engine/src/engine/tools/ToolResolver.ts@@ -1,3 +1,4 @@+import { ToolNameResolver } from './ToolNameResolver';import type {ActivatedStepTool,LobeToolManifest,@@ -29,6 +30,7 @@ export class ToolResolver {operationToolSet: OperationToolSet,stepDelta: StepToolDelta,accumulatedActivations: ActivatedStepTool[] = [],+ allowedToolNames?: string[],): ResolvedToolSet {// Start from operation-level snapshot (shallow copies, with safe defaults)const tools: UniformTool[] = [...(operationToolSet.tools ?? [])];@@ -55,12 +57,36 @@ export class ToolResolver {this.applyActivation(activation, tools, manifestMap, sourceMap, enabledToolIds);}+ const shouldFilterByToolNames = allowedToolNames !== undefined;+ const allowedToolNameSet = new Set(allowedToolNames ?? []);+ const toolNameResolver = new ToolNameResolver();++ let promptManifestMap = manifestMap;+ if (shouldFilterByToolNames) {+ promptManifestMap = {};++ for (const [identifier, manifest] of Object.entries(manifestMap)) {+ const api = manifest.api.filter(({ name }) =>+ allowedToolNameSet.has(toolNameResolver.generate(identifier, name, manifest.type)),+ );++ if (api.length > 0) {+ promptManifestMap[identifier] = {+ ...manifest,+ api,+ ...(api.length < manifest.api.length && { systemRole: undefined }),+ };+ }+ }+ }+// Handle deactivation (e.g. forceFinish strips all tools)if (stepDelta.deactivatedToolIds?.includes('*')) {return {enabledToolIds: [],executorMap,manifestMap, // keep manifests for ToolNameResolver+ promptManifestMap: {},sourceMap,tools: [],};@@ -70,16 +96,24 @@ export class ToolResolver {const seen = new Set<string>();const dedupedTools: UniformTool[] = [];for (const tool of tools) {+ if (shouldFilterByToolNames && !allowedToolNameSet.has(tool.function.name)) {+ continue;+ }if (!seen.has(tool.function.name)) {seen.add(tool.function.name);dedupedTools.push(tool);}}+ const resolvedEnabledToolIds = shouldFilterByToolNames+ ? enabledToolIds.filter((id) => !!promptManifestMap[id])+ : enabledToolIds;+return {- enabledToolIds: [...new Set(enabledToolIds)],+ enabledToolIds: [...new Set(resolvedEnabledToolIds)],executorMap,manifestMap,+ promptManifestMap,sourceMap,tools: dedupedTools,};diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.tsindex 0f31e3439a9..4e372ff2833 100644--- a/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts+++ b/packages/context-engine/src/engine/tools/__tests__/ToolNameResolver.test.ts@@ -897,6 +897,32 @@ describe('ToolNameResolver', () => {expect(result).toEqual([]);});+ it('should drop fully-qualified tool names that were not offered this turn', () => {+ const toolCalls = [+ {+ function: { arguments: '{}', name: 'workspace____write' },+ id: 'call_1',+ type: 'function',+ },+ ];++ const manifests = {+ workspace: {+ api: [+ { description: '', name: 'read', parameters: {} },+ { description: '', name: 'write', parameters: {} },+ ],+ identifier: 'workspace',+ meta: {},+ type: 'builtin' as const,+ },+ };++ const result = resolver.resolve(toolCalls, manifests, ['workspace____read']);++ expect(result).toEqual([]);+ });+it('should treat an enabled call as unique when a disabled duplicate would have made it ambiguous', () => {const toolCalls = [{diff --git a/packages/context-engine/src/engine/tools/__tests__/ToolResolver.test.ts b/packages/context-engine/src/engine/tools/__tests__/ToolResolver.test.tsindex e6c1dac62bf..8816340f755 100644--- a/packages/context-engine/src/engine/tools/__tests__/ToolResolver.test.ts+++ b/packages/context-engine/src/engine/tools/__tests__/ToolResolver.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from 'vitest';+import { ToolNameResolver } from '../ToolNameResolver';import { ToolResolver } from '../ToolResolver';import type {ActivatedStepTool,@@ -85,6 +86,7 @@ const emptyDelta: StepToolDelta = { activatedTools: [] };describe('ToolResolver', () => {const resolver = new ToolResolver();+ const toolNameResolver = new ToolNameResolver();describe('resolve with operation-only tools', () => {it('should return operation tools when no step delta', () => {@@ -301,6 +303,64 @@ describe('ToolResolver', () => {});});+ describe('allowed tool names', () => {+ it('should filter tools, enabled ids, and prompt manifests by allowed tool names', () => {+ const opSet = makeOperationToolSet([mockSearchManifest, mockLocalSystemManifest]);+ const allowedToolName = toolNameResolver.generate(+ mockLocalSystemManifest.identifier,+ 'read_file',+ mockLocalSystemManifest.type,+ );++ const result = resolver.resolve(opSet, emptyDelta, [], [allowedToolName]);++ expect(result.tools.map((tool) => tool.function.name)).toEqual([allowedToolName]);+ expect(result.enabledToolIds).toEqual(['local-system']);+ expect(result.manifestMap['web-search']).toBeDefined();+ expect(result.manifestMap['local-system']).toBeDefined();+ expect(result.promptManifestMap).toEqual({+ 'local-system': expect.objectContaining({+ api: [expect.objectContaining({ name: 'read_file' })],+ identifier: 'local-system',+ }),+ });+ });++ it('should clear manifest systemRole when only part of the manifest is offered to the model', () => {+ const manifestWithSystemRole: LobeToolManifest = {+ ...mockLocalSystemManifest,+ systemRole: 'Use all local-system tools.',+ };+ const opSet = makeOperationToolSet([manifestWithSystemRole]);+ const allowedToolName = toolNameResolver.generate(+ manifestWithSystemRole.identifier,+ 'read_file',+ manifestWithSystemRole.type,+ );++ const result = resolver.resolve(opSet, emptyDelta, [], [allowedToolName]);++ expect(result.promptManifestMap['local-system']).toEqual(+ expect.objectContaining({+ api: [expect.objectContaining({ name: 'read_file' })],+ systemRole: undefined,+ }),+ );+ expect(result.manifestMap['local-system']?.systemRole).toBe('Use all local-system tools.');+ });++ it('should return empty prompt manifests when an explicit empty allowlist is provided', () => {+ const opSet = makeOperationToolSet([mockSearchManifest]);++ const result = resolver.resolve(opSet, emptyDelta, [], []);++ expect(result.tools).toEqual([]);+ expect(result.enabledToolIds).toEqual([]);+ expect(result.promptManifestMap).toEqual({});+ expect(result.manifestMap['web-search']).toBeDefined();+ });+ });+describe('defensive defaults for missing fields', () => {it('should handle undefined enabledToolIds gracefully', () => {// Simulate lambda path where enabledToolIds is not provided at runtimediff --git a/packages/context-engine/src/engine/tools/types.ts b/packages/context-engine/src/engine/tools/types.tsindex 5383a97e5b0..986e23215cb 100644--- a/packages/context-engine/src/engine/tools/types.ts+++ b/packages/context-engine/src/engine/tools/types.ts@@ -220,6 +220,7 @@ export interface ResolvedToolSet {enabledToolIds: string[];executorMap?: Record<string, ToolExecutor>;manifestMap: Record<string, LobeToolManifest>;+ promptManifestMap: Record<string, LobeToolManifest>;sourceMap: Record<string, ToolSource>;tools: UniformTool[];}diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.tsindex ec318d51f98..a6b294224c1 100644--- a/packages/locales/src/default/labs.ts+++ b/packages/locales/src/default/labs.ts@@ -2,6 +2,9 @@ export default {'features.agentDocumentFloatingChatPanel.desc':'Show the floating chat panel in agent document preview only when this lab feature is enabled.','features.agentDocumentFloatingChatPanel.title': 'Agent Document Floating Chat Panel',+ 'features.agentGraphConfig.desc':+ 'Show graph runtime configuration in an agent profile advanced settings.',+ 'features.agentGraphConfig.title': 'Agent Graph Runtime Configuration','features.agentSelfIteration.desc':'Allow the agent to reflect, build self-awareness, and continuously iterate through ongoing attempts and interactions.','features.agentSelfIteration.title': 'Agent Self-iteration',diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 1aeccbd19b1..4a365928f0a 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -189,6 +189,7 @@ export default {'agentSkillModal.url.title': 'Import from URL','agentSkillModal.url.urlPlaceholder': 'https://example.com/path/to/SKILL.md','agentSkillTag': 'Agent Skill',+ 'agentTab.graph': 'Graph Runtime','agentTab.opening': 'Opening Settings','agentTab.plugin': 'Skill Settings','agentTab.prompt': 'Agent Profile',@@ -847,6 +848,19 @@ export default {'settingOpening.openingQuestions.title': 'Opening Questions','settingOpening.title': 'Opening Settings','settingPlugin.title': 'Skill List',+ 'settingGraphRuntime.enabled.desc':+ '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.',+ 'settingGraphRuntime.snapshot.placeholder':+ 'Paste a ReasoningGraph 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.',+ 'settingGraphRuntime.validation.required':+ 'A graph snapshot is required before enabling graph runtime.',+ 'settingGraphRuntime.validation.unknown': 'Unknown graph validation error','settingSelfIteration.enabled.desc':'Allow this assistant to review recent signals and improve its own skills when the self-iteration workflow runs.','settingSelfIteration.enabled.managedDesc':diff --git a/packages/openapi/src/types/agent.type.ts b/packages/openapi/src/types/agent.type.tsindex e63dbcb4c31..f801e0dbb8b 100644--- a/packages/openapi/src/types/agent.type.ts+++ b/packages/openapi/src/types/agent.type.ts@@ -1,4 +1,5 @@import type { LobeAgentChatConfig } from '@lobechat/types';+import { ReasoningGraphSchema } from '@lobechat/types';import { z } from 'zod';import type { AgentItem } from '@/database/schemas';@@ -30,10 +31,12 @@ export const CreateAgentRequestSchema = 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/types/package.json b/packages/types/package.jsonindex ff4993714ee..dffd70f995f 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -12,6 +12,7 @@"dependencies": {"@lobehub/market-sdk": "0.39.2","@lobehub/market-types": "^1.17.1",+ "ajv": "^8.20.0","model-bank": "workspace:*","type-fest": "^4.41.0","zustand": "5.0.4"diff --git a/packages/types/src/agent/chatConfig.ts b/packages/types/src/agent/chatConfig.tsindex cdcb46a6f94..fb72fd3ad78 100644--- a/packages/types/src/agent/chatConfig.ts+++ b/packages/types/src/agent/chatConfig.ts@@ -4,6 +4,8 @@ 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;@@ -69,6 +71,11 @@ 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*/@@ -92,6 +99,11 @@ export interface LobeAgentChatConfig extends AgentMemoryChatConfig, AgentSelfItegpt5_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_20ReasoningEffort?: 'low' | 'medium' | 'high' | 'xhigh';@@ -235,7 +247,9 @@ export const AgentChatConfigSchema = zenableAutoScrollOnStreaming: 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.tsnew file mode 100644index 00000000000..532ac6fa1e3--- /dev/null+++ b/packages/types/src/agent/graph.ts@@ -0,0 +1,314 @@+import Ajv from 'ajv';+import { z } from 'zod';++export const AGENT_GRAPH_ROOT_NODE_ID = '__root__';++/**+ * Serializable reasoning graph snapshot stored on agent config.+ * Kept package-local so shared config types don't depend on runtime packages.+ */+export type AgentGraphNode =+ | {+ allowedToolApiNames?: string[];+ maxAgentSteps?: number;+ type: 'agent';+ }+ | {+ type: 'llm';+ };++export interface AgentGraphField {+ desc: string;+ schema: Record<string, any>;+}++export interface AgentGraphFieldRef {+ desc?: string;+ field: string;+ required?: boolean;+}++export interface AgentGraphInputField extends AgentGraphFieldRef {+ from: string;+}++export type AgentGraphOutputField = AgentGraphFieldRef;++export interface AgentGraphEdge {+ /**+ * JSON Schema evaluated against the current node output.+ * If omitted, the edge is treated as the default edge for its source node.+ */+ condition?: Record<string, unknown>;+ from: string;+ input?: {+ fields?: AgentGraphInputField[];+ };+ instruction: string;+ maxTraversals?: number;+ output?: {+ fields?: AgentGraphOutputField[];+ instruction?: string;+ };+ to: string;+}++export interface ReasoningGraph {+ description?: string;+ edges: AgentGraphEdge[];+ fields: Record<string, AgentGraphField>;+ maxInstructionCount?: number;+ name: string;+ nodes: Record<string, AgentGraphNode>;+ terminal: string;+}++const AgentGraphNodeSchema = z.discriminatedUnion('type', [+ z.object({+ allowedToolApiNames: z.array(z.string().min(1)).optional(),+ maxAgentSteps: z.number().int().positive().optional(),+ type: z.literal('agent'),+ }),+ z.object({+ type: z.literal('llm'),+ }),+]);++const AgentGraphFieldSchema = z.object({+ desc: z.string().min(1),+ schema: z.record(z.unknown()),+});++const AgentGraphFieldRefSchema = z.object({+ desc: z.string().min(1).optional(),+ field: z.string().min(1),+ required: z.boolean().optional(),+});++const AgentGraphInputFieldSchema = AgentGraphFieldRefSchema.extend({+ from: z.string().min(1),+});++const AgentGraphOutputFieldSchema = AgentGraphFieldRefSchema;++const AgentGraphEdgeSchema = z.object({+ condition: z.record(z.unknown()).optional(),+ from: z.string(),+ input: z+ .object({+ fields: z.array(AgentGraphInputFieldSchema).optional(),+ })+ .optional(),+ output: z+ .object({+ fields: z.array(AgentGraphOutputFieldSchema).optional(),+ instruction: z.string().min(1).optional(),+ })+ .optional(),+ instruction: z.string().min(1),+ maxTraversals: z.number().int().nonnegative().optional(),+ to: z.string(),+});++const findSchemaDescriptionPath = (+ value: unknown,+ path: (number | string)[],+): (number | string)[] | undefined => {+ if (!value || typeof value !== 'object') return;++ if (Array.isArray(value)) {+ for (const [index, item] of value.entries()) {+ const found = findSchemaDescriptionPath(item, [...path, index]);+ if (found) return found;+ }++ return;+ }++ const record = value as Record<string, unknown>;+ if (Object.hasOwn(record, 'description') && path.at(-1) !== 'properties') {+ return [...path, 'description'];+ }++ for (const [key, item] of Object.entries(record)) {+ const found = findSchemaDescriptionPath(item, [...path, key]);+ if (found) return found;+ }+};++export const ReasoningGraphSchema: z.ZodType<ReasoningGraph> = z+ .object({+ description: z.string().optional(),+ fields: z.record(AgentGraphFieldSchema),+ maxInstructionCount: z.number().int().positive().optional(),+ name: z.string().min(1),+ nodes: z.record(AgentGraphNodeSchema),+ terminal: z.string().min(1),+ edges: z.array(AgentGraphEdgeSchema),+ })+ .superRefine((graph, ctx) => {+ const outputSchemaAjv = new Ajv({ allErrors: false, strict: false });+ const conditionSchemaAjv = new Ajv({ allErrors: false, strict: true });+ const fieldIds = new Set(Object.keys(graph.fields));+ const nodeIds = new Set(Object.keys(graph.nodes));+ const sourceNodeIds = new Set([AGENT_GRAPH_ROOT_NODE_ID, ...nodeIds]);++ for (const [fieldId, field] of Object.entries(graph.fields)) {+ const descriptionPath = findSchemaDescriptionPath(field.schema, [+ 'fields',+ fieldId,+ 'schema',+ ]);+ if (descriptionPath) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ `Graph field "${fieldId}" schema must not contain "description"; ` ++ 'field schemas are only for validation. Use the graph field desc or edge field desc instead.',+ path: descriptionPath,+ });+ }++ try {+ outputSchemaAjv.compile(field.schema);+ } catch (error) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ `Graph field "${fieldId}" schema must be a valid JSON Schema: ` ++ (error instanceof Error ? error.message : String(error)),+ path: ['fields', fieldId, 'schema'],+ });+ }+ }++ if (nodeIds.size === 0) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Graph must define at least one node',+ path: ['nodes'],+ });+ return;+ }++ if (!nodeIds.has(graph.terminal)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Graph terminal must reference an existing node',+ path: ['terminal'],+ });+ }++ const rootEdges = graph.edges.filter((edge) => edge.from === AGENT_GRAPH_ROOT_NODE_ID);+ if (rootEdges.length !== 1) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Graph must define exactly one "${AGENT_GRAPH_ROOT_NODE_ID}" outgoing edge`,+ path: ['edges'],+ });+ }++ const defaultEdgeBySource = new Map<string, number>();+ graph.edges.forEach((edge, index) => {+ if (edge.condition) {+ try {+ conditionSchemaAjv.compile(edge.condition);+ } catch (error) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ `Edge condition must be a valid JSON Schema: ` ++ (error instanceof Error ? error.message : String(error)),+ path: ['edges', index, 'condition'],+ });+ }+ }++ if (!edge.condition) {+ const previousIndex = defaultEdgeBySource.get(edge.from);+ if (previousIndex !== undefined) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Only one default edge without condition is allowed from "${edge.from}"`,+ path: ['edges', index, 'condition'],+ });+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Only one default edge without condition is allowed from "${edge.from}"`,+ path: ['edges', previousIndex, 'condition'],+ });+ }+ defaultEdgeBySource.set(edge.from, index);+ }++ if (edge.from !== AGENT_GRAPH_ROOT_NODE_ID && !nodeIds.has(edge.from)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Edge from must reference an existing node or "${AGENT_GRAPH_ROOT_NODE_ID}"`,+ path: ['edges', index, 'from'],+ });+ }++ if (!nodeIds.has(edge.to)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Edge to must reference an existing node',+ path: ['edges', index, 'to'],+ });+ }++ const inputFields = edge.input?.fields;+ if (inputFields && inputFields.length > 0) {+ const names = new Set<string>();+ inputFields.forEach((field, fieldIndex) => {+ if (names.has(field.field)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Edge input field "${field.field}" is duplicated`,+ path: ['edges', index, 'input', 'fields', fieldIndex, 'field'],+ });+ }+ names.add(field.field);++ if (!fieldIds.has(field.field)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Edge input field "${field.field}" must reference a registered graph field`,+ path: ['edges', index, 'input', 'fields', fieldIndex, 'field'],+ });+ }++ if (!sourceNodeIds.has(field.from)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Edge input source node "${field.from}" must reference an existing node or "${AGENT_GRAPH_ROOT_NODE_ID}"`,+ path: ['edges', index, 'input', 'fields', fieldIndex, 'from'],+ });+ }+ });+ }++ const outputFields = edge.output?.fields;+ if (outputFields && outputFields.length > 0) {+ const names = new Set<string>();+ outputFields.forEach((field, fieldIndex) => {+ if (names.has(field.field)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Edge output field "${field.field}" is duplicated`,+ path: ['edges', index, 'output', 'fields', fieldIndex, 'field'],+ });+ }+ names.add(field.field);++ if (!fieldIds.has(field.field)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Edge output field "${field.field}" must reference a registered graph field`,+ path: ['edges', index, 'output', 'fields', fieldIndex, 'field'],+ });+ }+ });+ }+ });+ });diff --git a/packages/types/src/agent/index.ts b/packages/types/src/agent/index.tsindex 72b57eafa69..771874c483c 100644--- a/packages/types/src/agent/index.ts+++ b/packages/types/src/agent/index.ts@@ -2,6 +2,7 @@ export * from './agencyConfig';export * from './agentConfig';export * from './chatConfig';export * from './document';+export * from './graph';export * from './item';export * from './pluginConfig';export * from './tts';diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.tsindex 39fb63f45a9..e5d1d42c2c1 100644--- a/packages/types/src/user/preference.ts+++ b/packages/types/src/user/preference.ts@@ -38,6 +38,10 @@ export const UserGuideSchema = z.object({export type UserGuide = z.infer<typeof UserGuideSchema>;export const UserLabSchema = z.object({+ /**+ * enable graph runtime configuration for agents+ */+ enableAgentGraphConfig: z.boolean().optional(),/*** enable agent self-iteration feedback capture and policy execution*/diff --git a/src/features/AgentSetting/AgentGraphRuntime/index.tsx b/src/features/AgentSetting/AgentGraphRuntime/index.tsxnew file mode 100644index 00000000000..cbf99efaa4c--- /dev/null+++ b/src/features/AgentSetting/AgentGraphRuntime/index.tsx@@ -0,0 +1,167 @@+'use client';++import type { ReasoningGraph } from '@lobechat/types';+import { ReasoningGraphSchema } from '@lobechat/types';+import { Alert, Flexbox, TextArea } from '@lobehub/ui';+import { Button, Switch } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import isEqual from 'fast-deep-equal';+import { memo, useCallback, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useStore } from '../store';+import { selectors } from '../store/selectors';++const styles = createStaticStyles(({ css }) => ({+ actions: css`+ justify-content: flex-end;+ `,+ editor: css`+ font-family: ${cssVar.fontFamilyCode};+ `,+ item: css`+ padding: 16px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorBgContainer};+ `,+ itemDesc: css`+ margin: 0;+ font-size: 13px;+ line-height: 1.5;+ color: ${cssVar.colorTextSecondary};+ `,+ itemTitle: css`+ margin: 0;+ font-size: 14px;+ font-weight: 600;+ color: ${cssVar.colorText};+ `,+}));++const formatGraph = (graph?: ReasoningGraph | 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;+ const initialGraphText = useMemo(+ () => formatGraph(config.chatConfig?.graph),+ [config.chatConfig?.graph],+ );++ const [enabled, setEnabled] = useState(initialEnabled);+ const [graphText, setGraphText] = useState(initialGraphText);+ const [error, setError] = useState<string>();+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ setEnabled(initialEnabled);+ setGraphText(initialGraphText);+ setError(undefined);+ }, [initialEnabled, initialGraphText]);++ const isDirty = enabled !== initialEnabled || graphText !== initialGraphText;++ const handleSave = useCallback(async () => {+ if (disabled) return;++ const trimmedGraphText = graphText.trim();+ if (enabled && !trimmedGraphText) {+ setError(t('settingGraphRuntime.validation.required'));+ return;+ }++ let graph: ReasoningGraph | undefined;++ if (trimmedGraphText) {+ let parsedGraph: unknown;++ try {+ parsedGraph = JSON.parse(trimmedGraphText);+ } catch {+ setError(t('settingGraphRuntime.validation.invalidJson'));+ return;+ }++ const graphResult = ReasoningGraphSchema.safeParse(parsedGraph);++ if (!graphResult.success) {+ setError(+ t('settingGraphRuntime.validation.invalidGraph', {+ error:+ graphResult.error.issues[0]?.message || t('settingGraphRuntime.validation.unknown'),+ }),+ );+ return;+ }++ graph = graphResult.data;+ }++ setError(undefined);+ setSaving(true);++ try {+ await updateConfig({+ chatConfig: { enableGraphMode: enabled, graph: graph ?? null },+ });+ } finally {+ setSaving(false);+ }+ }, [disabled, enabled, graphText, t, updateConfig]);++ return (+ <Flexbox gap={16} width={'100%'}>+ <Flexbox horizontal align={'center'} className={styles.item} gap={16}>+ <Flexbox flex={1} gap={4}>+ <h3 className={styles.itemTitle}>{t('settingGraphRuntime.enabled.title')}</h3>+ <p className={styles.itemDesc}>{t('settingGraphRuntime.enabled.desc')}</p>+ </Flexbox>+ <Switch+ checked={enabled}+ disabled={disabled}+ onChange={(checked) => {+ setEnabled(checked);+ setError(undefined);+ }}+ />+ </Flexbox>++ <Flexbox className={styles.item} gap={12}>+ <Flexbox gap={4}>+ <h3 className={styles.itemTitle}>{t('settingGraphRuntime.snapshot.title')}</h3>+ <p className={styles.itemDesc}>{t('settingGraphRuntime.snapshot.desc')}</p>+ </Flexbox>+ <TextArea+ className={styles.editor}+ disabled={disabled}+ placeholder={t('settingGraphRuntime.snapshot.placeholder')}+ rows={16}+ value={graphText}+ onChange={(event) => {+ setGraphText(event.target.value);+ setError(undefined);+ }}+ />+ </Flexbox>++ {error && <Alert showIcon title={error} type="error" />}++ <Flexbox horizontal className={styles.actions}>+ <Button+ disabled={disabled || !isDirty}+ loading={saving}+ type={'primary'}+ onClick={handleSave}+ >+ {t('save', { ns: 'common' })}+ </Button>+ </Flexbox>+ </Flexbox>+ );+});++export default AgentGraphRuntime;diff --git a/src/features/AgentSetting/AgentSettingsContent.tsx b/src/features/AgentSetting/AgentSettingsContent.tsxindex 8c8bde640a8..53f59289a6e 100644--- a/src/features/AgentSetting/AgentSettingsContent.tsx+++ b/src/features/AgentSetting/AgentSettingsContent.tsx@@ -5,8 +5,11 @@ import { useAgentStore } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import { ChatSettingsTabs } from '@/store/global/initialState';import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';import AgentConnectors from './AgentConnectors';+import AgentGraphRuntime from './AgentGraphRuntime';import AgentOpening from './AgentOpening';import AgentSelfIteration from './AgentSelfIteration';@@ -18,6 +21,7 @@ export interface AgentSettingsContentProps {const AgentSettingsContent = memo<AgentSettingsContentProps>(({ tab, loadingSkeleton }) => {const loading = useAgentStore(agentSelectors.isAgentConfigLoading);const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);+ const enableAgentGraphConfigLab = useUserStore(labPreferSelectors.enableAgentGraphConfig);if (loading) return loadingSkeleton;@@ -25,6 +29,7 @@ const AgentSettingsContent = memo<AgentSettingsContentProps>(({ tab, loadingSkel<>{tab === ChatSettingsTabs.Opening && <AgentOpening />}{enableAgentSelfIteration && tab === ChatSettingsTabs.SelfIteration && <AgentSelfIteration />}+ {enableAgentGraphConfigLab && tab === ChatSettingsTabs.Graph && <AgentGraphRuntime />}{tab === ChatSettingsTabs.Connector && <AgentConnectors />}</>);diff --git a/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx b/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsxindex 33a955af28d..c1b1231c4a6 100644--- a/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx+++ b/src/routes/(main)/agent/profile/features/AgentSettings/Content.test.tsx@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({agentState: {activeAgentId: 'inbox-agent',config: {},+ isCurrentAgentHeterogeneous: false,isInbox: true,meta: {},optimisticUpdateAgentConfig: vi.fn(),@@ -61,6 +62,8 @@ vi.mock('@/store/agent/selectors', () => ({agentSelectors: {currentAgentConfig: (state: typeof mocks.agentState) => state.config,currentAgentMeta: (state: typeof mocks.agentState) => state.meta,+ isCurrentAgentHeterogeneous: (state: typeof mocks.agentState) =>+ state.isCurrentAgentHeterogeneous,},builtinAgentSelectors: {isInboxAgent: (state: typeof mocks.agentState) => state.isInbox,diff --git a/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx b/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsxindex ac6d9830873..d4bf69c99f3 100644--- a/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx+++ b/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx@@ -1,7 +1,7 @@'use client';import isEqual from 'fast-deep-equal';-import { ActivityIcon, MessageSquareHeartIcon } from 'lucide-react';+import { ActivityIcon, GitBranchIcon, MessageSquareHeartIcon } from 'lucide-react';import { memo, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { shallow } from 'zustand/shallow';@@ -17,8 +17,11 @@ import { useAgentStore } from '@/store/agent';import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';import { ChatSettingsTabs } from '@/store/global/initialState';import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';const TAB_META = {+ [ChatSettingsTabs.Graph]: { icon: GitBranchIcon, labelKey: 'agentTab.graph' },[ChatSettingsTabs.Opening]: { icon: MessageSquareHeartIcon, labelKey: 'agentTab.opening' },[ChatSettingsTabs.SelfIteration]: {icon: ActivityIcon,@@ -35,16 +38,20 @@ const Content = memo(() => {);const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);+ const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);+ const enableAgentGraphConfigLab = useUserStore(labPreferSelectors.enableAgentGraphConfig);const [tab, setTab] = useState(ChatSettingsTabs.Opening);+ const showGraphTab = enableAgentGraphConfigLab && !isInbox && !isHeterogeneous;const availableTabs = useMemo(() =>[ChatSettingsTabs.Opening,enableAgentSelfIteration ? ChatSettingsTabs.SelfIteration : null,+ showGraphTab ? ChatSettingsTabs.Graph : null,].filter(Boolean) as ChatSettingsTabs[],- [enableAgentSelfIteration],+ [enableAgentSelfIteration, showGraphTab],);const activeTab = availableTabs.includes(tab) ? tab : availableTabs[0];diff --git a/src/routes/(main)/settings/advanced/index.tsx b/src/routes/(main)/settings/advanced/index.tsxindex 733570a9c1a..07c8e94a261 100644--- a/src/routes/(main)/settings/advanced/index.tsx+++ b/src/routes/(main)/settings/advanced/index.tsx@@ -49,6 +49,7 @@ const Page = memo(() => {const [isPreferenceInit,enableAgentDocumentFloatingChatPanel,+ enableAgentGraphConfig,enableInputMarkdown,enablePlatformAgent,enableImessage,@@ -59,6 +60,7 @@ const Page = memo(() => {] = useUserStore((s) => [preferenceSelectors.isPreferenceInit(s),labPreferSelectors.enableAgentDocumentFloatingChatPanel(s),+ labPreferSelectors.enableAgentGraphConfig(s),labPreferSelectors.enableInputMarkdown(s),labPreferSelectors.enablePlatformAgent(s),labPreferSelectors.enableImessage(s),@@ -172,6 +174,19 @@ const Page = memo(() => {label: tLabs('features.agentDocumentFloatingChatPanel.title'),minWidth: undefined,},+ {+ children: (+ <Switch+ checked={enableAgentGraphConfig}+ loading={!isPreferenceInit}+ onChange={(checked: boolean) => updateLab({ enableAgentGraphConfig: checked })}+ />+ ),+ className: styles.labItem,+ desc: tLabs('features.agentGraphConfig.desc'),+ label: tLabs('features.agentGraphConfig.title'),+ minWidth: undefined,+ } satisfies FormItemProps,{children: (<Switchdiff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex 3ff87824810..17b4062810a 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -23,6 +23,7 @@ export enum SidebarTabKey {export enum ChatSettingsTabs {Connector = 'connector',+ Graph = 'graph',Opening = 'opening',Plugin = 'plugin',Prompt = 'prompt',diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.tsindex 072c41b58cc..6ee0be165d7 100644--- a/src/store/user/slices/preference/selectors/labPrefer.ts+++ b/src/store/user/slices/preference/selectors/labPrefer.ts@@ -7,6 +7,10 @@ export const labPreferSelectors = {s.preference.lab?.enableAgentDocumentFloatingChatPanel ??DEFAULT_PREFERENCE.lab?.enableAgentDocumentFloatingChatPanel ??false,+ enableAgentGraphConfig: (s: UserState): boolean =>+ s.preference.lab?.enableAgentGraphConfig ??+ DEFAULT_PREFERENCE.lab?.enableAgentGraphConfig ??+ false,enableAgentSelfIteration: (s: UserState): boolean =>s.preference.lab?.enableAgentSelfIteration ?? false,enableFleet: (s: UserState): boolean => s.preference.lab?.enableFleet ?? false,