Skip to content

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

🐛 fix: enforce strict tool resume and exclusive discovery (#21212)

AmAzing-d14761f27e88
diff --git a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts
index a3bf95277cd..ebb41787890 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/__tests__/serverCallLlmTooling.test.ts
@@ -1,4 +1,5 @@
import { type AgentState, normalizeAgentState } from '@lobechat/agent-runtime';
+import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import { describe, expect, it } from 'vitest';
import { resolveServerCallLlmTooling } from '../serverCallLlmTooling';
@@ -29,6 +30,34 @@ const searchTool = {
} as unknown as NonNullable<AgentState['tools']>[number];
describe('resolveServerCallLlmTooling', () => {
+ it.each([false, true])(
+ 'limits active-device tools to the operation pool (allowed=%s)',
+ (allowed) => {
+ const callerTool = {
+ type: 'function' as const,
+ function: { name: 'lobe-client-fn____inspect' },
+ };
+ const result = resolveServerCallLlmTooling(
+ { operationId: 'op-1', stepIndex: 0 },
+ buildState({
+ binding: { device: { id: 'device-1' } },
+ plan: { execution: { deviceId: 'device-1', kind: 'device', target: 'device' } },
+ operationToolSet: {
+ enabledToolIds: ['lobe-client-fn'],
+ executorMap: {},
+ manifestMap: allowed ? { 'lobe-local-system': LocalSystemManifest } : {},
+ sourceMap: { 'lobe-client-fn': 'client' },
+ tools: [callerTool],
+ },
+ }),
+ );
+ expect(result.tools).toContainEqual(callerTool);
+ expect(result.resolved.enabledToolIds.includes('lobe-local-system')).toBe(allowed);
+ if (!allowed) expect(result.tools).toEqual([callerTool]);
+ else expect(result.tools!.length).toBeGreaterThan(1);
+ },
+ );
+
// Regression: `serverCallLlmContextBuilder` needs this to compute
// `creds_sandbox_reachable` — `sandbox_enabled` alone (whether the
// dedicated Cloud Sandbox tool is offered) doesn't tell it whether
diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts
index ebaa931fdd0..98134e51dcf 100644
--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts
+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmTooling.ts
@@ -1,9 +1,7 @@
import { type AgentState, selectOperationToolSet } from '@lobechat/agent-runtime';
-import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
import {
buildStepSkillDelta,
buildStepToolDelta,
- type LobeToolManifest,
type OperationToolSet,
type ResolvedSkillSet,
type ResolvedToolSet,
@@ -52,11 +50,8 @@ export const resolveServerCallLlmTooling = (
): ServerCallLlmTooling => {
// Resolve tools via ToolResolver (unified tool injection).
//
- // Single-track device gate: `buildStepToolDelta` treats activeDeviceId as
- // an independent activation signal (it only dedupes against already-
- // enabled tools), so any id that reaches it WILL inject local-system.
- // `resolveRunActiveDeviceId` swallows the id whenever the plan/policy
- // forbids devices — the same filter the tool executors apply.
+ // Resolve device policy first, then activate only tools already allowed by
+ // the operation snapshot. Routing a device must not widen that tool pool.
const activeDeviceId = resolveRunActiveDeviceId(state);
const executionTarget = (state.plan?.execution as ExecutionPlan | undefined)?.target;
const operationToolSet: OperationToolSet = selectOperationToolSet(state);
@@ -65,7 +60,8 @@ export const resolveServerCallLlmTooling = (
activeDeviceId,
enabledToolIds: operationToolSet.enabledToolIds,
forceFinish: state.forceFinish,
- localSystemManifest: LocalSystemManifest as unknown as LobeToolManifest,
+ // Device activation cannot widen the operation's allowed tool pool.
+ localSystemManifest: operationToolSet.manifestMap['lobe-local-system'],
operationManifestMap: operationToolSet.manifestMap,
});
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
index 7fd88b52d15..29587c3b050 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.branches.test.ts
@@ -25,6 +25,9 @@ import { discoverTools } from '.';
vi.mock('@/business/client/model-bank/loadModels', () => ({
loadModels: vi.fn().mockResolvedValue([]),
}));
+vi.mock('@/server/services/agentSignal/featureGate', () => ({
+ isAgentSignalEnabledForUser: vi.fn().mockResolvedValue(true),
+}));
vi.mock('@/database/models/aiModel', () => ({
AiModelModel: class {
findByIdAndProvider = vi.fn().mockResolvedValue(undefined);
@@ -194,7 +197,8 @@ describe('discoverTools — disabled tools and client function tools', () => {
const result = await run({ input: { disableTools: true, functionTools } }).promise;
expect(result.toolsEngine).toBeUndefined();
- expect(result.tools).toBeUndefined();
+ expect(result.tools).toHaveLength(1);
+ expect(result.tools?.[0].function.name).toBe('lobe-client-fn____getWeather');
expect(createServerAgentToolsEngine).not.toHaveBeenCalled();
expect(result.toolsResult.enabledToolIds).toEqual(['lobe-client-fn']);
expect(result.toolSourceMap['lobe-client-fn']).toBe('client');
@@ -222,6 +226,20 @@ describe('discoverTools — disabled tools and client function tools', () => {
});
expect(result.toolsResult.enabledToolIds.at(-1)).toBe('lobe-client-fn');
});
+
+ it('keeps an exclusive function-only surface despite media and self-feedback injection', async () => {
+ const result = await run({
+ agentConfig: { plugins: ['lobe-agent'] },
+ input: { exclusivePluginIds: [], externalFileTypes: ['image/png'], functionTools },
+ }).promise;
+
+ expect(result.agentPlugins).toEqual([]);
+ expect(result.toolsResult.enabledToolIds).toEqual(['lobe-client-fn']);
+ expect(Object.keys(result.toolManifestMap)).toEqual(['lobe-client-fn']);
+ expect(result.tools?.map((tool) => tool.function.name)).toEqual([
+ 'lobe-client-fn____getWeather',
+ ]);
+ });
});
describe('discoverTools — connector permissions and ownership', () => {
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
index 650112905e7..f4c03597b9a 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts
@@ -4,6 +4,7 @@ import type { DeviceAttachment } from '@lobechat/builtin-tool-remote-device';
import { generateSystemPrompt, RemoteDeviceManifest } from '@lobechat/builtin-tool-remote-device';
import {
injectSelfFeedbackIntentTool,
+ SELF_FEEDBACK_INTENT_IDENTIFIER,
shouldExposeSelfFeedbackIntentTool,
} from '@lobechat/builtin-tool-self-iteration';
import { manualModeExcludeToolIds } from '@lobechat/builtin-tools';
@@ -334,6 +335,9 @@ export const discoverTools = async (
modelMediaCapabilities,
})),
];
+ if (exclusivePluginIds) {
+ agentPlugins = agentPlugins.filter((id) => exclusivePluginIds.includes(id));
+ }
// Share allowlist filters the full candidate set (pinned + mentioned +
// internal additions) before manifest discovery. This only trims which
@@ -571,7 +575,11 @@ export const discoverTools = async (
// not be conditional on it either.
//
// There is no per-agent switch: Labs → Self-evolving covers every agent.
- if (!shareGate && !disableSelfFeedbackIntentTool) {
+ if (
+ !shareGate &&
+ !disableSelfFeedbackIntentTool &&
+ (!exclusivePluginIds || exclusivePluginIds.includes(SELF_FEEDBACK_INTENT_IDENTIFIER))
+ ) {
// The run already reads `users.preference` for expertise injection; reuse that row.
// A failed read leaves the tool off (fail closed).
const featureUserEnabled = await isAgentSignalEnabledForUser(deps.db, deps.userId, {
@@ -600,8 +608,9 @@ export const discoverTools = async (
// Inject client function tools from Response API
const CLIENT_FN_IDENTIFIER = 'lobe-client-fn';
if (functionTools?.length) {
+ tools ??= [];
for (const ft of functionTools) {
- tools?.push({
+ tools.push({
function: {
description: ft.description,
name: `${CLIENT_FN_IDENTIFIER}____${ft.name}`,
diff --git a/locales/en-US/common.json b/locales/en-US/common.json
index 03dd52b7dcd..49c4a4a6c66 100644
--- a/locales/en-US/common.json
+++ b/locales/en-US/common.json
@@ -409,12 +409,16 @@
"supportAgent.context.attached": "Diagnostic info attached",
"supportAgent.context.remove": "Remove",
"supportAgent.error.failed": "Something went wrong while answering. Try again.",
+ "supportAgent.error.inspection_expired": "This permission request expired. Start a new conversation to continue.",
+ "supportAgent.error.inspection_submitted": "A permission response may already have been submitted. Its outcome is unknown. Start a new conversation to continue.",
"supportAgent.error.invalid_conversation": "This conversation can no longer be continued. Send again to start a new one.",
"supportAgent.error.rate_limited": "You've reached the hourly question limit. Try again later.",
+ "supportAgent.error.resume_failed": "Unable to confirm that this conversation resumed. Start a new conversation to continue.",
"supportAgent.error.unavailable": "The support assistant is unavailable right now. Try again later.",
"supportAgent.feedback": "Community & feedback",
"supportAgent.inspect.accessHint": "For the next 10 minutes it can act as you in your account to investigate. It has been told to only read, and to change nothing unless you ask.",
"supportAgent.inspect.allow": "Allow",
+ "supportAgent.inspect.approvedDecision": "You approved access to {{target}}.",
"supportAgent.inspect.declined": "You declined the request",
"supportAgent.inspect.deny": "Decline",
"supportAgent.inspect.granted": "Granted {{target}}",
@@ -429,6 +433,7 @@
"supportAgent.inspect.target.accountWithWorkspace": "your plan, credit balance and budget usage, including the workspace \"{{title}}\"",
"supportAgent.inspect.target.agent": "the configuration of the agent \"{{title}}\"",
"supportAgent.inspect.target.conversation": "the full conversation \"{{title}}\" ({{total}} messages)",
+ "supportAgent.inspect.target.unavailable": "an unavailable page",
"supportAgent.inspect.untitled": "Untitled",
"supportAgent.newConversation": "New conversation",
"supportAgent.placeholder": "Describe your question…",
diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.json
index 8f71bfe53ba..66b916073c8 100644
--- a/locales/zh-CN/common.json
+++ b/locales/zh-CN/common.json
@@ -409,12 +409,16 @@
"supportAgent.context.attached": "已附带诊断信息",
"supportAgent.context.remove": "移除",
"supportAgent.error.failed": "回答时出了点问题,请重试。",
+ "supportAgent.error.inspection_expired": "授权请求已过期,请新建对话继续。",
+ "supportAgent.error.inspection_submitted": "授权答复可能已提交,但目前无法确认结果。请新建对话继续。",
"supportAgent.error.invalid_conversation": "这个对话已无法继续,重新发送即可开始新对话。",
"supportAgent.error.rate_limited": "提问次数已达到每小时上限,请稍后再试。",
+ "supportAgent.error.resume_failed": "无法确认对话是否已恢复,请新建对话继续。",
"supportAgent.error.unavailable": "答疑助手暂时不可用,请稍后再试。",
"supportAgent.feedback": "社群与反馈",
"supportAgent.inspect.accessHint": "接下来 10 分钟内,它可以以你的身份访问你的账号来排查问题。它被要求只查看,除非你明确要求,否则不做任何修改。",
"supportAgent.inspect.allow": "允许",
+ "supportAgent.inspect.approvedDecision": "你已同意授权:{{target}}。",
"supportAgent.inspect.declined": "你拒绝了查看请求",
"supportAgent.inspect.deny": "拒绝",
"supportAgent.inspect.granted": "已授予{{target}}",
@@ -429,6 +433,7 @@
"supportAgent.inspect.target.accountWithWorkspace": "你的套餐、积分余额和预算使用情况(含工作区「{{title}}」)",
"supportAgent.inspect.target.agent": "助理「{{title}}」的配置",
"supportAgent.inspect.target.conversation": "对话「{{title}}」的完整内容({{total}} 条消息)",
+ "supportAgent.inspect.target.unavailable": "无法访问的页面",
"supportAgent.inspect.untitled": "未命名",
"supportAgent.newConversation": "新对话",
"supportAgent.placeholder": "描述你遇到的问题…",
diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.ts
index 112c0d7b74d..fd551fee92e 100644
--- a/packages/locales/src/default/common.ts
+++ b/packages/locales/src/default/common.ts
@@ -502,6 +502,12 @@ export default {
'supportAgent.context.attached': 'Diagnostic info attached',
'supportAgent.context.remove': 'Remove',
'supportAgent.error.failed': 'Something went wrong while answering. Try again.',
+ 'supportAgent.error.inspection_expired':
+ 'This permission request expired. Start a new conversation to continue.',
+ 'supportAgent.error.inspection_submitted':
+ 'A permission response may already have been submitted. Its outcome is unknown. Start a new conversation to continue.',
+ 'supportAgent.error.resume_failed':
+ 'Unable to confirm that this conversation resumed. Start a new conversation to continue.',
'supportAgent.error.invalid_conversation':
'This conversation can no longer be continued. Send again to start a new one.',
'supportAgent.error.rate_limited': "You've reached the hourly question limit. Try again later.",
@@ -511,6 +517,7 @@ export default {
'supportAgent.inspect.accessHint':
'For the next 10 minutes it can act as you in your account to investigate. It has been told to only read, and to change nothing unless you ask.',
'supportAgent.inspect.allow': 'Allow',
+ 'supportAgent.inspect.approvedDecision': 'You approved access to {{target}}.',
'supportAgent.inspect.declined': 'You declined the request',
'supportAgent.inspect.deny': 'Decline',
'supportAgent.inspect.granted': 'Granted {{target}}',
@@ -529,6 +536,7 @@ export default {
'supportAgent.inspect.target.agent': 'the configuration of the agent "{{title}}"',
'supportAgent.inspect.target.conversation':
'the full conversation "{{title}}" ({{total}} messages)',
+ 'supportAgent.inspect.target.unavailable': 'an unavailable page',
'supportAgent.inspect.untitled': 'Untitled',
'supportAgent.newConversation': 'New conversation',
'supportAgent.placeholder': 'Describe your question…',
diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.yml
index 5d2d05aba6e..ea538a3f86f 100644
--- a/packages/openapi/openapi.yml
+++ b/packages/openapi/openapi.yml
@@ -19137,6 +19137,8 @@ paths:
type:
- boolean
- "null"
+ strict_tool_resume:
+ type: boolean
temperature:
anyOf:
- type: number
@@ -19195,6 +19197,11 @@ paths:
required:
- type
- type: "null"
+ tools_mode:
+ type: string
+ enum:
+ - additional
+ - exclusive
top_p:
anyOf:
- type: number
diff --git a/packages/openapi/src/services/__tests__/responses.streaming.test.ts b/packages/openapi/src/services/__tests__/responses.streaming.test.ts
index de119299d06..cf36a4148ce 100644
--- a/packages/openapi/src/services/__tests__/responses.streaming.test.ts
+++ b/packages/openapi/src/services/__tests__/responses.streaming.test.ts
@@ -231,4 +231,61 @@ describe('ResponsesService function call outputs', () => {
}),
);
});
+
+ it.each([false, true])(
+ 'rejects a stale strict resume without starting a run (stream=%s)',
+ async (stream) => {
+ resumeParkedClientToolsMock.mockResolvedValue(undefined);
+ const params = { ...toolOutputRequest, strict_tool_resume: true };
+ const service = buildService();
+ let response;
+ if (stream) {
+ const events = [];
+ for await (const event of service.createStreamingResponse(params)) events.push(event);
+ expect(events.at(-1)?.type).toBe('response.failed');
+ response = events.at(-1)?.response;
+ } else {
+ response = await service.createResponse(params);
+ }
+ expect(response).toMatchObject({
+ status: 'failed',
+ error: { code: 'invalid_request_error' },
+ });
+ expect(execAgentMock).not.toHaveBeenCalled();
+ expect(executeResponseRunMock).not.toHaveBeenCalled();
+ },
+ );
+
+ it('requires both a previous response and tool outputs for strict resume', async () => {
+ for (const params of [
+ { input: 'hello', model: 'agt_1', previous_response_id: 'tpc_1' },
+ { input: toolOutputRequest.input, model: 'agt_1' },
+ ]) {
+ const response = await buildService().createResponse({ ...params, strict_tool_resume: true });
+ expect(response).toMatchObject({
+ status: 'failed',
+ error: { code: 'invalid_request_error' },
+ });
+ }
+ expect(execAgentMock).not.toHaveBeenCalled();
+ });
+
+ it('limits hosted discovery to the explicitly declared tools in exclusive mode', async () => {
+ const response = await buildService().createResponse({
+ input: 'Read the document',
+ model: 'agt_1',
+ tools: [
+ { type: 'lobe-agent-documents' },
+ { type: 'function', name: 'read_page', parameters: { type: 'object' } },
+ ],
+ tools_mode: 'exclusive',
+ });
+ expect(response.status).toBe('completed');
+ expect(execAgentMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ exclusivePluginIds: ['lobe-agent-documents'],
+ functionTools: [{ name: 'read_page', parameters: { type: 'object' } }],
+ }),
+ );
+ });
});
diff --git a/packages/openapi/src/services/responses.service.ts b/packages/openapi/src/services/responses.service.ts
index 19a7c46f992..4cca63ed3f9 100644
--- a/packages/openapi/src/services/responses.service.ts
+++ b/packages/openapi/src/services/responses.service.ts
@@ -15,12 +15,14 @@ import type {
FunctionCallOutputItem,
InputItem,
OutputItem,
+ ResponseError,
ResponseObject,
ResponseStreamEvent,
ResponseUsage,
Tool,
} from '../types/responses.type';
import {
+ ClientToolResumeError,
executeResponseRun,
parkedOnToolsReason,
pendingFunctionCallItems,
@@ -278,6 +280,12 @@ export class ResponsesService extends BaseService {
const functionCallOutputs = this.extractFunctionCallOutputs(params.input);
const isResumeFlow = functionCallOutputs.length > 0 && !!previousTopicId;
+ if (params.strict_tool_resume && !isResumeFlow) {
+ throw new ClientToolResumeError(
+ 'Strict tool resume requires previous_response_id and function_call_output items.',
+ );
+ }
+
if (isResumeFlow) {
const resumed = await resumeParkedClientTools({
agentRuntimeService: options.agentRuntimeService,
@@ -288,6 +296,11 @@ export class ResponsesService extends BaseService {
workspaceId: this.workspaceId,
});
if (resumed) return { ...resumed, resumed: true, topicId: previousTopicId };
+ if (params.strict_tool_resume) {
+ throw new ClientToolResumeError(
+ 'The response is no longer waiting for these tool outputs.',
+ );
+ }
}
const instructions = this.buildInstructions(params);
@@ -314,6 +327,7 @@ export class ResponsesService extends BaseService {
agentId: params.model,
appContext: previousTopicId ? { topicId: previousTopicId } : undefined,
autoStart: false,
+ exclusivePluginIds: params.tools_mode === 'exclusive' ? additionalPluginIds : undefined,
functionTools: functionTools.length > 0 ? functionTools : undefined,
instructions,
prompt,
@@ -379,7 +393,7 @@ export class ResponsesService extends BaseService {
return this.buildResponseObject({
createdAt,
error: {
- code: 'server_error',
+ code: error instanceof ClientToolResumeError ? 'invalid_request_error' : 'server_error',
message: error instanceof Error ? error.message : 'Unknown error',
},
id: errorResponseId,
@@ -839,7 +853,7 @@ export class ResponsesService extends BaseService {
const errorResponse = this.buildResponseObject({
createdAt,
error: {
- code: 'server_error',
+ code: error instanceof ClientToolResumeError ? 'invalid_request_error' : 'server_error',
message: error instanceof Error ? error.message : 'Unknown error',
},
id: errorResponseId,
@@ -889,7 +903,7 @@ export class ResponsesService extends BaseService {
private buildResponseObject(opts: {
completedAt?: number | null;
createdAt: number;
- error?: { code: 'server_error'; message: string };
+ error?: ResponseError;
id: string;
incompleteDetails?: { reason: string };
output: OutputItem[];
diff --git a/packages/openapi/src/types/responses.type.ts b/packages/openapi/src/types/responses.type.ts
index 06f754c6f8b..349d03e76f9 100644
--- a/packages/openapi/src/types/responses.type.ts
+++ b/packages/openapi/src/types/responses.type.ts
@@ -177,6 +177,8 @@ export const CreateResponseRequestSchema = z
previous_response_id: z.string().nullish(),
reasoning: ReasoningConfigSchema.nullish(),
stream: z.boolean().nullish(),
+ // Reject stale tool results instead of interpreting them as a new user turn.
+ strict_tool_resume: z.boolean().optional(),
temperature: z.number().min(0).max(2).nullish(),
tool_choice: z
.union([
@@ -185,6 +187,8 @@ export const CreateResponseRequestSchema = z
])
.nullish(),
tools: z.array(ToolSchema).nullish(),
+ // Exclusive mode also restricts tools discoverable later in the operation.
+ tools_mode: z.enum(['additional', 'exclusive']).optional(),
top_p: z.number().min(0).max(1).nullish(),
truncation: TruncationSchema.nullish(),
user: z.string().nullish(),