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(activator): keep why a tool is unavailable, and report tool activation as a tool (#23338)

AmAzing-a7cd4fb4c57e
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
index d706829230a..efe0a4e2f5e 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
@@ -173,6 +173,89 @@ describe('activatorRuntime', () => {
});
});
+ describe('activateTools β€” what the run already offers and what it reports', () => {
+ const webBrowsingManifest = {
+ api: [{ name: 'search', parameters: {} }],
+ identifier: 'lobe-web-browsing',
+ meta: { title: 'Web Browsing' },
+ type: 'builtin',
+ } as never;
+
+ it('answers "Already active" for a tool the run already offers', async () => {
+ // The runtime is rebuilt for every tool call, so an in-memory list of
+ // what it activated is always empty; what the run offers comes from
+ // `enabledToolIds` (operation tool set plus earlier activations).
+ const { activatorRuntime } = await import('../activator');
+ const runtime = await activatorRuntime.factory({
+ enabledToolIds: ['lobe-web-browsing'],
+ serverDB: {} as never,
+ toolManifestMap: { 'lobe-web-browsing': webBrowsingManifest },
+ userId: 'user-1',
+ });
+
+ const result = await runtime.activateTools({ identifiers: ['lobe-web-browsing'] });
+
+ expect(result.content).toContain('Already active: lobe-web-browsing');
+ expect(result.content).not.toContain('Successfully activated');
+ expect(result.state.alreadyActive).toEqual(['lobe-web-browsing']);
+ expect(result.state.activatedTools).toEqual([]);
+ }, 20_000);
+
+ it('reports an activated tool as a tool, outside the skill domain', async () => {
+ // Activating a tool used to be reported as `activateSkill` on
+ // `skill:builtin-skill` with the tool id as a skill object, which wrote
+ // skill procedure records, markers and receipts for something that is
+ // not a skill.
+ const { emitToolOutcomeSafely } = await import('@/server/services/agentSignal/procedure');
+ const { activatorRuntime } = await import('../activator');
+ const runtime = await activatorRuntime.factory({
+ serverDB: {} as never,
+ toolManifestMap: { 'lobe-web-browsing': webBrowsingManifest },
+ userId: 'user-1',
+ });
+
+ await runtime.activateTools({ identifiers: ['lobe-web-browsing'] });
+
+ await vi.waitFor(() => expect(emitToolOutcomeSafely).toHaveBeenCalledTimes(1));
+ const outcome = vi.mocked(emitToolOutcomeSafely).mock.calls[0][0];
+ expect(outcome).toMatchObject({
+ apiName: 'activateTools',
+ relatedObjects: [
+ { objectId: 'lobe-web-browsing', objectType: 'tool', relation: 'selected' },
+ ],
+ status: 'succeeded',
+ toolAction: 'activate',
+ });
+ expect(outcome.domainKey).toBeUndefined();
+ }, 20_000);
+
+ it('still reports a skill opened through the activateTools fallback as a skill', async () => {
+ mocks.findByName.mockImplementation(async (name: string) =>
+ name === 'user-skill' ? userSkillRow() : undefined,
+ );
+ mocks.getAgentConfigById.mockResolvedValue({
+ plugins: [{ identifier: 'user-skill-identifier', mode: 'auto' }],
+ });
+ const { emitToolOutcomeSafely } = await import('@/server/services/agentSignal/procedure');
+ const { activatorRuntime } = await import('../activator');
+ const runtime = await activatorRuntime.factory({
+ agentId: 'agent-1',
+ serverDB: {} as never,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ await runtime.activateTools({ identifiers: ['user-skill'] });
+
+ expect(emitToolOutcomeSafely).toHaveBeenCalledTimes(1);
+ expect(vi.mocked(emitToolOutcomeSafely).mock.calls[0][0]).toMatchObject({
+ apiName: 'activateSkill',
+ domainKey: 'skill:builtin-skill',
+ relatedObjects: [{ objectId: 'user-skill', objectType: 'skill', relation: 'selected' }],
+ });
+ }, 20_000);
+ });
+
describe('activateTools β€” wire-name resolution', () => {
// Production vent: the model requested `lobe-web-browsing____search` β€” the
// wire name from `tools[]` β€” while the manifest map is keyed by the plugin
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
index 3132e5041bd..197914b588d 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
@@ -27,10 +27,21 @@ import { type ServerRuntimeRegistration } from './types';
*/
export const activatorRuntime: ServerRuntimeRegistration = {
factory: async (context) => {
- const activatedIds: string[] = [];
+ // This factory runs for every tool call, so a list kept here only ever
+ // sees the current call. What the run already offers the model β€” the
+ // operation tool set plus earlier activations β€” arrives as
+ // `enabledToolIds`; seeding from it is what lets a repeated request
+ // answer "Already active".
+ const activatedIds: string[] = [...(context.enabledToolIds ?? [])];
const emitActivationOutcome = async (input: {
errorReason?: string;
identifiers: string[];
+ /**
+ * What was activated. Only a skill belongs to the skill procedure
+ * domain; a tool is reported as a tool, with no domain, so it leaves no
+ * skill record, marker or receipt behind.
+ */
+ kind: 'skill' | 'tool';
status: 'failed' | 'succeeded';
summary: string;
}) => {
@@ -43,10 +54,12 @@ export const activatorRuntime: ServerRuntimeRegistration = {
userId: context.userId,
});
+ const isSkill = input.kind === 'skill';
+
await emitToolOutcomeSafely({
- apiName: 'activateSkill',
+ apiName: isSkill ? 'activateSkill' : 'activateTools',
context: { agentId: context.agentId, userId: context.userId },
- domainKey: 'skill:builtin-skill',
+ domainKey: isSkill ? 'skill:builtin-skill' : undefined,
errorReason: input.errorReason,
identifier: LobeActivatorIdentifier,
intentClass: 'tool_command',
@@ -55,7 +68,7 @@ export const activatorRuntime: ServerRuntimeRegistration = {
policyStateStore: redisPolicyStateStore,
relatedObjects: input.identifiers.map((id) => ({
objectId: id,
- objectType: 'skill',
+ objectType: input.kind,
relation: 'selected',
})),
scope,
@@ -132,6 +145,7 @@ export const activatorRuntime: ServerRuntimeRegistration = {
const result = await skillsRuntime!.activateSkill(args);
await emitActivationOutcome({
identifiers: [args.name],
+ kind: 'skill',
status: 'succeeded',
summary: 'Activator selected a skill.',
});
@@ -140,6 +154,7 @@ export const activatorRuntime: ServerRuntimeRegistration = {
await emitActivationOutcome({
errorReason: (error as Error).message,
identifiers: [args.name],
+ kind: 'skill',
status: 'failed',
summary: 'Activator failed to select a skill.',
});
@@ -201,8 +216,9 @@ export const activatorRuntime: ServerRuntimeRegistration = {
}
void emitActivationOutcome({
identifiers,
+ kind: 'tool',
status: 'succeeded',
- summary: 'Activator marked skills as active.',
+ summary: 'Activator activated tools.',
}).catch((error) => {
console.error('[AgentSignal] Failed to emit activator outcome:', error);
});
diff --git a/packages/builtin-tool-activator/src/ExecutionRuntime/__tests__/activateTools-unavailable.test.ts b/packages/builtin-tool-activator/src/ExecutionRuntime/__tests__/activateTools-unavailable.test.ts
new file mode 100644
index 00000000000..a031da80d3c
--- /dev/null
+++ b/packages/builtin-tool-activator/src/ExecutionRuntime/__tests__/activateTools-unavailable.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { ActivatorExecutionRuntime, type ToolManifestInfo } from '../index';
+
+const webBrowsingManifest: ToolManifestInfo = {
+ apiDescriptions: [{ description: 'Search the web.', name: 'search' }],
+ identifier: 'lobe-web-browsing',
+ name: 'Web Browsing',
+};
+
+const LOCK_REASON = 'Device switching is off for this run: it is locked to device "device-a".';
+
+const buildRuntime = () =>
+ new ActivatorExecutionRuntime({
+ service: {
+ explainNotFound: (identifier) =>
+ identifier === 'lobe-remote-device' ? LOCK_REASON : undefined,
+ getActivatedToolIds: () => [],
+ getToolManifests: vi.fn(async (identifiers: string[]) =>
+ [webBrowsingManifest].filter((m) => identifiers.includes(m.identifier)),
+ ),
+ markActivated: vi.fn(),
+ },
+ });
+
+describe('ActivatorExecutionRuntime.activateTools β€” withheld tools', () => {
+ it('records the reason in state, so a later rewrite of the result can keep it', async () => {
+ // The result text is rebuilt from `state` once the activated tool's docs
+ // move to the system prompt (ActivationResultTrimProcessor). A reason that
+ // lives only in the text is lost there, and the model is left with a bare
+ // "Not found" for a tool it can see is installed.
+ const result = await buildRuntime().activateTools({
+ identifiers: ['lobe-web-browsing', 'lobe-remote-device', 'nonexistent'],
+ reason: 'test',
+ });
+
+ expect(result.content).toContain(`Not available: lobe-remote-device. ${LOCK_REASON}`);
+ expect(result.content).toContain('Not found: nonexistent');
+ expect(result.state?.notAvailable).toEqual([
+ { identifier: 'lobe-remote-device', reason: LOCK_REASON },
+ ]);
+ // `notFound` stays the full list of what could not be activated: the
+ // inspector counts it, and older readers know no other field.
+ expect(result.state?.notFound).toEqual(['lobe-remote-device', 'nonexistent']);
+ });
+
+ it('leaves `notAvailable` empty when the host explains nothing', async () => {
+ const result = await buildRuntime().activateTools({
+ identifiers: ['lobe-web-browsing', 'nonexistent'],
+ reason: 'test',
+ });
+
+ expect(result.state?.notAvailable).toEqual([]);
+ expect(result.state?.notFound).toEqual(['nonexistent']);
+ });
+});
diff --git a/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts b/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts
index 3c95bb52088..a74853644fa 100644
--- a/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts
@@ -1,7 +1,13 @@
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
import { Md5 } from 'ts-md5';
-import type { ActivatedToolInfo, ActivateSkillParams, ActivateToolsParams } from '../types';
+import type {
+ ActivatedToolInfo,
+ ActivateSkillParams,
+ ActivateToolsParams,
+ ActivateToolsState,
+ UnavailableToolInfo,
+} from '../types';
export interface ToolManifestInfo {
apiDescriptions: Array<{ description: string; name: string }>;
@@ -343,27 +349,31 @@ export class ActivatorExecutionRuntime {
parts.push(`\nAlready active: ${alreadyActiveList.join(', ')}`);
}
+ const notAvailable: UnavailableToolInfo[] = [];
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);
+ const reason = this.service.explainNotFound?.(id);
+ if (reason) {
+ parts.push(`\nNot available: ${id}. ${reason}`);
+ notAvailable.push({ identifier: id, reason });
+ } else {
+ unexplained.push(id);
+ }
}
if (unexplained.length > 0) {
parts.push(`\nNot found: ${unexplained.join(', ')}`);
}
- return {
- content: parts.join('\n'),
- state: {
- activatedSkills: activatedSkillResults.map((r) => r.state),
- activatedTools,
- alreadyActive: alreadyActiveList,
- notFound,
- },
- success: true,
+ const state: ActivateToolsState = {
+ activatedSkills: activatedSkillResults.map((r) => r.state),
+ activatedTools,
+ alreadyActive: alreadyActiveList,
+ notAvailable,
+ notFound,
};
+
+ return { content: parts.join('\n'), state, success: true };
} catch (e) {
return {
content: `Failed to activate tools: ${(e as Error).message}`,
diff --git a/packages/builtin-tool-activator/src/types.ts b/packages/builtin-tool-activator/src/types.ts
index 68c1222b551..ae43f124a8c 100644
--- a/packages/builtin-tool-activator/src/types.ts
+++ b/packages/builtin-tool-activator/src/types.ts
@@ -17,10 +17,10 @@ export interface ActivatedToolInfo {
name: string;
}
-export interface ActivateToolsState {
- activatedTools: ActivatedToolInfo[];
- alreadyActive: string[];
- notFound: string[];
+export interface UnavailableToolInfo {
+ identifier: string;
+ /** Why the host withholds the tool from this run, in words for the model. */
+ reason: string;
}
export interface ActivateSkillParams {
@@ -39,3 +39,18 @@ export interface ActivateSkillState {
/** Friendly title for UI display; falls back to `name` when unset. */
title?: string;
}
+
+export interface ActivateToolsState {
+ /** Skills opened because a requested identifier named a skill, not a tool. */
+ activatedSkills?: ActivateSkillState[];
+ activatedTools: ActivatedToolInfo[];
+ alreadyActive: string[];
+ /**
+ * The entries of `notFound` the host could explain. The result text is
+ * rebuilt from this state once the activated docs move to the system prompt,
+ * so a reason kept only in the text would not survive that rewrite.
+ */
+ notAvailable?: UnavailableToolInfo[];
+ /** Every requested identifier that was not activated, explained or not. */
+ notFound: string[];
+}
diff --git a/packages/context-engine/src/processors/ActivationResultTrim.ts b/packages/context-engine/src/processors/ActivationResultTrim.ts
index e83693ee5f4..4cbecb2effa 100644
--- a/packages/context-engine/src/processors/ActivationResultTrim.ts
+++ b/packages/context-engine/src/processors/ActivationResultTrim.ts
@@ -38,6 +38,11 @@ interface ActivatedSkillState {
name?: string;
}
+interface UnavailableToolState {
+ identifier?: string;
+ reason?: string;
+}
+
export interface ActivationResultTrimConfig {
/**
* Manifests whose systemRole / API descriptions the ToolSystemRoleProvider
@@ -181,6 +186,7 @@ export class ActivationResultTrimProcessor extends BaseProcessor {
activatedSkills?: ActivatedSkillState[];
activatedTools?: ActivatedToolState[];
alreadyActive?: string[];
+ notAvailable?: UnavailableToolState[];
notFound?: string[];
}
| undefined;
@@ -243,8 +249,17 @@ export class ActivationResultTrimProcessor extends BaseProcessor {
if (state?.alreadyActive?.length) {
parts.push(`Already active: ${state.alreadyActive.join(', ')}.`);
}
- if (state?.notFound?.length) {
- parts.push(`Not found: ${state.notFound.join(', ')}.`);
+ // `notFound` lists every identifier that was not activated; the ones the
+ // host explained keep their reason, so a tool withheld from this run does
+ // not read as a typo to retry.
+ const notAvailable = this.readUnavailableTools(state, message.content as string);
+ for (const item of notAvailable) {
+ parts.push(`Not available: ${item.identifier}. ${item.reason}`);
+ }
+ const explained = new Set(notAvailable.map((item) => item.identifier));
+ const notFound = (state?.notFound ?? []).filter((id) => !explained.has(id));
+ if (notFound.length > 0) {
+ parts.push(`Not found: ${notFound.join(', ')}.`);
}
parts.push('Usage instructions for the activated items are in the system prompt.');
@@ -252,12 +267,43 @@ export class ActivationResultTrimProcessor extends BaseProcessor {
return parts.join('\n');
}
+ /**
+ * The not-activated tools the host explained, with the reason it gave.
+ * Results persisted before `notAvailable` existed carry the reason only in
+ * their text, as a `Not available: <id>. <reason>` line per tool β€” read it
+ * back from there so those rows keep it too.
+ */
+ private readUnavailableTools(
+ state: { notAvailable?: UnavailableToolState[]; notFound?: string[] } | undefined,
+ original: string,
+ ): Array<{ identifier: string; reason: string }> {
+ if (Array.isArray(state?.notAvailable)) {
+ return state.notAvailable.flatMap((item) =>
+ item?.identifier && item.reason
+ ? [{ identifier: item.identifier, reason: item.reason }]
+ : [],
+ );
+ }
+
+ return (state?.notFound ?? []).flatMap((identifier) => {
+ const label = `\nNot available: ${identifier}. `;
+ const labelIndex = original.indexOf(label);
+ if (labelIndex === -1) return [];
+
+ const from = labelIndex + label.length;
+ const lineEnd = original.indexOf('\n', from);
+ const reason = original.slice(from, lineEnd === -1 ? undefined : lineEnd).trim();
+ return reason ? [{ identifier, reason }] : [];
+ });
+ }
+
/**
* Locate each fallback-activated skill's injected content inside the
* activateTools result blob (skill contents are appended in activation
* order) and return the non-injected suffix that follows each copy, cut at
- * the next skill's content or the trailing `Already active:` / `Not found:`
- * sections. Returns undefined when any copy cannot be located.
+ * the next skill's content or the trailing `Already active:` /
+ * `Not available:` / `Not found:` sections. Returns undefined when any copy
+ * cannot be located.
*/
private extractFallbackSkillRemainders(
original: string,
@@ -284,7 +330,7 @@ export class ActivationResultTrimProcessor extends BaseProcessor {
let to = index + 1 < positions.length ? positions[index + 1].start : original.length;
// Matches the literal section labels ActivatorExecutionRuntime appends
// after the skill contents.
- for (const label of ['\nAlready active:', '\nNot found:']) {
+ for (const label of ['\nAlready active:', '\nNot available:', '\nNot found:']) {
const labelIndex = original.indexOf(label, position.end);
if (labelIndex !== -1 && labelIndex < to) to = labelIndex;
}
diff --git a/packages/context-engine/src/processors/__tests__/ActivationResultTrim.test.ts b/packages/context-engine/src/processors/__tests__/ActivationResultTrim.test.ts
index f82aecddb68..5bb066042c6 100644
--- a/packages/context-engine/src/processors/__tests__/ActivationResultTrim.test.ts
+++ b/packages/context-engine/src/processors/__tests__/ActivationResultTrim.test.ts
@@ -8,6 +8,8 @@ import { ActivationResultTrimProcessor } from '../ActivationResultTrim';
const CREDS_SYSTEM_ROLE = 'lobe-creds instructions: manage credentials carefully.\n'.repeat(20);
const SKILL_CONTENT = '# PowerShell Skill\n\nRun PowerShell commands safely.\n'.repeat(20);
const RESOURCE_TREE = '<resources skill="PowerShell">\n- scripts/run.ps1\n</resources>';
+const LOCK_REASON =
+ 'Device switching is off for this run: it is locked to device "device-a". Tell the user to pick another device.';
const credsManifest = {
api: [
@@ -94,6 +96,93 @@ describe('ActivationResultTrimProcessor', () => {
expect(content).toContain('Not found: nonexistent.');
});
+ it('should keep why a withheld tool is unavailable instead of a bare not-found', async () => {
+ // A device-locked run walls the device picker off and the activator says
+ // why. Rebuilding the result from `notFound` alone turned that into
+ // "Not found: lobe-remote-device." on the very next LLM call β€” the typo
+ // reading the explanation exists to prevent.
+ const processor = new ActivationResultTrimProcessor({ injectedManifests: [credsManifest] });
+ const result = await processor.process(
+ createContext([
+ activateToolsMessage({
+ content: [
+ 'Successfully activated tools: lobe-creds.listCreds, lobe-creds.createCred.',
+ 'Usage instructions for the activated items are in the system prompt.',
+ `\nNot available: lobe-remote-device. ${LOCK_REASON}`,
+ '\nNot found: nonexistent',
+ ].join('\n'),
+ pluginState: {
+ activatedTools: [{ apiCount: 2, identifier: 'lobe-creds', name: 'Creds' }],
+ alreadyActive: [],
+ notAvailable: [{ identifier: 'lobe-remote-device', reason: LOCK_REASON }],
+ notFound: ['lobe-remote-device', 'nonexistent'],
+ },
+ }),
+ ]),
+ );
+
+ const content = result.messages[0].content as string;
+ expect(content).toContain(`Not available: lobe-remote-device. ${LOCK_REASON}`);
+ expect(content).toContain('Not found: nonexistent.');
+ expect(content).not.toContain('Not found: lobe-remote-device');
+ });
+
+ it('should recover the unavailable reason from results persisted without it in state', async () => {
+ // Rows written before `notAvailable` existed carry the reason only in
+ // their text; they are replayed on every later turn of the topic.
+ const processor = new ActivationResultTrimProcessor({ injectedManifests: [credsManifest] });
+ const result = await processor.process(
+ createContext([
+ activateToolsMessage({
+ content: [
+ 'Successfully activated tools: lobe-creds.listCreds, lobe-creds.createCred.',
+ 'Usage instructions for the activated items are in the system prompt.',
+ `\nNot available: lobe-remote-device. ${LOCK_REASON}`,
+ '\nNot found: nonexistent',
+ ].join('\n'),
+ pluginState: {
+ activatedTools: [{ apiCount: 2, identifier: 'lobe-creds', name: 'Creds' }],
+ alreadyActive: [],
+ notFound: ['lobe-remote-device', 'nonexistent'],
+ },
+ }),
+ ]),
+ );
+
+ const content = result.messages[0].content as string;
+ expect(content).toContain(`Not available: lobe-remote-device. ${LOCK_REASON}`);
+ expect(content).toContain('Not found: nonexistent.');
+ expect(content).not.toContain('Not found: lobe-remote-device');
+ });
+
+ it('should state the unavailable reason once next to a fallback-activated skill', async () => {
+ // The skill suffix is cut at the trailing sections; without the
+ // `Not available:` label the reason rode along inside the suffix and a
+ // contradicting "Not found" for the same tool was appended after it.
+ const processor = new ActivationResultTrimProcessor({
+ injectedManifests: [credsManifest],
+ injectedSkills: [powershellSkill],
+ });
+ const result = await processor.process(
+ createContext([
+ activateToolsMessage({
+ content: `Successfully activated tools: lobe-creds.listCreds, lobe-creds.createCred.\n${SKILL_CONTENT}\n\n${RESOURCE_TREE}\n\nNot available: lobe-remote-device. ${LOCK_REASON}`,
+ pluginState: {
+ activatedSkills: [{ name: 'PowerShell' }],
+ activatedTools: [{ apiCount: 2, identifier: 'lobe-creds', name: 'Creds' }],
+ notAvailable: [{ identifier: 'lobe-remote-device', reason: LOCK_REASON }],
+ notFound: ['lobe-remote-device'],
+ },
+ }),
+ ]),
+ );
+
+ const content = result.messages[0].content as string;
+ expect(content).toContain(RESOURCE_TREE);
+ expect(content.split(LOCK_REASON)).toHaveLength(2);
+ expect(content).not.toContain('Not found');
+ });
+
it('should NOT trim when an activated tool is not injected into the system prompt', async () => {
const processor = new ActivationResultTrimProcessor({ injectedManifests: [] });
const original = activateToolsMessage();