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(agent-runtime): resolve wire names in activateTools instead of a bare Not found (#20791)

Arvin Xu27ad65ff7bc3
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 d52d250a305..543ae6520d7 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/activator.test.ts
@@ -159,6 +159,77 @@ describe('activatorRuntime', () => {
});
});
+ 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
+ // identifier. Activation must resolve it instead of a bare "Not found"
+ // that the model then retried until it vented.
+ const webBrowsingManifest = {
+ api: [
+ { name: 'search', parameters: {} },
+ { name: 'crawlSinglePage', parameters: {} },
+ ],
+ identifier: 'lobe-web-browsing',
+ meta: { title: 'Web Browsing' },
+ type: 'builtin',
+ } as never;
+
+ it('activates a tool requested by its wire name (identifier____apiName)', async () => {
+ const { activatorRuntime } = await import('../activator');
+ const runtime = await activatorRuntime.factory({
+ serverDB: {} as never,
+ toolManifestMap: { 'lobe-web-browsing': webBrowsingManifest },
+ userId: 'user-1',
+ });
+
+ const result = await runtime.activateTools({
+ identifiers: ['lobe-web-browsing____search'],
+ });
+
+ expect(result.content).toContain('Successfully activated tools: lobe-web-browsing.search');
+ expect(result.state?.notFound).toEqual([]);
+ }, 20_000);
+
+ it('activates a tool requested by a wire name with an MD5-compressed api segment', async () => {
+ const { activatorRuntime } = await import('../activator');
+ const runtime = await activatorRuntime.factory({
+ serverDB: {} as never,
+ toolManifestMap: { 'lobe-web-browsing': webBrowsingManifest },
+ userId: 'user-1',
+ });
+
+ const result = await runtime.activateTools({
+ identifiers: ['lobe-web-browsing____MD5HASH_abc123def456'],
+ });
+
+ expect(result.content).toContain('Successfully activated tools: lobe-web-browsing.search');
+ expect(result.state?.notFound).toEqual([]);
+ }, 20_000);
+
+ it('activates a tool whose wire name carries an MD5-compressed identifier segment via the discoverable list', async () => {
+ // Codex P2 on PR #20791: a hashed identifier segment cannot be probed
+ // against the identifier-keyed `toolManifestMap`; the runtime must use
+ // the host's discoverable list and match hashed wire-name variants
+ // locally (mirror of `ToolNameResolver.generate`).
+ const { Md5 } = await import('ts-md5');
+ const wireHash = (segment: string) =>
+ `MD5HASH_${Md5.hashStr(segment).toString().slice(0, 12)}`;
+ const { activatorRuntime } = await import('../activator');
+ const runtime = await activatorRuntime.factory({
+ serverDB: {} as never,
+ toolManifestMap: { 'lobe-web-browsing': webBrowsingManifest },
+ userId: 'user-1',
+ });
+
+ const result = await runtime.activateTools({
+ identifiers: [`${wireHash('lobe-web-browsing')}____${wireHash('search')}`],
+ });
+
+ expect(result.content).toContain('Successfully activated tools: lobe-web-browsing.search');
+ expect(result.state?.notFound).toEqual([]);
+ }, 20_000);
+ });
+
describe('Agent Share visitor runs', () => {
const userSkill = {
content: '# User skill',
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
index 33e6d5b19e2..23241956cec 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/activator.ts
@@ -171,14 +171,31 @@ export const activatorRuntime: ServerRuntimeRegistration = {
description: a.description,
name: a.name,
})),
+ // Passed through for wire-name matching: non-builtin types
+ // (`mcp`, `standalone`) append a `____<type>` segment to the
+ // offered wire name, so resolving a copied name needs it.
identifier: manifest.identifier,
name: manifest.meta?.title ?? manifest.identifier,
systemRole: manifest.systemRole,
+ type: manifest.type,
});
}
return results;
},
+ // Full discoverable list, for inverting `MD5HASH_…` wire-name segments
+ // and resolving bare API names: neither can be probed against the
+ // identifier-keyed map, so the runtime hashes every discoverable
+ // identifier locally and matches the generated wire-name variants. Same
+ // scoping as `getToolManifests` β€” the map only holds discoverable tools.
+ listToolManifests: async (): Promise<ToolManifestInfo[]> =>
+ Object.values(context.toolManifestMap ?? {}).map((manifest) => ({
+ apiDescriptions: manifest.api.map((a) => ({ description: a.description, name: a.name })),
+ identifier: manifest.identifier,
+ name: manifest.meta?.title ?? manifest.identifier,
+ systemRole: manifest.systemRole,
+ type: manifest.type,
+ })),
markActivated: (identifiers: string[]) => {
for (const id of identifiers) {
if (!activatedIds.includes(id)) {
diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
index bf67996d14e..556ec950999 100644
--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts
+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts
@@ -52,7 +52,8 @@ const partitionEmptyArgumentsCalls = (toolsCalling: ChatToolPayload[]) => {
const emptyArgsCalls: ChatToolPayload[] = [];
const executableCalls: ChatToolPayload[] = [];
for (const toolCalling of toolsCalling) {
- if (toolCalling.arguments && toolCalling.arguments.trim().length > 0) executableCalls.push(toolCalling);
+ if (toolCalling.arguments && toolCalling.arguments.trim().length > 0)
+ executableCalls.push(toolCalling);
else emptyArgsCalls.push(toolCalling);
}
return { emptyArgsCalls, executableCalls };
diff --git a/packages/agent-runtime/src/executors/tool.test.ts b/packages/agent-runtime/src/executors/tool.test.ts
index 22a771bded2..583a7eaa2c2 100644
--- a/packages/agent-runtime/src/executors/tool.test.ts
+++ b/packages/agent-runtime/src/executors/tool.test.ts
@@ -176,6 +176,41 @@ describe('tool executors', () => {
expect(result.newState.usage.tools.totalCalls).toBe(1);
});
+ it('deduplicates activatedTools persisted in one tool result (PR #20791 P2 regression)', async () => {
+ // persistActivatedTools updates its dedup set inside the filter: a result
+ // listing the same plugin twice (e.g. two wire names of one plugin both
+ // resolved to the same identifier) must be appended once.
+ runTool = vi.fn().mockResolvedValue({
+ attempts: 1,
+ result: {
+ content: 'Tool result',
+ executionTime: 100,
+ state: {
+ activatedTools: [
+ { identifier: 'lobe-web-browsing' },
+ { identifier: 'lobe-web-browsing' },
+ ],
+ },
+ success: true,
+ },
+ });
+ host.transports.tools!.run = runTool;
+
+ const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
+ payload: {
+ parentMessageId: 'assistant-msg-1',
+ toolCalling: createToolCall(),
+ },
+ type: 'call_tool',
+ };
+
+ const result = await callTool(host)(instruction, createState());
+
+ const stepTools = result.newState.activatedStepTools ?? [];
+ expect(stepTools).toHaveLength(1);
+ expect(stepTools[0]).toMatchObject({ id: 'lobe-web-browsing', source: 'discovery' });
+ });
+
it('parks single client-source tools without invoking the transport runner', async () => {
const instruction: Extract<AgentInstruction, { type: 'call_tool' }> = {
payload: {
diff --git a/packages/agent-runtime/src/executors/tool.ts b/packages/agent-runtime/src/executors/tool.ts
index dba40624311..bf343bf4bc5 100644
--- a/packages/agent-runtime/src/executors/tool.ts
+++ b/packages/agent-runtime/src/executors/tool.ts
@@ -559,8 +559,15 @@ const persistActivatedTools = ({
Array<{ identifier: string }> | undefined;
if (!discoveredTools?.length) continue;
+ // The set is updated inside the filter, not after mapping the batch: two
+ // results in the same step (or one result listing the same tool twice)
+ // would otherwise both pass and be appended twice.
const newActivations = discoveredTools
- .filter((tool) => !existingIds.has(tool.identifier))
+ .filter((tool) => {
+ if (existingIds.has(tool.identifier)) return false;
+ existingIds.add(tool.identifier);
+ return true;
+ })
.map((tool) => ({
activatedAtStep: stepCount,
id: tool.identifier,
@@ -568,8 +575,6 @@ const persistActivatedTools = ({
source: 'discovery' as const,
}));
- for (const activation of newActivations) existingIds.add(activation.id);
-
if (newActivations.length > 0) {
newState.activatedStepTools = [...(newState.activatedStepTools ?? []), ...newActivations];
}
diff --git a/packages/builtin-tool-activator/package.json b/packages/builtin-tool-activator/package.json
index 7fdb162c0ad..c1b338f8ef3 100644
--- a/packages/builtin-tool-activator/package.json
+++ b/packages/builtin-tool-activator/package.json
@@ -9,6 +9,9 @@
"./executionRuntime": "./src/ExecutionRuntime/index.ts"
},
"main": "./src/index.ts",
+ "dependencies": {
+ "ts-md5": "^2.0.1"
+ },
"devDependencies": {
"@lobechat/prompts": "workspace:*",
"@lobechat/types": "workspace:*"
diff --git a/packages/builtin-tool-activator/src/ExecutionRuntime/__tests__/activateTools-resolution.test.ts b/packages/builtin-tool-activator/src/ExecutionRuntime/__tests__/activateTools-resolution.test.ts
new file mode 100644
index 00000000000..ab1564a4dc5
--- /dev/null
+++ b/packages/builtin-tool-activator/src/ExecutionRuntime/__tests__/activateTools-resolution.test.ts
@@ -0,0 +1,311 @@
+import { Md5 } from 'ts-md5';
+import { describe, expect, it, vi } from 'vitest';
+
+import { ActivatorExecutionRuntime, type ToolManifestInfo } from '../index';
+
+/**
+ * Same truncation as the runtime's `hashSegment` (mirror of
+ * `ToolNameResolver.genHash`): 12-char MD5 prefix.
+ */
+const wireHash = (segment: string): string =>
+ `MD5HASH_${Md5.hashStr(segment).toString().slice(0, 12)}`;
+
+const webBrowsingManifest: ToolManifestInfo = {
+ apiDescriptions: [
+ { description: 'Search the web.', name: 'search' },
+ { description: 'Crawl one page.', name: 'crawlSinglePage' },
+ ],
+ identifier: 'lobe-web-browsing',
+ name: 'Web Browsing',
+};
+
+const buildService = (manifests: ToolManifestInfo[]) => ({
+ getActivatedToolIds: vi.fn(() => [] as string[]),
+ getToolManifests: vi.fn(async (identifiers: string[]) =>
+ manifests.filter((m) => identifiers.includes(m.identifier)),
+ ),
+ listToolManifests: vi.fn(async () => manifests),
+ markActivated: vi.fn(),
+});
+
+describe('ActivatorExecutionRuntime.activateTools β€” request-name resolution', () => {
+ it('resolves a wire name (identifier____apiName) to the plugin identifier', async () => {
+ const service = buildService([webBrowsingManifest]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({
+ identifiers: ['lobe-web-browsing____search'],
+ reason: 'test',
+ });
+
+ expect(result.content).toContain('Successfully activated tools: lobe-web-browsing.search');
+ expect(result.state?.notFound).toEqual([]);
+ expect(service.markActivated).toHaveBeenCalledWith(['lobe-web-browsing']);
+ });
+
+ it('resolves a bare API name by loading the full discoverable list', async () => {
+ // Codex P2 on PR #20791: the probe sends only the API name to the
+ // identifier-keyed map (no manifests come back), so the unique bare-name
+ // match must come from the host's full discoverable list.
+ const service = buildService([webBrowsingManifest]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({ identifiers: ['search'], reason: 'test' });
+
+ expect(service.getToolManifests).toHaveBeenCalledWith(['search']);
+ expect(service.listToolManifests).toHaveBeenCalled();
+ expect(result.content).toContain('Successfully activated tools: lobe-web-browsing.search');
+ expect(result.state?.notFound).toEqual([]);
+ });
+
+ it('resolves a bare API name when the manifests were returned for the request', async () => {
+ // The host's getToolManifests only matches plugin identifiers, so a bare
+ // API name gets no manifests back β€” the resolver then passes it through.
+ // This pins that behavior: bare names resolve only when the host returns
+ // the manifest for them.
+ const service = {
+ getActivatedToolIds: vi.fn(() => [] as string[]),
+ getToolManifests: vi.fn(async (identifiers: string[]) =>
+ identifiers.includes('lobe-web-browsing') ? [webBrowsingManifest] : [],
+ ),
+ markActivated: vi.fn(),
+ };
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({
+ identifiers: ['lobe-web-browsing'],
+ reason: 'test',
+ });
+
+ expect(result.content).toContain('Successfully activated tools: lobe-web-browsing.search');
+ });
+
+ it('resolves a wire name whose api segment is MD5-compressed to the identifier prefix', async () => {
+ const service = buildService([webBrowsingManifest]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({
+ identifiers: [`lobe-web-browsing____${wireHash('search')}`],
+ reason: 'test',
+ });
+
+ expect(result.content).toContain('Successfully activated tools: lobe-web-browsing.search');
+ expect(result.state?.notFound).toEqual([]);
+ });
+
+ it('still returns Not found for a name that matches no manifest', async () => {
+ const service = buildService([webBrowsingManifest]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({
+ identifiers: ['totally-unknown-tool'],
+ reason: 'test',
+ });
+
+ expect(result.content).toContain('Not found: totally-unknown-tool');
+ expect(result.state?.notFound).toEqual(['totally-unknown-tool']);
+ });
+
+ it('does not resolve an ambiguous bare API name shared by two manifests', async () => {
+ const otherManifest: ToolManifestInfo = {
+ apiDescriptions: [{ description: 'Search something else.', name: 'search' }],
+ identifier: 'other-tool',
+ name: 'Other Tool',
+ };
+ const service = buildService([webBrowsingManifest, otherManifest]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({ identifiers: ['search'], reason: 'test' });
+
+ expect(result.content).toContain('Not found: search');
+ });
+
+ it('reports already-active for a wire name whose plugin is already activated', async () => {
+ const service = buildService([webBrowsingManifest]);
+ service.getActivatedToolIds.mockReturnValue(['lobe-web-browsing']);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({
+ identifiers: ['lobe-web-browsing____search'],
+ reason: 'test',
+ });
+
+ expect(result.content).toContain('Already active: lobe-web-browsing');
+ expect(result.state?.notFound).toEqual([]);
+ });
+
+ it('keeps the exact plugin identifier working unchanged', async () => {
+ const service = buildService([webBrowsingManifest]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({
+ identifiers: ['lobe-web-browsing'],
+ reason: 'test',
+ });
+
+ expect(result.content).toContain('Successfully activated tools: lobe-web-browsing.search');
+ });
+
+ it('deduplicates identifiers when one request carries two wire names of the same plugin', async () => {
+ // Vent scenario (Codex P2 on PR #20791): the model asks for two APIs of
+ // the same plugin; both resolve to the plugin identifier, and without dedup the
+ // response would list the plugin (and its manifests/React keys) twice.
+ const service = buildService([webBrowsingManifest]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({
+ identifiers: ['lobe-web-browsing____search', 'lobe-web-browsing____crawlSinglePage'],
+ reason: 'test',
+ });
+
+ expect(service.markActivated).toHaveBeenCalledTimes(1);
+ expect(service.markActivated).toHaveBeenCalledWith(['lobe-web-browsing']);
+ const occurrences = (result.content.match(/lobe-web-browsing\.search/g) ?? []).length;
+ expect(occurrences).toBe(1);
+ expect(result.state?.notFound).toEqual([]);
+ });
+
+ it('activates a tool requested by a wire name with an MD5-compressed api segment, mirroring ToolNameResolver variants', async () => {
+ // Codex P2 on PR #20791: `ToolNameResolver.generate` compresses the api
+ // segment to `MD5HASH_…` when the name is provider-invalid or over the
+ // length cap; a request copied from `tools[]` must match that exact
+ // variant instead of falling to the prefix probe.
+ const service = buildService([webBrowsingManifest]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({
+ identifiers: ['lobe-web-browsing____' + wireHash('search')],
+ reason: 'test',
+ });
+
+ expect(result.content).toContain('Successfully activated tools: lobe-web-browsing.search');
+ expect(result.state?.notFound).toEqual([]);
+ });
+
+ it('activates a tool requested by a wire name whose identifier segment is MD5-compressed', async () => {
+ // Codex P2 on PR #20791: when the identifier makes the generated name
+ // exceed the provider length cap, `ToolNameResolver.generate` hashes the
+ // identifier segment too (`MD5HASH_xxx____MD5HASH_yyy`). The prefix probe
+ // cannot invert it against the identifier-keyed map, so the host's
+ // discoverable list is used to match hashed variants locally.
+ const service = buildService([webBrowsingManifest]);
+ service.listToolManifests = vi.fn(async () => [webBrowsingManifest]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({
+ identifiers: [`${wireHash('lobe-web-browsing')}____${wireHash('search')}`],
+ reason: 'test',
+ });
+
+ expect(service.listToolManifests).toHaveBeenCalled();
+ expect(result.content).toContain('Successfully activated tools: lobe-web-browsing.search');
+ expect(result.state?.notFound).toEqual([]);
+ });
+
+ it('does not activate a truncated-identifier prefix tool for a separator-free request', async () => {
+ // Codex P2 on PR #20791: `identifiers: ['other-tool']` where another
+ // discoverable plugin is literally named `other-too` β€” the old probe
+ // derived `other-too` via `slice(0, -1)` and activated the wrong tool.
+ // No manifest here exposes an API named `other-tool` and no manifest is
+ // named `other-tool`, so a correct resolver has nothing to match.
+ const prefixTool: ToolManifestInfo = {
+ apiDescriptions: [{ description: 'An api.', name: 'unrelatedApi' }],
+ identifier: 'other-too',
+ name: 'Other Too',
+ };
+ const service = buildService([prefixTool]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({ identifiers: ['other-tool'], reason: 'test' });
+
+ // `other-tool` is not a manifest identifier nor an API name; the
+ // truncated prefix must not be probed, so the request cannot resolve to
+ // `other-too`.
+ expect(result.content).toContain('Not found: other-tool');
+ expect(result.state?.notFound).toEqual(['other-tool']);
+ });
+
+ it('activates a tool requested by a bare API name unique to one manifest', async () => {
+ // Separator-free request that IS a real API name resolves via the
+ // discoverable list without ever slicing a truncated identifier.
+ const prefixTool: ToolManifestInfo = {
+ apiDescriptions: [{ description: 'An api.', name: 'other-tool' }],
+ identifier: 'other-too',
+ name: 'Other Too',
+ };
+ const service = buildService([prefixTool]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({ identifiers: ['other-tool'], reason: 'test' });
+
+ expect(result.content).toContain('Successfully activated tools: other-too.other-tool');
+ expect(result.state?.notFound).toEqual([]);
+ });
+
+ it('activates a hashed MCP wire name carrying a type segment', async () => {
+ // Codex P2 on PR #20791: MCP/standalone manifests get a `____<type>`
+ // segment from `ToolNameResolver.generate`, so a copied name for a
+ // hashed MCP identifier is `MD5HASH_x____MD5HASH_y____mcp` β€” the type
+ // must come through the manifest and match, not fall to the prefix probe.
+ const mcpManifest: ToolManifestInfo = {
+ apiDescriptions: [{ description: 'List issues.', name: 'listIssues' }],
+ identifier: 'github-mcp',
+ name: 'GitHub MCP',
+ type: 'mcp',
+ };
+ const service = buildService([mcpManifest]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({
+ identifiers: [`${wireHash('github-mcp')}____${wireHash('listIssues')}____mcp`],
+ reason: 'test',
+ });
+
+ expect(result.content).toContain('Successfully activated tools: github-mcp.listIssues');
+ expect(result.state?.notFound).toEqual([]);
+ });
+
+ it('activates a typed wire name even when the request dropped the type segment', async () => {
+ // Tolerance path: a hashed MCP wire name without the `____mcp` suffix
+ // still recovers the same tool through the untyped variant index.
+ const mcpManifest: ToolManifestInfo = {
+ apiDescriptions: [{ description: 'List issues.', name: 'listIssues' }],
+ identifier: 'github-mcp',
+ name: 'GitHub MCP',
+ type: 'mcp',
+ };
+ const service = buildService([mcpManifest]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({
+ identifiers: [`${wireHash('github-mcp')}____${wireHash('listIssues')}`],
+ reason: 'test',
+ });
+
+ expect(result.content).toContain('Successfully activated tools: github-mcp.listIssues');
+ expect(result.state?.notFound).toEqual([]);
+ });
+
+ it('activates the exact manifest identifier even when another plugin exposes an API with the same name', async () => {
+ // Codex P2 on PR #20791: a plugin whose identifier equals another
+ // plugin's API name must resolve to itself, not be hijacked by the
+ // bare-API-name path.
+ const impostor: ToolManifestInfo = {
+ apiDescriptions: [{ description: 'A colliding api.', name: 'other-tool' }],
+ identifier: 'impostor-plugin',
+ name: 'Impostor Plugin',
+ };
+ const target: ToolManifestInfo = {
+ apiDescriptions: [{ description: 'Target api.', name: 'targetApi' }],
+ identifier: 'other-tool',
+ name: 'Other Tool',
+ };
+ const service = buildService([impostor, target]);
+ const runtime = new ActivatorExecutionRuntime({ service });
+
+ const result = await runtime.activateTools({ identifiers: ['other-tool'], reason: 'test' });
+
+ expect(result.content).toContain('Successfully activated tools: other-tool.targetApi');
+ expect(result.state?.notFound).toEqual([]);
+ });
+});
diff --git a/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts b/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts
index 1bc55b26901..3c95bb52088 100644
--- a/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-activator/src/ExecutionRuntime/index.ts
@@ -1,4 +1,5 @@
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
+import { Md5 } from 'ts-md5';
import type { ActivatedToolInfo, ActivateSkillParams, ActivateToolsParams } from '../types';
@@ -8,6 +9,17 @@ export interface ToolManifestInfo {
identifier: string;
name: string;
systemRole?: string;
+ /**
+ * Tool type as the host classifies it (`mcp`, `standalone`, …). Mirrored
+ * from `LobeToolManifest.type`: `ToolNameResolver.generate` appends a
+ * `____<type>` segment for any type other than `builtin`/`default`, so wire
+ * names for hashed MCP/standalone identifiers can carry a third segment
+ * (`MD5HASH_x____MD5HASH_y____mcp`) that only resolves when the host passed
+ * the type through. Hosts that cannot classify default to `undefined`,
+ * which behaves exactly like `builtin` (no type segment) β€” the previous
+ * behavior for every manifest.
+ */
+ type?: string;
}
export interface ActivatorRuntimeService {
@@ -20,6 +32,23 @@ export interface ActivatorRuntimeService {
explainNotFound?: (identifier: string) => string | undefined;
getActivatedToolIds: () => string[];
getToolManifests: (identifiers: string[]) => Promise<ToolManifestInfo[]>;
+ /**
+ * Full list of discoverable tool manifests for this run, when the host can
+ * provide it. Two uses, both about requests the identifier-keyed
+ * `getToolManifests` map cannot answer:
+ *
+ * 1. Inverting `MD5HASH_…` wire-name segments: a hashed identifier segment
+ * cannot be probed against the identifier-keyed manifest map, but hashing
+ * every discoverable identifier and matching the generated variants
+ * recovers the exact tool that was offered.
+ * 2. Bare API names (`search`): the probe sends only the API name to the
+ * identifier-keyed map, which returns nothing β€” the full list is the only
+ * place the unique bare-name match can come from.
+ *
+ * Scoping to discoverable tools stays the host's responsibility, same as
+ * `getToolManifests`.
+ */
+ listToolManifests?: () => Promise<ToolManifestInfo[]>;
markActivated: (identifiers: string[]) => void;
}
@@ -27,6 +56,138 @@ export interface ActivatorExecutionRuntimeOptions {
service: ActivatorRuntimeService;
}
+/** Same separator the tool-call wire names use (`identifier____apiName`). */
+const TOOL_NAME_SEPARATOR = '____';
+
+/**
+ * Mirror of `ToolNameResolver`'s MD5 compression (`PLUGIN_SCHEMA_API_MD5_PREFIX`
+ * + 12-char truncated hash of the original component, `ts-md5`). The resolver
+ * compresses a wire-name segment when it is invalid for strict providers
+ * (non-ASCII, dots, …) or when the full name exceeds the configured max length
+ * (OpenAI caps function names at 64), so a model can copy a wire name whose
+ * identifier segment is `MD5HASH_…` β€” inverting that segment locally is the
+ * only way to recover which tool it asked for.
+ */
+const API_MD5_PREFIX = 'MD5HASH_';
+const hashSegment = (segment: string): string =>
+ API_MD5_PREFIX + Md5.hashStr(segment).toString().slice(0, 12);
+
+/**
+ * Mirror of `ToolNameResolver.generate`'s type-segment rule: only types other
+ * than `builtin`/`default` produce a third `____<type>` segment, and the type
+ * itself goes through `normalizeComponent` β€” invalid characters are hashed,
+ * provider-safe segments (`mcp`) stay verbatim.
+ */
+const TOOL_NAME_COMPONENT_PATTERN = /^[\w-]+$/;
+const wireTypeSegment = (type: string | undefined): string => {
+ if (!type || type === 'builtin' || type === 'default') return '';
+ const normalized = TOOL_NAME_COMPONENT_PATTERN.test(type) ? type : hashSegment(type);
+ return TOOL_NAME_SEPARATOR + normalized;
+};
+
+/**
+ * Models call `activateTools` with names copied from what they can see: the
+ * wire names in `tools[]` (`identifier____apiName____type`, possibly with
+ * `MD5HASH_…` segments from provider-name sanitization or long-name
+ * compression) or a bare API name (`activateTools`) β€” not the plugin-level
+ * identifier the manifest map is keyed by. The tool-call parse path
+ * (`ToolNameResolver`) understands all three; activation previously accepted
+ * only the bare identifier and answered "Not found" for the platform's own
+ * naming, so the model retried the exact same call until it vented (e.g.
+ * `lobe-web-browsing____search` with `lobe-web-browsing` enabled and
+ * discoverable).
+ *
+ * Resolve each requested name against the run's discovery manifests before
+ * the not-found fallbacks. Unresolvable names pass through unchanged so the
+ * existing skill fallback and error semantics stay intact.
+ */
+const resolveActivationIdentifier = (
+ requested: string,
+ manifests: ToolManifestInfo[],
+): string | undefined => {
+ // The request itself is already an exact manifest identifier. Checked first
+ // so a plugin whose identifier equals another plugin's API name can never be
+ // hijacked by the bare-name path below.
+ const exactIdentifier = manifests.find((m) => m.identifier === requested);
+ if (exactIdentifier) return exactIdentifier.identifier;
+
+ const byApiName = new Map<string, string[]>();
+ /** Every wire-name spelling `ToolNameResolver.generate` can produce per api. */
+ const byWireName = new Map<string, string>();
+
+ for (const manifest of manifests) {
+ for (const api of manifest.apiDescriptions) {
+ const matches = byApiName.get(api.name);
+ if (matches) matches.push(manifest.identifier);
+ else byApiName.set(api.name, [manifest.identifier]);
+
+ // Mirror every compression variant `ToolNameResolver.generate` can
+ // produce: the plain name, the api segment hashed (invalid chars or
+ // length cap), the identifier hashed (length cap), and both hashed β€”
+ // each with and without the `____<type>` segment for non-builtin tools
+ // (MCP/standalone manifests, whose offered wire names carry it). The
+ // untyped spelling stays indexed so a request that dropped the type
+ // segment still recovers the same tool. A request copied from
+ // `tools[]` matches the exact variant that was offered.
+ const baseVariants = [
+ `${manifest.identifier}${TOOL_NAME_SEPARATOR}${api.name}`,
+ `${manifest.identifier}${TOOL_NAME_SEPARATOR}${hashSegment(api.name)}`,
+ `${hashSegment(manifest.identifier)}${TOOL_NAME_SEPARATOR}${api.name}`,
+ `${hashSegment(manifest.identifier)}${TOOL_NAME_SEPARATOR}${hashSegment(api.name)}`,
+ ];
+ const typeSegment = wireTypeSegment(manifest.type);
+ for (const wireName of baseVariants) {
+ for (const spelling of typeSegment ? [wireName, wireName + typeSegment] : [wireName]) {
+ if (!byWireName.has(spelling)) {
+ byWireName.set(spelling, manifest.identifier);
+ }
+ }
+ }
+ }
+ }
+
+ // Exact wire name β€” the common case: the model copies the name it was
+ // offered (or a compressed variant of it) straight into `identifiers`.
+ const wireMatch = byWireName.get(requested);
+ if (wireMatch) return wireMatch;
+
+ // Wire name whose identifier segment is hashed but whose full spelling is
+ // not among the indexed variants (e.g. a type segment the host did not
+ // classify): activation is plugin-level, so resolving to the identifier
+ // prefix is still the tool the model asked for β€” and the prefix is
+ // manifest-list-scoped, so no wall is bypassed. Only derive a prefix when
+ // the separator is present: slicing a separator-free request would
+ // otherwise probe a truncated identifier as another tool. Bare names stay
+ // conservative: only a unique API match resolves.
+ const separatorIndex = requested.indexOf(TOOL_NAME_SEPARATOR);
+ if (separatorIndex > 0) {
+ const prefix = requested.slice(0, separatorIndex);
+ if (manifests.some((m) => m.identifier === prefix)) return prefix;
+ }
+
+ const apiMatches = byApiName.get(requested);
+ if (apiMatches?.length === 1) return apiMatches[0];
+
+ return undefined;
+};
+
+/**
+ * Which requests can only be answered from the full discoverable list. The
+ * probe into the identifier-keyed `getToolManifests` map cannot return
+ * manifests for them:
+ *
+ * - hashed identifier segments (`MD5HASH_…`) β€” the map is keyed by the
+ * original identifier;
+ * - separator-free bare names (`search`) β€” no identifier to probe, and the
+ * unique bare-API match needs the full list's `apiDescriptions`.
+ */
+const needsDiscoveryList = (identifiers: string[]): boolean =>
+ identifiers.some((id) => {
+ const separatorIndex = id.indexOf(TOOL_NAME_SEPARATOR);
+ if (separatorIndex <= 0) return true;
+ return id.slice(0, separatorIndex).startsWith(API_MD5_PREFIX);
+ });
+
export class ActivatorExecutionRuntime {
private service: ActivatorRuntimeService;
@@ -57,10 +218,57 @@ export class ActivatorExecutionRuntime {
try {
const alreadyActive = this.service.getActivatedToolIds();
+
+ // Wire names (`identifier____apiName____type`) and bare API names
+ // resolve to the plugin-level identifier the manifest map is keyed by β€”
+ // mirrored from the tool-call parse path so both entrances accept the
+ // same names.
+ //
+ // First try the identifier-keyed map (probing wire-name prefixes). A
+ // request it cannot answer β€” hashed identifier segments (`MD5HASH_…`,
+ // the map is keyed by the original identifier) or separator-free bare
+ // API names (nothing to probe) β€” then falls back to the full
+ // discoverable list when the host exposes one, and every request is
+ // re-resolved against it. The list is a superset of the probe results
+ // (same host, same discoverable scoping), so the re-resolution is
+ // consistent.
+ let discoveryManifests = await this.service.getToolManifests(
+ // The map lookup is by plugin identifier: a wire name misses it, so
+ // probe with the `____`-prefix too and let the resolver match. The
+ // prefix is only derived when the separator is present β€” slicing a
+ // separator-free request would probe a truncated identifier as
+ // another tool.
+ identifiers.flatMap((id) => {
+ const separatorIndex = id.indexOf(TOOL_NAME_SEPARATOR);
+ if (separatorIndex <= 0) return [id];
+ const prefix = id.slice(0, separatorIndex);
+ return prefix !== id ? [id, prefix] : [id];
+ }),
+ );
+ const unresolved = identifiers.filter(
+ (id) => resolveActivationIdentifier(id, discoveryManifests) === undefined,
+ );
+ if (
+ unresolved.length > 0 &&
+ needsDiscoveryList(unresolved) &&
+ typeof this.service.listToolManifests === 'function'
+ ) {
+ discoveryManifests = await this.service.listToolManifests();
+ }
+ // Deduplicate after resolution: two wire names of the same plugin
+ // (`lobe-web-browsing____search`, `…____crawlSinglePage`) both resolve
+ // to the plugin identifier, and duplicate entries would surface as
+ // duplicate manifests (and duplicate React keys) downstream.
+ const resolvedIdentifiers = [
+ ...new Set(
+ identifiers.map((id) => resolveActivationIdentifier(id, discoveryManifests) ?? id),
+ ),
+ ];
+
const toActivate: string[] = [];
const alreadyActiveList: string[] = [];
- for (const id of identifiers) {
+ for (const id of resolvedIdentifiers) {
if (alreadyActive.includes(id)) {
alreadyActiveList.push(id);
} else {
diff --git a/packages/builtin-tool-activator/vitest.config.mts b/packages/builtin-tool-activator/vitest.config.mts
new file mode 100644
index 00000000000..a9f5456ffd2
--- /dev/null
+++ b/packages/builtin-tool-activator/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'happy-dom',
+ },
+});
diff --git a/src/store/tool/slices/builtin/executors/__tests__/lobe-activator.test.ts b/src/store/tool/slices/builtin/executors/__tests__/lobe-activator.test.ts
index d20ee7b1b7e..55476a08bde 100644
--- a/src/store/tool/slices/builtin/executors/__tests__/lobe-activator.test.ts
+++ b/src/store/tool/slices/builtin/executors/__tests__/lobe-activator.test.ts
@@ -1,6 +1,7 @@
/**
* Tests for Lobe Tools Executor (activateTools discovery allowlist)
*/
+import { Md5 } from 'ts-md5';
import { beforeEach, describe, expect, it, vi } from 'vitest';
// Mock getToolStoreState
@@ -19,7 +20,6 @@ vi.mock('@/store/tool/selectors/tool', () => ({
// Import after mocks
const { activatorExecutor } = await import('../lobe-activator');
-
const makeBuiltinTool = (identifier: string, discoverable?: boolean) => ({
discoverable,
identifier,
@@ -129,4 +129,150 @@ describe('lobe-activator executor discovery allowlist', () => {
const activatedIds = state.activatedTools?.map((t: any) => t.identifier) ?? [];
expect(activatedIds).toContain('community-plugin');
});
+
+ it('should activate a hashed wire name via the client discoverable list', async () => {
+ // Codex P2 on PR #20791: the client executor did not implement
+ // `listToolManifests`, so `MD5HASH_x____MD5HASH_y` names had no manifests
+ // to resolve against and returned Not found even when the tool was
+ // discoverable. The list must be served from the same discovery
+ // allowlist as `getToolManifests`.
+ const tool = makeBuiltinTool('long-named-plugin');
+
+ mockGetState.mockReturnValue({
+ builtinTools: [tool],
+ installedPlugins: [],
+ });
+
+ mockAvailableToolsForDiscovery.mockReturnValue([
+ { description: 'desc', identifier: 'long-named-plugin', name: 'long-named-plugin' },
+ ]);
+
+ const wireName = `MD5HASH_${Md5.hashStr('long-named-plugin').toString().slice(0, 12)}____run`;
+
+ const result = await activatorExecutor.invoke(
+ 'activateTools',
+ { identifiers: [wireName], reason: 'Activate via hashed wire name.' },
+ { messageId: 'msg-1', operationId: 'op-1' },
+ );
+
+ expect(result.success).toBe(true);
+
+ const state = result.state as any;
+ const activatedIds = state.activatedTools?.map((t: any) => t.identifier) ?? [];
+ expect(activatedIds).toContain('long-named-plugin');
+ }, 10_000);
+
+ it('should activate a bare API name via the client discoverable list', async () => {
+ // Companion regression for the same P2: separator-free API names need
+ // the full list too β€” the identifier-keyed probe returns nothing for
+ // them.
+ const tool = makeBuiltinTool('web-browsing');
+
+ mockGetState.mockReturnValue({
+ builtinTools: [tool],
+ installedPlugins: [],
+ });
+
+ mockAvailableToolsForDiscovery.mockReturnValue([
+ { description: 'desc', identifier: 'web-browsing', name: 'web-browsing' },
+ ]);
+
+ const result = await activatorExecutor.invoke(
+ 'activateTools',
+ { identifiers: ['run'], reason: 'Activate via bare API name.' },
+ { messageId: 'msg-1', operationId: 'op-1' },
+ );
+
+ expect(result.success).toBe(true);
+
+ const state = result.state as any;
+ const activatedIds = state.activatedTools?.map((t: any) => t.identifier) ?? [];
+ expect(activatedIds).toContain('web-browsing');
+ }, 10_000);
+
+ it('should activate a cached Composio server tool while the plugin replica is still pending', async () => {
+ // Codex P2 on PR #20791: discovery exposes connected Composio servers
+ // straight from the cached `composioServers` replica, but manifest lookup
+ // only probed builtin tools, installed plugins and LobeHub Skill servers.
+ // During the startup window before the independent plugin fetch lands,
+ // `getInstalledPluginById` misses and activation failed with `Not found`.
+ mockGetState.mockReturnValue({
+ builtinTools: [],
+ composioServers: [
+ {
+ identifier: 'composio-github',
+ label: 'GitHub',
+ status: 'active',
+ tools: [{ description: 'Create an issue', inputSchema: {}, name: 'create_issue' }],
+ },
+ ],
+ installedPlugins: [],
+ });
+
+ mockAvailableToolsForDiscovery.mockReturnValue([
+ { description: 'GitHub tools', identifier: 'composio-github', name: 'GitHub' },
+ ]);
+
+ const result = await activatorExecutor.invoke(
+ 'activateTools',
+ {
+ identifiers: ['composio-github____create_issue'],
+ reason: 'Use the Composio GitHub connection.',
+ },
+ { messageId: 'msg-1', operationId: 'op-1' },
+ );
+
+ expect(result.success).toBe(true);
+
+ const state = result.state as any;
+ const activated = state.activatedTools?.find((t: any) => t.identifier === 'composio-github');
+ expect(activated).toBeDefined();
+ expect(activated.name).toBe('GitHub');
+ expect(activated.apiCount).toBe(1);
+ }, 10_000);
+
+ it('should let a connected LobeHub Skill server own a conflicting Composio identifier', async () => {
+ // Discovery's ownership rule: when a connector identifier has both legacy
+ // Composio and current LobeHub connections, the LobeHub Skill server owns
+ // the single visible entry. Manifest resolution must mirror that order.
+ mockGetState.mockReturnValue({
+ builtinTools: [],
+ composioServers: [
+ {
+ identifier: 'notion',
+ label: 'Legacy Composio Notion',
+ status: 'active',
+ tools: [{ description: 'Legacy api', inputSchema: {}, name: 'legacy_api' }],
+ },
+ ],
+ installedPlugins: [],
+ lobehubSkillServers: [
+ {
+ identifier: 'notion',
+ name: 'Notion',
+ status: 'connected',
+ tools: [{ description: 'LobeHub api', name: 'lobehub_api' }],
+ },
+ ],
+ });
+
+ mockAvailableToolsForDiscovery.mockReturnValue([
+ { description: 'Notion tools', identifier: 'notion', name: 'Notion' },
+ ]);
+
+ const result = await activatorExecutor.invoke(
+ 'activateTools',
+ {
+ identifiers: ['notion____lobehub_api'],
+ reason: 'Use the LobeHub Notion connection.',
+ },
+ { messageId: 'msg-1', operationId: 'op-1' },
+ );
+
+ expect(result.success).toBe(true);
+
+ const state = result.state as any;
+ const activatedIds = state.activatedTools?.map((t: any) => t.identifier) ?? [];
+ expect(activatedIds).toContain('notion');
+ }, 10_000);
});
diff --git a/src/store/tool/slices/builtin/executors/lobe-activator.ts b/src/store/tool/slices/builtin/executors/lobe-activator.ts
index 0627339d0d2..8c519ebe532 100644
--- a/src/store/tool/slices/builtin/executors/lobe-activator.ts
+++ b/src/store/tool/slices/builtin/executors/lobe-activator.ts
@@ -23,6 +23,7 @@ import { agentSkillService } from '@/services/skill';
import { getToolStoreState } from '@/store/tool';
import { pluginSelectors } from '@/store/tool/selectors';
import { toolSelectors } from '@/store/tool/selectors/tool';
+import { composioStoreSelectors } from '@/store/tool/slices/composioStore/selectors';
import { LobehubSkillStatus } from '@/store/tool/slices/lobehubSkillStore';
const skillsRuntime = new SkillsExecutionRuntime({
@@ -63,6 +64,9 @@ const service: ActivatorRuntimeService = {
identifier: builtin.identifier,
name: builtin.title ?? builtin.identifier,
systemRole: builtin.manifest.systemRole,
+ // Passed through for wire-name matching: non-builtin types append
+ // a `____<type>` segment to the offered wire name.
+ type: builtin.manifest.type,
});
continue;
}
@@ -79,6 +83,7 @@ const service: ActivatorRuntimeService = {
identifier: plugin.identifier,
name: plugin.manifest.meta?.title ?? plugin.identifier,
systemRole: plugin.manifest.systemRole,
+ type: (plugin.manifest as { type?: string }).type,
});
continue;
}
@@ -99,10 +104,50 @@ const service: ActivatorRuntimeService = {
});
continue;
}
+
+ // Search Composio MCP servers β€” the discovery allowlist includes
+ // connected Composio entries whose manifests come straight from the
+ // cached `composioServers` replica, while `getInstalledPluginById`
+ // only sees synced plugin replicas. During the startup window before
+ // the independent plugin fetch lands, the plugin probe misses and
+ // activation would fail with `Not found`; build the manifest from the
+ // cached server tools instead. Placed after the LobeHub Skill probe to
+ // mirror discovery's ownership rule: an identifier served by a
+ // connected LobeHub Skill server must not be claimed by its legacy
+ // Composio connection.
+ const composioManifest = composioStoreSelectors
+ .composioAsLobeTools(s)
+ .find((tool) => tool.identifier === id);
+ if (composioManifest) {
+ results.push({
+ apiDescriptions: (composioManifest.manifest.api || []).map((a: any) => ({
+ description: a.description,
+ name: a.name,
+ })),
+ avatar: composioManifest.manifest.meta?.avatar,
+ identifier: composioManifest.identifier,
+ name: composioManifest.manifest.meta?.title ?? composioManifest.identifier,
+ systemRole: composioManifest.manifest.systemRole,
+ type: (composioManifest.manifest as { type?: string }).type,
+ });
+ continue;
+ }
}
return results;
},
+ // Full discoverable list, for inverting `MD5HASH_…` wire-name segments and
+ // resolving bare API names: neither can be probed against the
+ // identifier-keyed `getToolManifests`, so the runtime hashes every
+ // discoverable identifier locally and matches the generated wire-name
+ // variants. Reuses `getToolManifests` on the same
+ // `availableToolsForDiscovery` allowlist so scoping and manifest mapping
+ // cannot drift between the two paths.
+ listToolManifests: async (): Promise<ToolManifestInfo[]> => {
+ const s = getToolStoreState();
+ const discoveryIds = toolSelectors.availableToolsForDiscovery(s).map((tool) => tool.identifier);
+ return service.getToolManifests(discoveryIds);
+ },
markActivated: () => {},
};