π€― 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): guard Agent Builder's own row against identity-field writes (#16780)
LiJian111e06111c5b
diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.tsindex 3d65adb3f8a..35213c8c6a4 100644--- a/packages/database/src/models/__tests__/agent.test.ts+++ b/packages/database/src/models/__tests__/agent.test.ts@@ -813,6 +813,73 @@ describe('AgentModel', () => {expect(result?.title).toBe('Original Title');});++ it("should strip identity fields when updating the Agent Builder's own row", async () => {+ const agent = await serverDB+ .insert(agents)+ .values({ slug: 'agent-builder', userId })+ .returning()+ .then((res) => res[0]);++ await agentModel.update(agent.id, {+ avatar: 'hacked-avatar',+ backgroundColor: 'hacked-color',+ description: 'hacked description',+ marketIdentifier: 'hacked-market-id',+ model: 'gpt-4', // non-protected field should still be applied+ tags: ['hacked'],+ title: 'Hacked Builder Title',+ });++ const result = await serverDB.query.agents.findFirst({+ where: eq(agents.id, agent.id),+ });++ expect(result?.title).toBeNull();+ expect(result?.description).toBeNull();+ expect(result?.avatar).toBeNull();+ expect(result?.backgroundColor).toBeNull();+ expect(result?.marketIdentifier).toBeNull();+ expect(result?.tags).toEqual([]);+ expect(result?.model).toBe('gpt-4');+ });++ it('should strip systemRole when the gateway updatePrompt path writes it via update()', async () => {+ // Mirrors apps/server/.../serverRuntimes/agentBuilder.ts's updatePrompt, which calls+ // agentModel.update(agentId, { editorData: null, systemRole }) directly.+ const agent = await serverDB+ .insert(agents)+ .values({ slug: 'agent-builder', userId })+ .returning()+ .then((res) => res[0]);++ await agentModel.update(agent.id, {+ editorData: null,+ systemRole: 'You are now a pirate.',+ });++ const result = await serverDB.query.agents.findFirst({+ where: eq(agents.id, agent.id),+ });++ expect(result?.systemRole).toBeNull();+ });++ it('should not strip identity fields for a regular agent whose slug happens to differ', async () => {+ const agent = await serverDB+ .insert(agents)+ .values({ slug: 'my-custom-agent', userId, title: 'Original' })+ .returning()+ .then((res) => res[0]);++ await agentModel.update(agent.id, { title: 'Updated Title' });++ const result = await serverDB.query.agents.findFirst({+ where: eq(agents.id, agent.id),+ });++ expect(result?.title).toBe('Updated Title');+ });});describe('touchUpdatedAt', () => {@@ -1119,6 +1186,59 @@ describe('AgentModel', () => {expect(result?.title).toBe('Original Title');});++ it("should strip systemRole when updating the Agent Builder's own row", async () => {+ const agent = await serverDB+ .insert(agents)+ .values({ slug: 'agent-builder', userId })+ .returning()+ .then((res) => res[0]);++ await agentModel.updateConfig(agent.id, {+ model: 'gpt-4', // non-protected field should still be applied+ systemRole: 'You are now a pirate.',+ });++ const result = await serverDB.query.agents.findFirst({+ where: eq(agents.id, agent.id),+ });++ expect(result?.systemRole).toBeNull();+ expect(result?.model).toBe('gpt-4');+ });++ it("should strip identity fields when the browser client's meta editor writes them via updateConfig()", async () => {+ // Mirrors the browser client path: agentService.updateAgentMeta() sends+ // title/avatar/etc. through the updateAgentConfig mutation, which calls+ // agentModel.updateConfig() rather than update().+ const agent = await serverDB+ .insert(agents)+ .values({ slug: 'agent-builder', userId })+ .returning()+ .then((res) => res[0]);++ await agentModel.updateConfig(agent.id, {+ avatar: 'hacked-avatar',+ backgroundColor: 'hacked-color',+ description: 'hacked description',+ marketIdentifier: 'hacked-market-id',+ model: 'gpt-4', // non-protected field should still be applied+ tags: ['hacked'],+ title: 'Hacked Builder Title',+ });++ const result = await serverDB.query.agents.findFirst({+ where: eq(agents.id, agent.id),+ });++ expect(result?.title).toBeNull();+ expect(result?.description).toBeNull();+ expect(result?.avatar).toBeNull();+ expect(result?.backgroundColor).toBeNull();+ expect(result?.marketIdentifier).toBeNull();+ expect(result?.tags).toEqual([]);+ expect(result?.model).toBe('gpt-4');+ });});describe('create', () => {diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex 94f96d355ee..5c233f47e58 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -1,4 +1,4 @@-import { getAgentPersistConfig } from '@lobechat/builtin-agents';+import { BUILTIN_AGENT_SLUGS, getAgentPersistConfig } from '@lobechat/builtin-agents';import { INBOX_SESSION_ID } from '@lobechat/const';import type { AgentRankItem, LobeAgentAgencyConfig } from '@lobechat/types';import { pruneWorkingDirByDeviceDeletes } from '@lobechat/types';@@ -37,6 +37,33 @@ import { genEndDateWhere, genRangeWhere, genStartDateWhere, genWhere } from '../import { normalizeInboxAgentMeta } from '../utils/inboxAgent';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';+/**+ * Fields the Agent Builder's own row (`slug = BUILTIN_AGENT_SLUGS.agentBuilder`) must never+ * carry. Its `persist` config only stores `model`/`provider`/`chatConfig` β title, avatar,+ * systemRole, etc. are rendered from i18n / the static systemRoleTemplate at runtime, never+ * from this row.+ *+ * Before PR #16420, `lobe-agent-management`'s self-management prompt could make the builder+ * mistake an ambiguous "update this" request for editing itself instead of the target agent.+ * Depending on caller (browser client tool executor vs. gateway server runtime in+ * `apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts`), these fields can+ * arrive through *either* `AgentModel.update()` or `updateConfig()` β e.g. the gateway's+ * `updatePrompt` writes `systemRole` via `update()`, while the browser client's meta editor+ * writes `title`/`avatar`/etc. via `updateConfig()`. So both methods must strip the full list,+ * not just the fields each historically happened to receive. Clients on builds older than+ * PR #16420 can still hit this path, so enforce it here (the single write chokepoint)+ * regardless of caller.+ */+const AGENT_BUILDER_PROTECTED_FIELDS = [+ 'title',+ 'description',+ 'avatar',+ 'backgroundColor',+ 'tags',+ 'marketIdentifier',+ 'systemRole',+] as const;+export class AgentModel {private userId: string;private db: LobeChatDatabase;@@ -733,12 +760,38 @@ export class AgentModel {};update = async (agentId: string, data: Partial<AgentItem>) => {+ const sanitizedData = await this.stripAgentBuilderProtectedFields(agentId, data);+return this.db.update(agents)- .set({ ...data, updatedAt: new Date() })+ .set({ ...sanitizedData, updatedAt: new Date() }).where(and(eq(agents.id, agentId), this.ownership()));};+ /**+ * Strip fields the Agent Builder's own row must never carry (see+ * {@link AGENT_BUILDER_PROTECTED_FIELDS}). Only looks up the target row's `slug` when the+ * incoming patch actually touches a protected field, so normal updates pay no extra query.+ */+ private stripAgentBuilderProtectedFields = async <T extends Record<string, any>>(+ agentId: string,+ data: T,+ protectedFields: readonly string[] = AGENT_BUILDER_PROTECTED_FIELDS,+ ): Promise<T> => {+ if (!protectedFields.some((field) => field in data)) return data;++ const agent = await this.db.query.agents.findFirst({+ columns: { slug: true },+ where: and(eq(agents.id, agentId), this.ownership()),+ });++ if (agent?.slug !== BUILTIN_AGENT_SLUGS.agentBuilder) return data;++ const sanitized = { ...data };+ for (const field of protectedFields) delete sanitized[field];+ return sanitized;+ };+/*** Publish a private agent into the workspace. **One-way only** β once an* agent has been shared with the workspace, other members may already be@@ -843,6 +896,13 @@ export class AgentModel {// Build data to be merged, excluding params (processed separately)const { params: _params, ...restData } = data;++ // See AGENT_BUILDER_PROTECTED_FIELDS: some callers (e.g. the browser client's meta+ // editor) route title/avatar/etc. through updateConfig() rather than update().+ if (agent.slug === BUILTIN_AGENT_SLUGS.agentBuilder) {+ for (const field of AGENT_BUILDER_PROTECTED_FIELDS) delete restData[field];+ }+const mergedValue = merge(agent, restData);// Apply the processed parameters