🤯 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
✨ feat(openapi): send to group chats on the IM channel and expose agentId on messages (#21281)
Inneibadab8bc41e1
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex b059ae1e77f..2a158dbbc93 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -530,8 +530,18 @@ export class AiAgentService {* 1. Create topic with groupId (if needed)* 2. Delegate to execAgent for the rest*/- async execGroupAgent(params: ExecGroupAgentParams): Promise<ExecGroupAgentResult> {- const { agentId, groupId, message, topicId: inputTopicId, newTopic } = params;+ async execGroupAgent(+ params: ExecGroupAgentParams & Pick<InternalExecAgentParams, 'clientIds' | 'interactiveStart'>,+ ): Promise<ExecGroupAgentResult> {+ const {+ agentId,+ clientIds,+ groupId,+ interactiveStart,+ message,+ topicId: inputTopicId,+ newTopic,+ } = params;log('execGroupAgent: agentId=%s, groupId=%s, message=%s',@@ -567,6 +577,8 @@ export class AiAgentService {agentId,appContext: { groupId, orchestrationRole: 'supervisor', topicId },autoStart: true,+ clientIds,+ interactiveStart,prompt: message,trigger: RequestTrigger.Chat,});diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.ymlindex 8697aa6fdfc..9bff1fcdd24 100644--- a/packages/openapi/openapi.yml+++ b/packages/openapi/openapi.yml@@ -13510,6 +13510,10 @@ paths:userMessage:additionalProperties: falseproperties:+ agentId:+ type:+ - string+ - "null"content:type: stringcreatedAt:@@ -13525,6 +13529,7 @@ paths:- usertype: stringrequired:+ - agentId- content- createdAt- error@@ -13610,26 +13615,53 @@ paths:content:application/json:schema:- type: object- properties:- agentId:- type: string- minLength: 1- clientMessageId:- type: string- pattern: ^msg_[\w-]{8,64}$- content:- type: string- minLength: 1- maxLength: 100000- topicId:- anyOf:- - type: string+ anyOf:+ - type: object+ properties:+ agentId:+ type: stringminLength: 1- - type: "null"- required:- - agentId- - content+ clientMessageId:+ type: string+ pattern: ^msg_[\w-]{8,64}$+ content:+ type: string+ minLength: 1+ maxLength: 100000+ groupId:+ type: string+ minLength: 1+ topicId:+ anyOf:+ - type: string+ minLength: 1+ - type: "null"+ required:+ - agentId+ - content+ - type: object+ properties:+ agentId:+ type: string+ minLength: 1+ clientMessageId:+ type: string+ pattern: ^msg_[\w-]{8,64}$+ content:+ type: string+ minLength: 1+ maxLength: 100000+ groupId:+ type: string+ minLength: 1+ topicId:+ anyOf:+ - type: string+ minLength: 1+ - type: "null"+ required:+ - content+ - groupId/api/v1/im/topics/{topicId}/sync:get:operationId: syncImTopic@@ -13652,6 +13684,10 @@ paths:items:additionalProperties: falseproperties:+ agentId:+ type:+ - string+ - "null"content:type: stringcreatedAt:@@ -13667,6 +13703,7 @@ paths:- usertype: stringrequired:+ - agentId- content- createdAt- errordiff --git a/packages/openapi/src/services/__tests__/im.service.test.ts b/packages/openapi/src/services/__tests__/im.service.test.tsindex b8818646e0c..c4256188ee1 100644--- a/packages/openapi/src/services/__tests__/im.service.test.ts+++ b/packages/openapi/src/services/__tests__/im.service.test.ts@@ -5,6 +5,9 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { getTestDB } from '@/database/core/getTestDB';import {agentOperations,+ agents,+ chatGroups,+ chatGroupsAgents,messages,pushLiveActivities,pushTokens,@@ -13,13 +16,18 @@ import {workspaces,} from '@/database/schemas';+import { ImSendRequestSchema } from '../../types/im.type';import { ImRestService } from '../im.service';-const { execAgentMock } = vi.hoisted(() => ({ execAgentMock: vi.fn() }));+const { execAgentMock, execGroupAgentMock } = vi.hoisted(() => ({+ execAgentMock: vi.fn(),+ execGroupAgentMock: vi.fn(),+}));vi.mock('@/server/services/aiAgent', () => ({AiAgentService: class {execAgent = execAgentMock;+ execGroupAgent = execGroupAgentMock;},}));@@ -28,6 +36,10 @@ const USER = 'im-user';const OTHER = 'im-other';const TOPIC = 'tpc_im';const AGENT = 'agt_im';+const GROUP = 'grp_im';+const SUPERVISOR = 'agt_im_supervisor';+const MEMBER = 'agt_im_member';+const GROUP_TOPIC = 'tpc_im_group';const service = new ImRestService(db, USER);@@ -63,13 +75,37 @@ const insertRun = (id: string, status: string, createdAt: string) =>userId: USER,});+const insertGroup = async ({ supervisor = true }: { supervisor?: boolean } = {}) => {+ await db.insert(agents).values([+ { id: SUPERVISOR, userId: USER, virtual: true },+ { id: MEMBER, userId: USER },+ { id: AGENT, userId: USER },+ ]);+ await db.insert(chatGroups).values({ id: GROUP, title: 'crew', userId: USER });+ await db+ .insert(chatGroupsAgents)+ .values([+ ...(supervisor+ ? [{ agentId: SUPERVISOR, chatGroupId: GROUP, role: 'supervisor', userId: USER }]+ : []),+ { agentId: MEMBER, chatGroupId: GROUP, role: 'participant', userId: USER },+ ]);+ await db+ .insert(topics)+ .values({ groupId: GROUP, id: GROUP_TOPIC, title: 'crew chat', userId: USER });+};+beforeEach(async () => {execAgentMock.mockReset();+ execGroupAgentMock.mockReset();await db.delete(pushLiveActivities);await db.delete(pushTokens);await db.delete(agentOperations);await db.delete(messages);await db.delete(topics);+ await db.delete(chatGroupsAgents);+ await db.delete(chatGroups);+ await db.delete(agents);await db.delete(workspaces);await db.delete(users);await db.insert(users).values([{ id: USER }, { id: OTHER }]);@@ -272,6 +308,62 @@ describe('ImRestService.sync — whole-message delivery', () => {expect(again.state).toBe(during.state);});+ it('carries the writing agent on each message and withholds the whole group turn', async () => {+ await insertGroup();+ const inGroup = { groupId: GROUP, topicId: GROUP_TOPIC };+ await insertMessage('msg_u1', 'user', 'plan the trip', '2026-10-04T10:00:00.000100Z', {+ ...inGroup,+ agentId: SUPERVISOR,+ });+ await insertMessage('msg_sup', 'assistant', 'asking the crew', '2026-10-04T10:00:00.000300Z', {+ ...inGroup,+ agentId: SUPERVISOR,+ });+ await insertMessage('msg_mem', 'assistant', 'flights are boo', '2026-10-04T10:00:00.000400Z', {+ ...inGroup,+ agentId: MEMBER,+ });+ // The supervisor parks on the member call; the member runs as its child.+ await db.insert(agentOperations).values([+ {+ createdAt: atUs('2026-10-04T10:00:00.000200Z') as unknown as Date,+ id: 'op_sup',+ status: 'waiting_for_async_tool',+ topicId: GROUP_TOPIC,+ userId: USER,+ },+ {+ createdAt: atUs('2026-10-04T10:00:00.000350Z') as unknown as Date,+ id: 'op_mem',+ parentOperationId: 'op_sup',+ status: 'running',+ topicId: GROUP_TOPIC,+ userId: USER,+ },+ ]);++ const working = await service.sync(GROUP_TOPIC, {});+ expect(working.typing).toBe(true);+ expect(working.readUpTo?.messageId).toBe('msg_u1');+ expect(working.messages).toEqual([+ expect.objectContaining({ agentId: null, id: 'msg_u1', role: 'user' }),+ ]);++ await db+ .update(messages)+ .set({ content: 'flights are booked' })+ .where(eq(messages.id, 'msg_mem'));+ await db.update(agentOperations).set({ status: 'done' });++ const landed = await service.sync(GROUP_TOPIC, { cursor: working.cursor });+ expect(landed.typing).toBe(false);+ expect(landed.messages.map((m) => [m.id, m.agentId, m.content])).toEqual([+ ['msg_sup', SUPERVISOR, 'asking the crew'],+ ['msg_mem', MEMBER, 'flights are booked'],+ ]);+ expect(landed.unread).toBe(2);+ });+it('refuses another user’s conversation', async () => {await expect(new ImRestService(db, OTHER).sync(TOPIC, {})).rejects.toMatchObject({name: 'NotFoundError',@@ -428,12 +520,139 @@ describe('ImRestService.send', () => {trigger: 'chat',}),);+ expect(execGroupAgentMock).not.toHaveBeenCalled();expect(result).toMatchObject({accepted: true,operationId: 'op_1',topicId: TOPIC,- userMessage: { content: 'hello', id: 'msg_client0001', role: 'user' },+ userMessage: { agentId: null, content: 'hello', id: 'msg_client0001', role: 'user' },+ });+ });++ it('requires an agentId or a groupId', () => {+ expect(ImSendRequestSchema.safeParse({ content: 'hi' }).success).toBe(false);+ expect(ImSendRequestSchema.safeParse({ agentId: AGENT, content: 'hi' }).success).toBe(true);+ expect(ImSendRequestSchema.safeParse({ content: 'hi', groupId: GROUP }).success).toBe(true);+ });++ it('runs a group send through the group supervisor in a new group topic', async () => {+ await insertGroup();+ execGroupAgentMock.mockImplementation(async () => {+ await insertMessage('msg_client0003', 'user', 'plan it', '2026-10-04T10:00:01Z', {+ agentId: SUPERVISOR,+ groupId: GROUP,+ topicId: GROUP_TOPIC,+ });+ return {+ isCreateNewTopic: true,+ operationId: 'op_group',+ success: true,+ topicId: GROUP_TOPIC,+ userMessageId: 'msg_client0003',+ };+ });++ const result = await service.send({+ clientMessageId: 'msg_client0003',+ content: 'plan it',+ groupId: GROUP,+ });++ expect(execAgentMock).not.toHaveBeenCalled();+ expect(execGroupAgentMock).toHaveBeenCalledWith({+ agentId: SUPERVISOR,+ clientIds: { userMessageId: 'msg_client0003' },+ groupId: GROUP,+ interactiveStart: true,+ message: 'plan it',+ topicId: undefined,+ });+ expect(result).toEqual({+ accepted: true,+ operationId: 'op_group',+ topicId: GROUP_TOPIC,+ userMessage: expect.objectContaining({ agentId: null, id: 'msg_client0003', role: 'user' }),});++ // A retry of the same group send is answered from the stored turn.+ await insertMessage('msg_client0003_reply', 'assistant', '...', '2026-10-04T10:00:01.5Z', {+ agentId: SUPERVISOR,+ topicId: GROUP_TOPIC,+ });+ const retry = await service.send({+ clientMessageId: 'msg_client0003',+ content: 'plan it',+ groupId: GROUP,+ });+ expect(retry).toMatchObject({ accepted: false, operationId: null, topicId: GROUP_TOPIC });+ expect(execGroupAgentMock).toHaveBeenCalledTimes(1);+ });++ it('accepts a member agentId with the group and still runs the supervisor', async () => {+ await insertGroup();+ execGroupAgentMock.mockImplementation(async () => {+ await insertMessage('msg_client0004', 'user', 'hey crew', '2026-10-04T10:00:01Z', {+ topicId: GROUP_TOPIC,+ });+ return {+ operationId: 'op_g',+ success: true,+ topicId: GROUP_TOPIC,+ userMessageId: 'msg_client0004',+ };+ });++ await service.send({+ agentId: MEMBER,+ clientMessageId: 'msg_client0004',+ content: 'hey crew',+ groupId: GROUP,+ topicId: GROUP_TOPIC,+ });++ expect(execGroupAgentMock).toHaveBeenCalledWith(+ expect.objectContaining({ agentId: SUPERVISOR, groupId: GROUP, topicId: GROUP_TOPIC }),+ );+ });++ it('refuses an agentId that is not a member of the group', async () => {+ await insertGroup();++ await expect(+ service.send({ agentId: AGENT, content: 'hi', groupId: GROUP }),+ ).rejects.toMatchObject({+ message: 'agentId is not a member of this group',+ name: 'ConflictError',+ });+ expect(execGroupAgentMock).not.toHaveBeenCalled();+ expect(execAgentMock).not.toHaveBeenCalled();+ });++ it('refuses a group with no supervisor instead of picking a member', async () => {+ await insertGroup({ supervisor: false });++ await expect(service.send({ content: 'hi', groupId: GROUP })).rejects.toMatchObject({+ name: 'ConflictError',+ });+ expect(execGroupAgentMock).not.toHaveBeenCalled();+ });++ it('refuses a conversation that belongs to another group or to a 1:1 chat', async () => {+ await insertGroup();++ await expect(+ service.send({ content: 'hi', groupId: GROUP, topicId: TOPIC }),+ ).rejects.toMatchObject({ name: 'ConflictError' });+ expect(execGroupAgentMock).not.toHaveBeenCalled();+ });++ it('refuses a group the caller cannot see', async () => {+ await insertGroup();++ await expect(+ new ImRestService(db, OTHER).send({ content: 'hi', groupId: GROUP }),+ ).rejects.toMatchObject({ name: 'NotFoundError' });+ expect(execGroupAgentMock).not.toHaveBeenCalled();});it('is idempotent on clientMessageId: a retry does not start a second run', async () => {diff --git a/packages/openapi/src/services/im.service.ts b/packages/openapi/src/services/im.service.tsindex 335d8ea054d..b133927ac49 100644--- a/packages/openapi/src/services/im.service.ts+++ b/packages/openapi/src/services/im.service.ts@@ -1,8 +1,9 @@-import type { ChatTopicMetadata } from '@lobechat/types';+import type { ChatTopicMetadata, ExecGroupAgentResult } from '@lobechat/types';import { RequestTrigger } from '@lobechat/types';import { and, asc, desc, eq, inArray, isNull, lte, type SQL, sql } from 'drizzle-orm';import type { AnyPgColumn } from 'drizzle-orm/pg-core';+import { ChatGroupModel } from '@/database/models/chatGroup';import { PushLiveActivityModel, PushTokenModel } from '@/database/models/pushToken';import { TopicModel } from '@/database/models/topic';import { agentOperations, messages, pushTokens, topics } from '@/database/schemas';@@ -47,6 +48,7 @@ const TYPING_STATUSES = new Set([]);type MessageRow = {+ agentId: string | null;content: string | null;createdAt: Date;/** Exact `created_at` in epoch microseconds; a JS Date drops the last three digits. */@@ -107,6 +109,7 @@ const asCursor = ({ createdAtUs, messageId }: ReadCursor): ParsedCursor => ({const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));const toImMessage = (row: Omit<MessageRow, 'createdAtUs'>): ImMessage => ({+ agentId: row.role === 'user' ? null : row.agentId,content: row.content ?? '',createdAt: row.createdAt.toISOString(),error: row.error !== null && row.error !== undefined,@@ -161,14 +164,24 @@ export class ImRestService extends BaseService {throw this.createAuthorizationError(permission.message || 'No permission to send messages');}+ const supervisorId = input.groupId+ ? await this.resolveGroupSupervisor(input.groupId, input.agentId)+ : undefined;+await assertCanUseWorkspaceAgent({- agentId: input.agentId,+ agentId: supervisorId ?? input.agentId,db: this.db,+ groupId: input.groupId,userId: this.userId,workspaceId: this.workspaceId,});- if (input.topicId) await this.requireTopic(input.topicId);+ if (input.topicId) {+ const topic = await this.requireTopic(input.topicId);+ if (input.groupId && topic.groupId !== input.groupId) {+ throw this.createConflictError('The conversation does not belong to this group');+ }+ }// Idempotent retry: the client minted this id and already got through once.const receipt = await this.idempotentReceipt(input.clientMessageId);@@ -178,16 +191,28 @@ export class ImRestService extends BaseService {workspaceId: this.workspaceId,});- let result: Awaited<ReturnType<typeof aiAgentService.execAgent>>;+ const clientIds = input.clientMessageId ? { userMessageId: input.clientMessageId } : undefined;++ let result: Awaited<ReturnType<typeof aiAgentService.execAgent>> | ExecGroupAgentResult;try {- result = await aiAgentService.execAgent({- agentId: input.agentId,- appContext: input.topicId ? { topicId: input.topicId } : undefined,- clientIds: input.clientMessageId ? { userMessageId: input.clientMessageId } : undefined,- interactiveStart: true,- prompt: input.content,- trigger: RequestTrigger.Chat,- });+ result =+ supervisorId && input.groupId+ ? await aiAgentService.execGroupAgent({+ agentId: supervisorId,+ clientIds,+ groupId: input.groupId,+ interactiveStart: true,+ message: input.content,+ topicId: input.topicId,+ })+ : await aiAgentService.execAgent({+ agentId: input.agentId,+ appContext: input.topicId ? { topicId: input.topicId } : undefined,+ clientIds,+ interactiveStart: true,+ prompt: input.content,+ trigger: RequestTrigger.Chat,+ });} catch (error) {// Two concurrent first sends can both miss the pre-check above; the loser// then collides with the winner on the message primary key. Report the@@ -316,6 +341,25 @@ export class ImRestService extends BaseService {// ------------------------------------------------------------------ internals+ private async resolveGroupSupervisor(groupId: string, agentId?: string): Promise<string> {+ const groupModel = new ChatGroupModel(this.db, this.userId, this.workspaceId);+ if (!(await groupModel.findById(groupId))) throw this.createNotFoundError('Group not found');++ if (agentId) {+ const members = await groupModel.getGroupAgents(groupId);+ if (!members.some((member) => member.agentId === agentId)) {+ throw this.createConflictError('agentId is not a member of this group');+ }+ }++ const supervisorId = await groupModel.getSupervisorAgentId(groupId);+ // Deliberately no fallback to a member: only a supervisor orchestrates a group turn.+ if (!supervisorId) {+ throw this.createConflictError('This group has no supervisor agent to answer messages');+ }+ return supervisorId;+ }+/*** The receipt for a `clientMessageId` this user already got through, or* `undefined` when the id is unused — or was consumed by a send that never got@@ -437,6 +481,7 @@ export class ImRestService extends BaseService {}private readonly rowSelect = {+ agentId: messages.agentId,content: messages.content,createdAt: messages.createdAt,createdAtUs: epochUs(messages.createdAt),diff --git a/packages/openapi/src/spec.ts b/packages/openapi/src/spec.tsindex 812bc6704a9..9ecad3dc5d1 100644--- a/packages/openapi/src/spec.ts+++ b/packages/openapi/src/spec.ts@@ -479,13 +479,14 @@ const ref = (schema: string): SchemaObject => ({ $ref: `#/components/schemas/${sconst imMessageSchema: SchemaObject = {additionalProperties: false,properties: {+ agentId: nullableString,content: { type: 'string' },createdAt: dateTime,error: { type: 'boolean' },id: { type: 'string' },role: { enum: ['assistant', 'user'], type: 'string' },},- required: ['content', 'createdAt', 'error', 'id', 'role'],+ required: ['agentId', 'content', 'createdAt', 'error', 'id', 'role'],type: 'object',};diff --git a/packages/openapi/src/types/im.type.ts b/packages/openapi/src/types/im.type.tsindex a918160b696..37cb232a049 100644--- a/packages/openapi/src/types/im.type.ts+++ b/packages/openapi/src/types/im.type.ts@@ -11,9 +11,12 @@ import { z } from 'zod';* read the user's messages.*/-export const ImSendRequestSchema = z.object({- /** The agent the user is talking to. */- agentId: z.string().min(1),+const ImSendFieldsSchema = z.object({+ /**+ * The agent the user is talking to. With `groupId` it must be a member of+ * that group; the group's supervisor still runs the turn.+ */+ agentId: z.string().min(1).optional(),/*** Client-minted id for the user message (`msg_…`). Makes the send idempotent:* retrying with the same id returns the original receipt instead of starting@@ -25,9 +28,17 @@ export const ImSendRequestSchema = z.object({.optional(),/** The message text. */content: z.string().trim().min(1).max(100_000),- /** The conversation to continue; omit to start a new one for the agent. */+ /** The group chat the user is talking to; its supervisor orchestrates the members. */+ groupId: z.string().min(1).optional(),+ /** The conversation to continue; omit to start a new one for the agent or group. */topicId: z.string().min(1).nullish(),});++// A union rather than .refine() so the generated spec and SDK require a target too.+export const ImSendRequestSchema = z.union([+ ImSendFieldsSchema.extend({ agentId: z.string().min(1) }),+ ImSendFieldsSchema.extend({ groupId: z.string().min(1) }),+]);export type ImSendRequest = z.infer<typeof ImSendRequestSchema>;export const ImTopicParamSchema = z.object({@@ -68,6 +79,8 @@ export const ImReadRequestSchema = z.object({export type ImReadRequest = z.infer<typeof ImReadRequestSchema>;export interface ImMessage {+ /** The agent that wrote the message; null on user messages. */+ agentId: string | null;content: string;createdAt: string;/** Set when the agent's turn failed; the client shows a retry affordance. */diff --git a/packages/sdk/src/generated/types.gen.ts b/packages/sdk/src/generated/types.gen.tsindex a052283647b..8b69ef7f76a 100644--- a/packages/sdk/src/generated/types.gen.ts+++ b/packages/sdk/src/generated/types.gen.ts@@ -6330,6 +6330,13 @@ export type PostApiV1ImMessagesData = {agentId: string;clientMessageId?: string;content: string;+ groupId?: string;+ topicId?: string | null;+ } | {+ agentId?: string;+ clientMessageId?: string;+ content: string;+ groupId: string;topicId?: string | null;};path?: never;@@ -6384,6 +6391,7 @@ export type PostApiV1ImMessagesResponses = {operationId: string | null;topicId: string;userMessage: {+ agentId: string | null;content: string;createdAt: string;error: boolean;@@ -6458,6 +6466,7 @@ export type GetApiV1ImTopicsByTopicIdSyncResponses = {data?: {cursor: string;messages: Array<{+ agentId: string | null;content: string;createdAt: string;error: boolean;