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: clamp message plugin identifier/apiName to 255 chars at every write path (#19002)

Arvin Xu5512942ba4d4
diff --git a/apps/server/src/services/agentEvalRun/index.ts b/apps/server/src/services/agentEvalRun/index.ts
index c13e32fc265..7ffa514c40e 100644
--- a/apps/server/src/services/agentEvalRun/index.ts
+++ b/apps/server/src/services/agentEvalRun/index.ts
@@ -17,6 +17,7 @@ import type {
ToolIntervention,
} from '@lobechat/types';
import { getActivePluginIds, RequestTrigger } from '@lobechat/types';
+import { clampToolIdentifier } from '@lobechat/utils/clampToolIdentifier';
import debug from 'debug';
import { eq, inArray, sql } from 'drizzle-orm';
@@ -396,11 +397,11 @@ export class AgentEvalRunService {
return [
{
- apiName: message.plugin?.apiName ?? null,
+ apiName: clampToolIdentifier(message.plugin?.apiName) ?? null,
arguments: message.plugin?.arguments ?? null,
error: message.pluginError ?? null,
id,
- identifier: message.plugin?.identifier ?? null,
+ identifier: clampToolIdentifier(message.plugin?.identifier) ?? null,
intervention: message.pluginIntervention as ToolIntervention | undefined,
state: message.pluginState ?? null,
toolCallId: message.tool_call_id ?? null,
diff --git a/packages/database/src/models/__tests__/messages/message.create.test.ts b/packages/database/src/models/__tests__/messages/message.create.test.ts
index eb72e385621..7f2cbd9dcb1 100644
--- a/packages/database/src/models/__tests__/messages/message.create.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.create.test.ts
@@ -2,6 +2,7 @@ import type { DBMessageItem } from '@lobechat/types';
import { asc, eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { MAX_TOOL_IDENTIFIER_LENGTH } from '@/utils/clampToolIdentifier';
import { uuid } from '@/utils/uuid';
import { getTestDB } from '../../../core/getTestDB';
@@ -190,6 +191,32 @@ describe('MessageModel Create Tests', () => {
expect(pluginResult[0].identifier).toBe('plugin1');
});
+ it('should clamp oversized plugin identifiers when creating a tool message', async () => {
+ const oversizedApiName = `api-${'a'.repeat(40_000)}`;
+ const oversizedIdentifier = `plugin-${'i'.repeat(40_000)}`;
+
+ const result = await messageModel.create({
+ content: 'tool result',
+ plugin: {
+ apiName: oversizedApiName,
+ arguments: '{}',
+ identifier: oversizedIdentifier,
+ type: 'default',
+ },
+ role: 'tool',
+ sessionId: '1',
+ tool_call_id: 'oversized-tool-call',
+ });
+
+ const [plugin] = await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, result.id));
+
+ expect(plugin.apiName).toBe(oversizedApiName.slice(0, MAX_TOOL_IDENTIFIER_LENGTH));
+ expect(plugin.identifier).toBe(oversizedIdentifier.slice(0, MAX_TOOL_IDENTIFIER_LENGTH));
+ });
+
it('should create tool message ', async () => {
// Call create method
const state = {
diff --git a/packages/database/src/models/__tests__/messages/message.update.test.ts b/packages/database/src/models/__tests__/messages/message.update.test.ts
index d91aa86ae65..64803d46cfb 100644
--- a/packages/database/src/models/__tests__/messages/message.update.test.ts
+++ b/packages/database/src/models/__tests__/messages/message.update.test.ts
@@ -1,6 +1,7 @@
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { MAX_TOOL_IDENTIFIER_LENGTH } from '@/utils/clampToolIdentifier';
import { uuid } from '@/utils/uuid';
import { getTestDB } from '../../../core/getTestDB';
@@ -591,6 +592,32 @@ describe('MessageModel Update Tests', () => {
expect(result[0].identifier).toEqual('plugin2');
});
+ it('should clamp oversized plugin identifiers on update', async () => {
+ const oversizedApiName = `api-${'a'.repeat(40_000)}`;
+ const oversizedIdentifier = `plugin-${'i'.repeat(40_000)}`;
+ await serverDB.insert(messages).values({ id: '1', content: 'abc', role: 'tool', userId });
+ await serverDB.insert(messagePlugins).values({
+ apiName: 'api1',
+ id: '1',
+ identifier: 'plugin1',
+ toolCallId: 'tool1',
+ userId,
+ });
+
+ await messageModel.updateMessagePlugin('1', {
+ apiName: oversizedApiName,
+ identifier: oversizedIdentifier,
+ });
+
+ const [plugin] = await serverDB
+ .select()
+ .from(messagePlugins)
+ .where(eq(messagePlugins.id, '1'));
+
+ expect(plugin.apiName).toBe(oversizedApiName.slice(0, MAX_TOOL_IDENTIFIER_LENGTH));
+ expect(plugin.identifier).toBe(oversizedIdentifier.slice(0, MAX_TOOL_IDENTIFIER_LENGTH));
+ });
+
it('should throw an error if plugin does not exist', async () => {
// Call updateMessagePlugin method (fix: previously incorrectly called updatePluginState)
await expect(
diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.ts
index 6e4740d8c73..57bddf77145 100644
--- a/packages/database/src/models/message.ts
+++ b/packages/database/src/models/message.ts
@@ -65,6 +65,7 @@ import {
sql,
} from 'drizzle-orm';
+import { clampToolIdentifier } from '@/utils/clampToolIdentifier';
import { merge } from '@/utils/merge';
import { sanitizeNullBytes } from '@/utils/sanitizeNullBytes';
import { today } from '@/utils/time';
@@ -3219,10 +3220,10 @@ export class MessageModel {
if (message.role === 'tool') {
await runTimedStage(timing, `${timingPrefix}.plugin.insert`, () =>
trx.insert(messagePlugins).values({
- apiName: plugin?.apiName,
+ apiName: clampToolIdentifier(plugin?.apiName),
arguments: sanitizeNullBytes(plugin?.arguments),
id,
- identifier: plugin?.identifier,
+ identifier: clampToolIdentifier(plugin?.identifier),
intervention: pluginIntervention,
state: sanitizeNullBytes(pluginState),
toolCallId: message.tool_call_id,
@@ -3581,7 +3582,11 @@ export class MessageModel {
return this.db
.update(messagePlugins)
- .set(value)
+ .set({
+ ...value,
+ apiName: clampToolIdentifier(value.apiName),
+ identifier: clampToolIdentifier(value.identifier),
+ })
.where(and(eq(messagePlugins.id, id), this.pluginsOwnership()));
};
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index 9fe90f4d8b5..17cd001f2a3 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -34,6 +34,8 @@ import {
sql,
} from 'drizzle-orm';
+import { clampToolIdentifier } from '@/utils/clampToolIdentifier';
+
import type { FtsSearchCandidateSource } from '../repositories/ftsSearch';
import type { TopicItem } from '../schemas';
import {
@@ -1540,8 +1542,10 @@ export class TopicModel {
await tx.insert(messagePlugins).values({
...plugin,
+ apiName: clampToolIdentifier(plugin.apiName),
clientId: null,
id: newId,
+ identifier: clampToolIdentifier(plugin.identifier),
toolCallId: newToolCallId,
});
}
diff --git a/packages/database/src/repositories/dataImporter/deprecated/index.ts b/packages/database/src/repositories/dataImporter/deprecated/index.ts
index e1b25b89cfb..8494b7fd86f 100644
--- a/packages/database/src/repositories/dataImporter/deprecated/index.ts
+++ b/packages/database/src/repositories/dataImporter/deprecated/index.ts
@@ -1,6 +1,7 @@
import type { ImporterEntryData } from '@lobechat/types';
import { and, inArray, sql } from 'drizzle-orm';
+import { clampToolIdentifier } from '@/utils/clampToolIdentifier';
import { sanitizeUTF8 } from '@/utils/sanitizeUTF8';
import {
@@ -306,10 +307,10 @@ export class DeprecatedDataImporterRepos {
if (pluginInserts.length > 0) {
await trx.insert(messagePlugins).values(
pluginInserts.map((msg) => ({
- apiName: msg.plugin?.apiName,
+ apiName: clampToolIdentifier(msg.plugin?.apiName),
arguments: msg.plugin?.arguments,
id: messageIdMap[msg.id],
- identifier: msg.plugin?.identifier,
+ identifier: clampToolIdentifier(msg.plugin?.identifier),
state: msg.pluginState,
toolCallId: msg.tool_call_id,
type: msg.plugin?.type,
diff --git a/packages/database/src/repositories/dataImporter/index.ts b/packages/database/src/repositories/dataImporter/index.ts
index 5b78aa66e40..57aa615847b 100644
--- a/packages/database/src/repositories/dataImporter/index.ts
+++ b/packages/database/src/repositories/dataImporter/index.ts
@@ -1,6 +1,7 @@
import type { ImporterEntryData, ImportPgDataStructure, ImportResultData } from '@lobechat/types';
import { and, eq, inArray } from 'drizzle-orm';
+import { clampToolIdentifier } from '@/utils/clampToolIdentifier';
import { uuid } from '@/utils/uuid';
import * as EXPORT_TABLES from '../../schemas';
@@ -177,6 +178,10 @@ const IMPORT_TABLE_CONFIG: TableImportConfig[] = [
},
{
conflictStrategy: 'skip',
+ fieldProcessors: {
+ apiName: (value) => clampToolIdentifier(value),
+ identifier: (value) => clampToolIdentifier(value),
+ },
preserveId: true, // Uses message ID as primary key
relations: [
{
diff --git a/packages/database/src/repositories/heteroSessionImporter/index.ts b/packages/database/src/repositories/heteroSessionImporter/index.ts
index 016661c1dbb..46534b68f0a 100644
--- a/packages/database/src/repositories/heteroSessionImporter/index.ts
+++ b/packages/database/src/repositories/heteroSessionImporter/index.ts
@@ -6,6 +6,8 @@ import type {
} from '@lobechat/types';
import { and, count, eq, inArray, isNotNull, like, or, sql } from 'drizzle-orm';
+import { clampToolIdentifier } from '@/utils/clampToolIdentifier';
+
import { agents, messagePlugins, messages, threads, topics } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { idGenerator } from '../../utils/idGenerator';
@@ -302,11 +304,11 @@ export class HeteroSessionImporterRepo {
const pluginRows = fresh
.filter((m) => m.plugin || m.toolCallId)
.map((m) => ({
- apiName: m.plugin?.apiName ?? null,
+ apiName: clampToolIdentifier(m.plugin?.apiName) ?? null,
arguments: m.plugin?.arguments ?? null,
clientId: m.clientId,
id: clientIdToDbId.get(m.clientId)!,
- identifier: m.plugin?.identifier ?? null,
+ identifier: clampToolIdentifier(m.plugin?.identifier) ?? null,
state: m.pluginState ?? null,
toolCallId: m.toolCallId ?? null,
type: m.plugin?.type ?? null,
diff --git a/packages/database/src/repositories/topicImporter/index.ts b/packages/database/src/repositories/topicImporter/index.ts
index 20104614a4c..10ca0a52564 100644
--- a/packages/database/src/repositories/topicImporter/index.ts
+++ b/packages/database/src/repositories/topicImporter/index.ts
@@ -1,5 +1,7 @@
import type { ExportedTopic, ImportedMessage } from '@lobechat/types';
+import { clampToolIdentifier } from '@/utils/clampToolIdentifier';
+
import { messagePlugins, messages, topics } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { idGenerator } from '../../utils/idGenerator';
@@ -216,11 +218,11 @@ export class TopicImporterRepo {
if (msg.plugin || msg.pluginState || msg.pluginError || msg.tool_call_id) {
const plugin = msg.plugin as Record<string, any> | undefined;
preparedPlugins.push({
- apiName: plugin?.apiName || null,
+ apiName: clampToolIdentifier(plugin?.apiName) || null,
arguments: plugin?.arguments || null,
error: msg.pluginError || null,
id: msg.newId,
- identifier: plugin?.identifier || null,
+ identifier: clampToolIdentifier(plugin?.identifier) || null,
state: msg.pluginState || null,
toolCallId: msg.tool_call_id || null,
type: plugin?.type || null,
diff --git a/packages/database/src/utils/copyMessagesInDatabase.ts b/packages/database/src/utils/copyMessagesInDatabase.ts
index 9cab292e640..31a1d73da93 100644
--- a/packages/database/src/utils/copyMessagesInDatabase.ts
+++ b/packages/database/src/utils/copyMessagesInDatabase.ts
@@ -2,6 +2,8 @@ import type { MessageMetadata } from '@lobechat/types';
import { getTableColumns, type SQL, sql } from 'drizzle-orm';
import type { PgColumn, PgTable } from 'drizzle-orm/pg-core';
+import { MAX_TOOL_IDENTIFIER_LENGTH } from '@/utils/clampToolIdentifier';
+
import {
messageChunks,
messageGroups,
@@ -272,7 +274,9 @@ export const copyMessagesInDatabase = async ({
};
await copyChildRows(messagePlugins, messagePlugins.id, {
+ apiName: sql`left(${messagePlugins.apiName}, ${MAX_TOOL_IDENTIFIER_LENGTH})`,
id: newMessageId,
+ identifier: sql`left(${messagePlugins.identifier}, ${MAX_TOOL_IDENTIFIER_LENGTH})`,
toolCallId: sql`case
when ${messagePlugins.toolCallId} is null then null
else ${remappedToolId(newMessageId, sql`${messagePlugins.toolCallId}`)}
diff --git a/packages/utils/src/clampToolIdentifier.test.ts b/packages/utils/src/clampToolIdentifier.test.ts
new file mode 100644
index 00000000000..8580abb4887
--- /dev/null
+++ b/packages/utils/src/clampToolIdentifier.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+
+import { clampToolIdentifier, MAX_TOOL_IDENTIFIER_LENGTH } from './clampToolIdentifier';
+
+describe('clampToolIdentifier', () => {
+ it('passes through short values untouched', () => {
+ expect(clampToolIdentifier('lobe-agent')).toBe('lobe-agent');
+ expect(clampToolIdentifier('')).toBe('');
+ });
+
+ it('passes through null and undefined', () => {
+ expect(clampToolIdentifier(null)).toBeNull();
+ expect(clampToolIdentifier(undefined)).toBeUndefined();
+ });
+
+ it('keeps a value exactly at the limit', () => {
+ const value = 'a'.repeat(MAX_TOOL_IDENTIFIER_LENGTH);
+ expect(clampToolIdentifier(value)).toBe(value);
+ });
+
+ it('truncates oversized values to the limit', () => {
+ const value = 'x'.repeat(40_000);
+ expect(clampToolIdentifier(value)).toHaveLength(MAX_TOOL_IDENTIFIER_LENGTH);
+ });
+});
diff --git a/packages/utils/src/clampToolIdentifier.ts b/packages/utils/src/clampToolIdentifier.ts
new file mode 100644
index 00000000000..d5ed75f1447
--- /dev/null
+++ b/packages/utils/src/clampToolIdentifier.ts
@@ -0,0 +1,13 @@
+/**
+ * Hard cap for `message_plugins.identifier` / `api_name`. Hallucinated tool
+ * calls have stuffed multi-KB payloads (artifact XML, shell commands) into
+ * these columns; once the columns are btree-indexed, any value past the index
+ * tuple size limit makes the whole row insert fail, so every write path must
+ * clamp before hitting the database.
+ */
+export const MAX_TOOL_IDENTIFIER_LENGTH = 255;
+
+export const clampToolIdentifier = <T extends string | null | undefined>(value: T): T =>
+ value && value.length > MAX_TOOL_IDENTIFIER_LENGTH
+ ? (value.slice(0, MAX_TOOL_IDENTIFIER_LENGTH) as T)
+ : value;