🤯 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
🐛 fix(agent-runtime): tell the model why the device picker is missing on a locked run (#20111)
Arvin Xu3ff12a78a68c
diff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.tsindex 15bf4930593..a76fd7b5dfe 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerToolTransport.ts@@ -242,6 +242,7 @@ export class ServerToolTransport implements ToolTransport {editingAgentId: context.state.origin?.editingAgentId,editingGroupId: context.state.origin?.editingGroupId,execSubAgent: this.ctx.execSubAgent,+ executionPlan: context.state.plan?.execution,executionTimeoutMs: timeoutMs,groupId: context.state.origin?.groupId,isSubAgent: context.state.origin?.lineage?.isSubAgent === true,diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.tsindex 6a42a6fc7f9..c8d2cfab2b5 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts@@ -113,4 +113,49 @@ describe('activatorRuntime', () => {expect(result.success).toBe(true);});});+ describe('activateTools — device picker on a locked run', () => {+ it.each([+ {+ expected: 'locked to device "device-a"',+ plan: { deviceId: 'device-a', kind: 'device', target: 'local' },+ },+ {+ expected: 'bound device, which is offline',+ plan: { kind: 'device-unrouted', reason: 'bound-device-offline', target: 'local' },+ },+ ] as const)(+ 'says why the picker is missing instead of a bare "Not found" ($plan.kind)',+ async ({ expected, plan }) => {+ const { activatorRuntime } = await import('../activator');+ const runtime = await activatorRuntime.factory({+ executionPlan: plan,+ serverDB: {} as never,+ toolManifestMap: {},+ userId: 'user-1',+ });++ const result = await runtime.activateTools({ identifiers: ['lobe-remote-device'] });++ expect(result.content).toContain('Not available: lobe-remote-device.');+ expect(result.content).toContain(expected);+ expect(result.content).toContain('device selector');+ expect(result.content).not.toContain('Not found');+ },+ 20_000,+ );++ it('keeps "Not found" when the picker was withheld for another reason', async () => {+ const { activatorRuntime } = await import('../activator');+ const runtime = await activatorRuntime.factory({+ executionPlan: { kind: 'sandbox', target: 'sandbox' },+ serverDB: {} as never,+ toolManifestMap: {},+ userId: 'user-1',+ });++ const result = await runtime.activateTools({ identifiers: ['lobe-remote-device'] });++ expect(result.content).toContain('Not found: lobe-remote-device');+ });+ });});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts b/apps/server/src/services/toolExecution/serverRuntimes/activator.tsindex 956fd47ae87..debbb539b5d 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts@@ -6,7 +6,7 @@ import {type ToolManifestInfo,} from '@lobechat/builtin-tool-activator/executionRuntime';import { SkillsExecutionRuntime } from '@lobechat/builtin-tool-skills/executionRuntime';-import { getDisabledPluginIds } from '@lobechat/types';+import { describeLockedDevicePicker, getDisabledPluginIds } from '@lobechat/types';import { AgentModel } from '@/database/models/agent';import { AgentSkillModel } from '@/database/models/agentSkill';@@ -17,6 +17,7 @@ import {} from '@/server/services/agentSignal/procedure';import { redisPolicyStateStore } from '@/server/services/agentSignal/store/adapters/redis/policyStateStore';+import { REMOTE_DEVICE_TOOL_IDENTIFIER } from './noActiveDevice';import { type ServerRuntimeRegistration } from './types';/**@@ -131,6 +132,12 @@ export const activatorRuntime: ServerRuntimeRegistration = {}}: undefined,+ // A device-locked run walls the picker off, so activating it can only fail;+ // say why, so the model sends the user to the device selector instead.+ explainNotFound: (identifier) =>+ identifier === REMOTE_DEVICE_TOOL_IDENTIFIER && context.executionPlan+ ? describeLockedDevicePicker(context.executionPlan)+ : undefined,getActivatedToolIds: () => [...activatedIds],getToolManifests: async (identifiers: string[]): Promise<ToolManifestInfo[]> => {// Note: context.toolManifestMap should only contain discoverable tools.diff --git a/apps/server/src/services/toolExecution/types.ts b/apps/server/src/services/toolExecution/types.tsindex 0bac8a7bff1..7410f886e45 100644--- a/apps/server/src/services/toolExecution/types.ts+++ b/apps/server/src/services/toolExecution/types.ts@@ -6,6 +6,7 @@ import {type ClientSecretPayload,type DeviceUnavailableErrorData,type ExecSubAgentParams,+ type ExecutionPlan,type StepActivatedSkill,type StepContextTodoItem,type WorkRegistrationIntent,@@ -245,6 +246,12 @@ export interface ToolExecutionContext {* flows; `lobe-agent.callSubAgent` uses the per-call `subAgent` runner below.*/execSubAgent?: (params: ExecSubAgentParams) => Promise<unknown>;+ /**+ * The run's resolved execution plan. Lets a runtime explain a gate the plan+ * imposes (e.g. a device-locked run has no device picker) instead of the+ * gated tool just looking missing.+ */+ executionPlan?: ExecutionPlan;/** Per-call execution timeout resolved by the agent runtime. */executionTimeoutMs?: number;/** Current group ID for group chat context */diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex e24515e75f5..b54a46b2f7b 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -1,6 +1,7 @@import { ToolNameResolver } from '@lobechat/context-engine';import {type ChatToolPayload,+ describeLockedDevicePicker,type ExtendedHumanInterventionConfig,type HumanInterventionConfig,type HumanInterventionPolicy,@@ -39,6 +40,8 @@ const TOOL_NOT_ALLOWED_REASON = 'tool_not_allowed';*/const unresolvedToolContent = (names: string) =>`Tool call rejected: no available tool is named ${names}. Copy a name exactly as declared in the tools schema and call it again.`;+/** The remote-device picker; walled off on device-locked runs. */+const REMOTE_DEVICE_IDENTIFIER = 'lobe-remote-device';const UNRESOLVED_TOOL_REASON = 'tool_name_unresolved';/*** How many times one operation may answer unresolvable tool calls with a@@ -820,9 +823,29 @@ export class GeneralChatAgent implements Agent {);}+ // A picker call on a locked run is not a typo: the tool was withheld on+ // purpose, and "copy the name exactly" sends the model into a retry+ // loop that ends the operation. Say why and who can switch instead;+ // any other unresolved name in the batch keeps the typo feedback.+ const lockedPickerNote = state.plan?.execution+ ? describeLockedDevicePicker(state.plan.execution)+ : undefined;+ const isPickerCall = (name: string) =>+ name.split(PLUGIN_SCHEMA_SEPARATOR)[0] === REMOTE_DEVICE_IDENTIFIER;+ const allNames = namedToolCalls.map((toolCall) => toolCall.function.name);+ const pickerNames = lockedPickerNote ? allNames.filter(isPickerCall) : [];+ const otherNames = allNames.filter((name) => !pickerNames.includes(name));+ const blockedContent = [+ pickerNames.length > 0 &&+ `Tool call rejected: ${pickerNames.join(', ')} is not available in this run. ${lockedPickerNote}`,+ otherNames.length > 0 && unresolvedToolContent(otherNames.join(', ')),+ ]+ .filter(Boolean)+ .join('\n\n');+return {payload: {- blockedContent: unresolvedToolContent(unresolvedNames),+ blockedContent,blockedReason: UNRESOLVED_TOOL_REASON,parentMessageId,unresolvedToolNames: true,diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.tsindex 8ef8696262b..8d2883c37c2 100644--- a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.test.ts@@ -305,6 +305,82 @@ describe('GeneralChatAgent', () => {// agent used to finish with "completed without tool calls", writing an// empty assistant message while the requested work never ran. Reject the// calls instead so the model can retry with a real name.+ it('explains a device-picker call on a device-locked run instead of asking for the exact name', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });++ const state = createMockState({+ plan: { execution: { deviceId: 'device-a', kind: 'device', target: 'local' } },+ } as Partial<AgentState>);+ const context = createMockContext('llm_result', {+ hasToolsCalling: true,+ toolsCalling: [],+ parentMessageId: 'msg-1',+ result: {+ content: '',+ tool_calls: [+ {+ id: 't1',+ type: 'function',+ function: {+ name: 'lobe-remote-device____activateDevice',+ arguments: '{"deviceId":"device-b"}',+ },+ },+ ],+ },+ });++ const result = (await agent.runner(context, state)) as any;++ expect(result.type).toBe('resolve_blocked_tools');+ expect(result.payload.blockedContent).toContain(+ 'lobe-remote-device____activateDevice is not available in this run',+ );+ expect(result.payload.blockedContent).toContain('locked to device "device-a"');+ expect(result.payload.blockedContent).toContain('device selector');+ expect(result.payload.blockedContent).not.toContain('Copy a name exactly');+ });++ it('keeps the typo feedback for other names batched with a locked picker call', async () => {+ const agent = new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ operationId: 'test-session',+ modelRuntimeConfig: mockModelRuntimeConfig,+ });++ const state = createMockState({+ plan: { execution: { deviceId: 'device-a', kind: 'device', target: 'local' } },+ } as Partial<AgentState>);+ const context = createMockContext('llm_result', {+ hasToolsCalling: true,+ toolsCalling: [],+ parentMessageId: 'msg-1',+ result: {+ content: '',+ tool_calls: [+ {+ id: 't1',+ type: 'function',+ function: { name: 'lobe-remote-device____activateDevice', arguments: '{}' },+ },+ { id: 't2', type: 'function', function: { name: 'activateTools', arguments: '{}' } },+ ],+ },+ });++ const result = (await agent.runner(context, state)) as any;++ expect(result.payload.blockedContent).toBe(+ 'Tool call rejected: lobe-remote-device____activateDevice is not available in this run. Device switching is off for this run: it is locked to device "device-a", where the Local System tools already run. You cannot activate another device from here. If the user wants a different device, tell them to pick it in the device selector of the chat input and send the message again.' ++ '\n\n' ++ 'Tool call rejected: no available tool is named activateTools. Copy a name exactly as declared in the tools schema and call it again.',+ );+ });+it('should reject unresolvable tool_calls so the model can retry', async () => {const agent = new GeneralChatAgent({agentConfig: { maxSteps: 100 },diff --git a/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts b/packages/builtin-tool-activator/src/ExecutionRuntime/index.tsindex fe52e10eb25..1bc55b26901 100644--- a/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts@@ -12,6 +12,12 @@ export interface ToolManifestInfo {export interface ActivatorRuntimeService {activateSkill?: (args: ActivateSkillParams) => Promise<BuiltinServerRuntimeOutput>;+ /**+ * Why an identifier that exists is withheld from this run, if the host knows.+ * A bare "Not found" for a tool the model has seen before reads as a typo, so+ * it retries instead of telling the user what they can change.+ */+ explainNotFound?: (identifier: string) => string | undefined;getActivatedToolIds: () => string[];getToolManifests: (identifiers: string[]) => Promise<ToolManifestInfo[]>;markActivated: (identifiers: string[]) => void;@@ -129,8 +135,15 @@ export class ActivatorExecutionRuntime {parts.push(`\nAlready active: ${alreadyActiveList.join(', ')}`);}- if (notFound.length > 0) {- parts.push(`\nNot found: ${notFound.join(', ')}`);+ const unexplained: string[] = [];+ for (const id of notFound) {+ const explanation = this.service.explainNotFound?.(id);+ if (explanation) parts.push(`\nNot available: ${id}. ${explanation}`);+ else unexplained.push(id);+ }++ if (unexplained.length > 0) {+ parts.push(`\nNot found: ${unexplained.join(', ')}`);}return {diff --git a/packages/types/src/agent/executionTargetRules.ts b/packages/types/src/agent/executionTargetRules.tsindex 18aca4616d9..d016794a5e0 100644--- a/packages/types/src/agent/executionTargetRules.ts+++ b/packages/types/src/agent/executionTargetRules.ts@@ -43,3 +43,21 @@ export const isDeviceCapablePlan = (plan: ExecutionPlan): boolean =>export const isDeviceLockedPlan = (plan: ExecutionPlan): boolean =>plan.kind === 'device' ||(plan.kind === 'device-unrouted' && plan.reason === 'bound-device-offline');++/**+ * What the model is told when it reaches for the remote-device picker on a+ * locked run. The picker is walled off (see {@link isDeviceLockedPlan}), so+ * without this it only looks missing ("Not found", "no available tool") and+ * the model keeps retrying, or gives up without telling the user that switching+ * devices is theirs to do.+ */+export const describeLockedDevicePicker = (plan: ExecutionPlan): string | undefined => {+ if (!isDeviceLockedPlan(plan)) return;++ const switchHint =+ 'You cannot activate another device from here. If the user wants a different device, tell them to pick it in the device selector of the chat input and send the message again.';++ return plan.kind === 'device'+ ? `Device switching is off for this run: it is locked to device "${plan.deviceId}", where the Local System tools already run. ${switchHint}`+ : `Device switching is off for this run: it is locked to the user's bound device, which is offline. Tell the user to reconnect it (LobeHub desktop app or \`lh connect\`). ${switchHint}`;+};