🤯 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(brief): add ignore action next to retry on error briefs (#14742)
Arvin Xuef8aa72af593
diff --git a/apps/cli/src/commands/agent.ts b/apps/cli/src/commands/agent.tsindex 1902d1b72f0..0c56d63bff8 100644--- a/apps/cli/src/commands/agent.ts+++ b/apps/cli/src/commands/agent.ts@@ -318,7 +318,7 @@ export function registerAgentCommand(program: Command) {}// 1. Exec agent to get operationId- const input: Record<string, any> = { prompt: options.prompt };+ const input: Record<string, any> = { prompt: options.prompt, trigger: 'cli' };if (options.agentId) input.agentId = options.agentId;if (deviceId) input.deviceId = deviceId;if (options.slug) input.slug = options.slug;diff --git a/locales/en-US/home.json b/locales/en-US/home.jsonindex 522891768fa..7228265d9fd 100644--- a/locales/en-US/home.json+++ b/locales/en-US/home.json@@ -8,6 +8,7 @@"brief.action.confirm": "Confirm","brief.action.confirmDone": "Confirm complete","brief.action.feedback": "Feedback",+ "brief.action.ignore": "Ignore","brief.action.retry": "Retry","brief.addFeedback": "Share feedback","brief.collapse": "Show less",diff --git a/locales/zh-CN/home.json b/locales/zh-CN/home.jsonindex 3b6d16e2ac6..b889e198c87 100644--- a/locales/zh-CN/home.json+++ b/locales/zh-CN/home.json@@ -8,6 +8,7 @@"brief.action.confirm": "已阅","brief.action.confirmDone": "确认完成","brief.action.feedback": "反馈",+ "brief.action.ignore": "忽略","brief.action.retry": "重试","brief.addFeedback": "分享反馈","brief.collapse": "收起",diff --git a/packages/openapi/src/services/responses.service.ts b/packages/openapi/src/services/responses.service.tsindex 0913356108a..5cee9cce26c 100644--- a/packages/openapi/src/services/responses.service.ts+++ b/packages/openapi/src/services/responses.service.ts@@ -301,6 +301,7 @@ export class ResponsesService extends BaseService {instructions,prompt,stream: false,+ trigger: 'openapi',});if (!execResult.success) {@@ -399,6 +400,7 @@ export class ResponsesService extends BaseService {instructions,prompt,stream: true,+ trigger: 'openapi',});if (!execResult.success) {diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.tsindex b97742fbd3d..37c730883a0 100644--- a/packages/types/src/agentRuntime.ts+++ b/packages/types/src/agentRuntime.ts@@ -3,11 +3,14 @@ export enum RequestTrigger {Api = 'api',Bot = 'bot',Chat = 'chat',+ Cli = 'cli',Cron = 'cron',Eval = 'eval',FileEmbedding = 'file_embedding',Image = 'image',Memory = 'memory',+ Notify = 'notify',+ Openapi = 'openapi',SemanticSearch = 'semantic_search',Topic = 'topic',Video = 'video',diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsxindex 30fdc83133a..d031ae05c14 100644--- a/src/features/Conversation/Error/index.test.tsx+++ b/src/features/Conversation/Error/index.test.tsx@@ -153,6 +153,38 @@ describe('ErrorMessageExtra', () => {expect(screen.getByText('guide:claude-code:rate_limit')).toBeInTheDocument();});+ it('renders the heterogeneous guide from the session body without relying on the top-level error type', () => {+ render(+ <ErrorMessageExtra+ error={{ message: 'response.ServerAgentRuntimeError' }}+ data={{+ error: {+ body: {+ agentType: 'claude-code',+ clearEchoedContent: true,+ code: HeterogeneousAgentSessionErrorCode.RateLimit,+ message: "You've hit your limit · resets May 17 at 2am (Asia/Shanghai)",+ rateLimitInfo: {+ isUsingOverage: false,+ overageDisabledReason: 'org_level_disabled',+ overageStatus: 'rejected',+ rateLimitType: 'seven_day',+ resetsAt: 1778954400,+ status: 'rejected',+ },+ stderr: "You've hit your limit · resets May 17 at 2am (Asia/Shanghai)",+ },+ message: "You've hit your limit · resets May 17 at 2am (Asia/Shanghai)",+ type: 'ServerAgentRuntimeError',+ } as any,+ id: 'msg-rate-limit-wrapped',+ }}+ />,+ );++ expect(screen.getByText('guide:claude-code:rate_limit')).toBeInTheDocument();+ });+it('falls back to the raw error message instead of rendering a blank block', () => {render(<ErrorMessageExtradiff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex c8332bc99a2..2b8344dbed1 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -1,3 +1,4 @@+import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';import { type ILobeAgentRuntimeErrorType } from '@lobechat/model-runtime';import { AgentRuntimeErrorType } from '@lobechat/model-runtime';@@ -72,6 +73,26 @@ const OllamaSetupGuide = dynamic(() => import('./OllamaSetupGuide'), {ssr: false,});+const HETEROGENEOUS_AGENT_STATUS_GUIDE_ERROR_CODES = new Set<string>([+ HeterogeneousAgentSessionErrorCode.AuthRequired,+ HeterogeneousAgentSessionErrorCode.CliNotFound,+ HeterogeneousAgentSessionErrorCode.RateLimit,+]);++const isHeterogeneousAgentStatusGuideError = (+ value: unknown,+): value is HeterogeneousAgentSessionError => {+ if (!value || typeof value !== 'object') return false;++ const { agentType, code } = value as Partial<HeterogeneousAgentSessionError>;++ return (+ (agentType === 'claude-code' || agentType === 'codex') &&+ typeof code === 'string' &&+ HETEROGENEOUS_AGENT_STATUS_GUIDE_ERROR_CODES.has(code)+ );+};+// Config for the errorMessage displayconst getErrorAlertConfig = (errorType?: IToolErrorType | ILobeAgentRuntimeErrorType | ErrorType,@@ -157,24 +178,15 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data }) =>const navigate = useNavigate();const businessChatErrorMessageExtra = useRenderBusinessChatErrorMessageExtra(error, data.id);const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);- const sessionErrorCode = error?.body?.code;- const sessionAgentType = error?.body?.agentType;const sessionErrorBody = error?.body;const rawErrorMessage = getRawErrorMessage(error) || alertError?.message;if (enableBusinessFeatures && businessChatErrorMessageExtra) return businessChatErrorMessageExtra;- if (- (error?.type === AgentRuntimeErrorType.AgentRuntimeError || !error?.type) &&- !!sessionErrorBody &&- (sessionErrorCode === HeterogeneousAgentSessionErrorCode.AuthRequired ||- sessionErrorCode === HeterogeneousAgentSessionErrorCode.CliNotFound ||- sessionErrorCode === HeterogeneousAgentSessionErrorCode.RateLimit) &&- (sessionAgentType === 'claude-code' || sessionAgentType === 'codex')- ) {+ if (isHeterogeneousAgentStatusGuideError(sessionErrorBody)) {return (<HeterogeneousAgentStatusGuide- agentType={sessionAgentType}+ agentType={sessionErrorBody.agentType}error={sessionErrorBody}onOpenSystemTools={() => navigate('/settings/system-tools')}/>diff --git a/src/features/Conversation/Messages/components/ContentLoading.tsx b/src/features/Conversation/Messages/components/ContentLoading.tsxindex e6f0d4c1f70..d00c0dea7ef 100644--- a/src/features/Conversation/Messages/components/ContentLoading.tsx+++ b/src/features/Conversation/Messages/components/ContentLoading.tsx@@ -1,5 +1,5 @@import { HETEROGENEOUS_TYPE_LABELS } from '@lobechat/heterogeneous-agents';-import { Flexbox, Text } from '@lobehub/ui';+import { Flexbox } from '@lobehub/ui';import { memo, useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -78,15 +78,18 @@ const ContentLoading = memo<ContentLoadingProps>(({ id }) => {);}+ if (operationLabel) {+ return (+ <Flexbox horizontal align={'center'} gap={4}>+ <span className={shinyTextStyles.shinyText}>{operationLabel}...</span>+ {showElapsedTime && <span>({elapsedSeconds}s)</span>}+ </Flexbox>+ );+ }+return (<Flexbox horizontal align={'center'}><BubblesLoading />- {operationLabel && (- <Text type={'secondary'}>- {operationLabel}...- {showElapsedTime && ` (${elapsedSeconds}s)`}- </Text>- )}</Flexbox>);});diff --git a/src/features/DailyBrief/BriefCardActions.tsx b/src/features/DailyBrief/BriefCardActions.tsxindex 88e529ae8e1..364477bf440 100644--- a/src/features/DailyBrief/BriefCardActions.tsx+++ b/src/features/DailyBrief/BriefCardActions.tsx@@ -224,6 +224,16 @@ const BriefCardActions = memo<BriefCardActionsProps>(</Button>);})}+ {briefType === 'error' && (+ <Button+ className={styles.actionBtn}+ disabled={loadingKey === 'ignore'}+ shape={'round'}+ onClick={() => handleResolve('ignore')}+ >+ {t('brief.action.ignore')}+ </Button>+ )}{primaryActions && (<Buttonshadowdiff --git a/src/locales/default/home.ts b/src/locales/default/home.tsindex 723b7fc9ac9..5cfed511603 100644--- a/src/locales/default/home.ts+++ b/src/locales/default/home.ts@@ -9,6 +9,7 @@ export default {'brief.action.confirm': 'Confirm','brief.action.confirmDone': 'Confirm complete','brief.action.feedback': 'Feedback',+ 'brief.action.ignore': 'Ignore','brief.action.retry': 'Retry','brief.collapse': 'Show less','brief.commentPlaceholder': 'Share your feedback...',diff --git a/src/server/routers/lambda/agentNotify.ts b/src/server/routers/lambda/agentNotify.tsindex 697aa6cb917..b96c7a7eec8 100644--- a/src/server/routers/lambda/agentNotify.ts+++ b/src/server/routers/lambda/agentNotify.ts@@ -1,3 +1,4 @@+import { RequestTrigger } from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';import { z } from 'zod';@@ -64,6 +65,7 @@ export const agentNotifyRouter = router({agentId,appContext: { threadId, topicId },prompt: content,+ trigger: RequestTrigger.Notify,});return {diff --git a/src/server/routers/lambda/aiAgent.ts b/src/server/routers/lambda/aiAgent.tsindex 82b12694f7f..80bc9f2fd40 100644--- a/src/server/routers/lambda/aiAgent.ts+++ b/src/server/routers/lambda/aiAgent.ts@@ -1,8 +1,12 @@import { type AgentStreamEvent } from '@lobechat/agent-gateway-client';-import { type AgentRuntimeContext } from '@lobechat/agent-runtime';import { parse } from '@lobechat/conversation-flow';import { type TaskCurrentActivity, type TaskStatusResult } from '@lobechat/types';-import { ThreadStatus, ThreadType, UserInterventionConfigSchema } from '@lobechat/types';+import {+ RequestTrigger,+ ThreadStatus,+ ThreadType,+ UserInterventionConfigSchema,+} from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';import pMap from 'p-map';@@ -20,7 +24,6 @@ import { AiAgentService } from '@/server/services/aiAgent';import { AiChatService } from '@/server/services/aiChat';import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';import { TaskLifecycleService } from '@/server/services/taskLifecycle';-import { nanoid } from '@/utils/uuid';const log = debug('lobe-server:ai-agent-router');@@ -72,23 +75,6 @@ const formatTaskError = (error: unknown): Record<string, unknown> | undefined =>return message ? { ...taskError, message } : taskError;};-// Zod schemas for agent operation-const CreateAgentOperationSchema = z.object({- agentConfig: z.record(z.any()).optional().default({}),- agentId: z.string().optional(),- autoStart: z.boolean().optional().default(true),- messages: z.array(z.any()).optional().default([]),- modelRuntimeConfig: z.object({- model: z.string(),- provider: z.string(),- }),- threadId: z.string().optional().nullable(),- toolManifestMap: z.record(z.string(), z.any()).default({}),- tools: z.array(z.any()).optional(),- topicId: z.string().optional().nullable(),- userId: z.string().optional(),-});-const GetOperationStatusSchema = z.object({historyLimit: z.number().optional().default(10),includeHistory: z.boolean().optional().default(false),@@ -196,6 +182,13 @@ const ExecAgentSchema = z.optional(),/** The agent slug to run (either agentId or slug is required) */slug: z.string().optional(),+ /**+ * What initiated this operation, persisted to `agent_operations.trigger`.+ * Defaults to `'chat'` when omitted — first-party SPA / desktop user+ * messages are the dominant caller. Pass a more specific value (`'cli'`,+ * `'openapi'`, `'eval'`, …) to override.+ */+ trigger: z.string().optional(),/*** User intervention configuration for tool approvals.* Pass `{ approvalMode: 'headless' }` from headless clients (CLI, cron, bots)@@ -612,93 +605,6 @@ export const aiAgentRouter = router({}}),- createOperation: aiAgentProcedure- .input(CreateAgentOperationSchema)- .mutation(async ({ input, ctx }) => {- const {- agentConfig = {},- agentId,- autoStart = true,- messages = [],- modelRuntimeConfig,- threadId,- topicId,- tools,- toolManifestMap,- } = input;- log('input: %O', input);-- // Validate required parameters- if (!modelRuntimeConfig.model || !modelRuntimeConfig.provider) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'modelRuntimeConfig.model and modelRuntimeConfig.provider are required',- });- }-- // Generate runtime operation ID: agt_{timestamp}_{agentId}_{topicId}_{random}- const timestamp = Date.now();- const operationId = `agt_${timestamp}_${agentId || 'unknown'}_${topicId || 'none'}_${nanoid(8)}`;-- log(`Creating operation ${operationId} for user ${ctx.userId}`);-- // Create initial context- const initialContext: AgentRuntimeContext = {- payload: {},- phase: 'user_input' as const,- session: {- messageCount: messages.length,- sessionId: operationId,- status: 'idle' as const,- stepCount: 0,- },- };-- // Create operation using AgentRuntimeService- const result = await ctx.agentRuntimeService.createOperation({- agentConfig,- appContext: {- agentId,- threadId,- topicId,- },- autoStart,- initialContext,- initialMessages: messages,- modelRuntimeConfig,- operationId,- toolSet: {- manifestMap: toolManifestMap,- tools,- },- userId: ctx.userId,- });-- let firstStepResult;- if (result.autoStarted) {- firstStepResult = {- context: initialContext,- messageId: result.messageId,- scheduled: true,- };-- log(- `Operation ${operationId} created and first step scheduled (messageId: ${result.messageId})`,- );- } else {- log(`Operation ${operationId} created without auto-start`);- }-- return {- autoStart,- createdAt: new Date().toISOString(),- firstStep: firstStepResult,- operationId,- status: 'created',- success: true,- };- }),-execAgent: aiAgentProcedure.input(ExecAgentSchema).mutation(async ({ input, ctx }) => {const {agentId,@@ -712,6 +618,7 @@ export const aiAgentRouter = router({fileIds,parentMessageId,resumeApproval,+ trigger,userInterventionConfig,} = input;@@ -733,6 +640,7 @@ export const aiAgentRouter = router({resume: !!parentMessageId,resumeApproval,slug,+ trigger: trigger ?? RequestTrigger.Chat,userInterventionConfig,});} catch (error: any) {@@ -780,6 +688,7 @@ export const aiAgentRouter = router({deviceId,existingMessageIds = [],parentMessageId,+ trigger,} = task;try {@@ -794,6 +703,7 @@ export const aiAgentRouter = router({// When parentMessageId is provided, this is a regeneration/continue — skip user message creationresume: !!parentMessageId,slug,+ trigger: trigger ?? RequestTrigger.Chat,});return {diff --git a/src/server/services/agentEvalRun/index.ts b/src/server/services/agentEvalRun/index.tsindex 754dbd22650..dfc7b20ef0e 100644--- a/src/server/services/agentEvalRun/index.ts+++ b/src/server/services/agentEvalRun/index.ts@@ -541,6 +541,7 @@ export class AgentEvalRunService {agentId: targetAgentId,appContext,autoStart: true,+ trigger: RequestTrigger.Eval,hooks: [{handler: async (event) => {@@ -682,6 +683,7 @@ export class AgentEvalRunService {agentId: targetAgentId,appContext,autoStart: true,+ trigger: RequestTrigger.Eval,hooks: [{handler: async (event) => {@@ -963,6 +965,7 @@ export class AgentEvalRunService {agentId: run.targetAgentId ?? undefined,appContext: { topicId },autoStart: true,+ trigger: RequestTrigger.Eval,hooks: [{handler: async (event) => {@@ -1119,6 +1122,7 @@ export class AgentEvalRunService {agentId: run.targetAgentId ?? undefined,appContext: { threadId, topicId },autoStart: true,+ trigger: RequestTrigger.Eval,hooks: [{handler: async (event) => {diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsindex 3f97c0a5804..0031561c7ba 100644--- a/src/server/services/aiAgent/index.ts+++ b/src/server/services/aiAgent/index.ts@@ -37,11 +37,12 @@ import type {MessagePluginItem,UserInterventionConfig,} from '@lobechat/types';-import { ThreadStatus, ThreadType } from '@lobechat/types';+import { RequestTrigger, ThreadStatus, ThreadType } from '@lobechat/types';import { nanoid } from '@lobechat/utils';import debug from 'debug';import { AgentModel } from '@/database/models/agent';+import { AgentOperationModel } from '@/database/models/agentOperation';import { AgentSkillModel } from '@/database/models/agentSkill';import { AiModelModel } from '@/database/models/aiModel';import { FileModel } from '@/database/models/file';@@ -2065,6 +2066,7 @@ export class AiAgentService {appContext: { groupId, topicId },autoStart: true,prompt: message,+ trigger: RequestTrigger.Chat,});log(@@ -2148,6 +2150,21 @@ export class AiAgentService {// 3. Create hooks for updating Thread metadata and task messageconst threadHooks = this.createThreadHooks(thread.id, startedAt, parentMessageId);+ // Inherit parent op's trigger so sub-agent rows stay attributable to the+ // original entry point (chat / bot / cli / eval / …). Lookup is best-effort+ // — a missing parent row falls back to undefined and the column stays null.+ let inheritedTrigger: string | undefined;+ if (parentOperationId) {+ try {+ const parentOp = await new AgentOperationModel(this.db, this.userId).findById(+ parentOperationId,+ );+ inheritedTrigger = parentOp?.trigger ?? undefined;+ } catch (error) {+ log('execSubAgentTask: failed to read parent operation trigger: %O', error);+ }+ }+// 4. Delegate to execAgent with threadId in appContext and hooks// The instruction will be created as user message in the Thread// Use headless mode to skip human approval in async task execution@@ -2158,6 +2175,7 @@ export class AiAgentService {hooks: threadHooks,parentOperationId,prompt: instruction,+ trigger: inheritedTrigger,userInterventionConfig: { approvalMode: 'headless' },});diff --git a/src/services/agentRuntime/__tests__/index.test.ts b/src/services/agentRuntime/__tests__/index.test.tsdeleted file mode 100644index 687bbe9276e..00000000000--- a/src/services/agentRuntime/__tests__/index.test.ts+++ /dev/null@@ -1,128 +0,0 @@-import { type UIChatMessage } from '@lobechat/types';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { agentRuntimeService } from '../index';--const {- contextEngineeringMock,- createOperationMutateMock,- createAgentToolsEngineMock,- getAgentStoreStateMock,-} = vi.hoisted(() => ({- contextEngineeringMock: vi.fn(),- createAgentToolsEngineMock: vi.fn(),- createOperationMutateMock: vi.fn(),- getAgentStoreStateMock: vi.fn(),-}));--vi.mock('@/helpers/toolEngineering', () => ({- createAgentToolsEngine: createAgentToolsEngineMock,-}));--vi.mock('@/libs/trpc/client', () => ({- lambdaClient: {- aiAgent: {- createOperation: {- mutate: createOperationMutateMock,- },- getOperationStatus: {- query: vi.fn(),- },- processHumanIntervention: {- mutate: vi.fn(),- },- },- },-}));--vi.mock('@/services/chat/mecha', () => ({- contextEngineering: contextEngineeringMock,-}));--vi.mock('@/store/agent', () => ({- getAgentStoreState: getAgentStoreStateMock,-}));--vi.mock('@/store/agent/selectors', () => ({- agentChatConfigSelectors: {- currentChatConfig: vi.fn(() => ({ inputTemplate: 'input-template' })),- enableHistoryCount: vi.fn(() => true),- historyCount: vi.fn(() => 3),- isAgentEnableSearch: vi.fn(() => false),- },- agentSelectors: {- currentAgentConfig: vi.fn(() => ({- model: 'gpt-4o',- plugins: ['plugin-1'],- provider: 'openai',- systemRole: 'system-role',- })),- getAgentDocumentsById: vi.fn(() => () => undefined),- },-}));--describe('AgentRuntimeService', () => {- beforeEach(() => {- vi.clearAllMocks();-- createAgentToolsEngineMock.mockReturnValue({- generateToolsDetailed: vi.fn(() => ({- enabledToolIds: ['plugin-1'],- tools: [{ function: { name: 'plugin-1____api-1' }, type: 'function' }],- })),- getEnabledPluginManifests: vi.fn(() => new Map([['plugin-1', { identifier: 'plugin-1' }]])),- });-- contextEngineeringMock.mockResolvedValue([{ content: 'compiled', role: 'system' }]);- createOperationMutateMock.mockResolvedValue({ operationId: 'op-1' });- });-- it('should keep agent documents optional when hydration returns undefined', async () => {- const ensureAgentDocuments = vi.fn().mockResolvedValue(undefined);-- getAgentStoreStateMock.mockReturnValue({- activeAgentId: 'agent-1',- ensureAgentDocuments,- });-- const messages = [{ content: 'Hello', role: 'user' }] as UIChatMessage[];-- await agentRuntimeService.createOperation({- messages,- userMessageId: 'msg-1',- });-- expect(ensureAgentDocuments).toHaveBeenCalledWith('agent-1');- expect(contextEngineeringMock).toHaveBeenCalledWith(- expect.objectContaining({- agentDocuments: undefined,- }),- );- expect(createOperationMutateMock).toHaveBeenCalledWith(- expect.objectContaining({- messages: [{ content: 'compiled', role: 'system' }],- }),- );- });-- it('should use current agent plugins when creating operation tools', async () => {- getAgentStoreStateMock.mockReturnValue({- activeAgentId: 'agent-1',- });-- await agentRuntimeService.createOperation({- messages: [{ id: 'msg-1', content: 'Hello', role: 'user' }] as UIChatMessage[],- userMessageId: 'msg-1',- });-- expect(createAgentToolsEngineMock).toHaveBeenCalledWith({- model: 'gpt-4o',- provider: 'openai',- });- expect(contextEngineeringMock).toHaveBeenCalledWith(- expect.objectContaining({- plugins: ['plugin-1'],- }),- );- });-});diff --git a/src/services/agentRuntime/index.ts b/src/services/agentRuntime/index.tsindex f57a7767d0c..8bde4fe6713 100644--- a/src/services/agentRuntime/index.ts+++ b/src/services/agentRuntime/index.ts@@ -1,97 +1,10 @@-import type { AgentContextDocument } from '@lobechat/context-engine';-import { type UIChatMessage } from '@lobechat/types';--import { createAgentToolsEngine } from '@/helpers/toolEngineering';import { lambdaClient } from '@/libs/trpc/client';import { type HumanInterventionRequest } from '@/services/agentRuntime/type';-import { contextEngineering } from '@/services/chat/mecha';-import { getAgentStoreState } from '@/store/agent';-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';export { agentRuntimeClient } from './client';export * from './type';-interface AgentOperationRequest {- appSessionId?: string;- autoStart?: boolean;- messages: UIChatMessage[];- threadId?: string;- topicId?: string;- userMessageId: string;-}-class AgentRuntimeService {- createOperation = async (data: AgentOperationRequest) => {- const agentStoreState = getAgentStoreState();- const agentConfig = agentSelectors.currentAgentConfig(agentStoreState);- const chatConfig = agentChatConfigSelectors.currentChatConfig(agentStoreState);- let agentDocuments: AgentContextDocument[] | undefined = agentSelectors.getAgentDocumentsById(- agentStoreState.activeAgentId || '',- )(agentStoreState);-- if (agentStoreState.activeAgentId && agentDocuments === undefined) {- try {- agentDocuments = await agentStoreState.ensureAgentDocuments(agentStoreState.activeAgentId);- } catch (error) {- console.error('[AgentRuntimeService] Failed to ensure agent documents:', error);- }- }-- const modelRuntimeConfig = {- model: agentConfig.model,- provider: agentConfig.provider!,- };-- const toolsEngine = createAgentToolsEngine(modelRuntimeConfig);-- const { tools, enabledToolIds } = toolsEngine.generateToolsDetailed({- model: agentConfig.model,- provider: agentConfig.provider!,- toolIds: agentConfig.plugins,- });-- // Apply context engineering with preprocessing configuration- const llmMessages = await contextEngineering({- agentDocuments,- agentId: agentStoreState.activeAgentId,- enableHistoryCount: agentChatConfigSelectors.enableHistoryCount(agentStoreState),- // historyCount is number of history messages; add 1 for current user message- historyCount: agentChatConfigSelectors.historyCount(agentStoreState) + 1,- inputTemplate: chatConfig.inputTemplate,- messages: data.messages as any,- ...modelRuntimeConfig,- plugins: agentConfig.plugins,- systemRole: agentConfig.systemRole,- tools: enabledToolIds,- });-- const toolManifestMap = Object.fromEntries(- toolsEngine.getEnabledPluginManifests(enabledToolIds).entries(),- );-- return await lambdaClient.aiAgent.createOperation.mutate({- ...data,- agentConfig: {- enableSearch: agentChatConfigSelectors.isAgentEnableSearch(agentStoreState),- maxSteps: 50,- // costLimit: agentChatConfig.costLimit,- // enableRAG: false,- // humanApprovalRequired: agentChatConfig.humanApprovalRequired || false,- },- messages: llmMessages,- modelRuntimeConfig,- toolManifestMap,- tools,- });- };-- /**- * Get operation status- */- async getOperationStatus(operationId: string, includeHistory = false): Promise<any> {- return await lambdaClient.aiAgent.getOperationStatus.query({ includeHistory, operationId });- }-/*** Handle human intervention*/diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex da0c3dc1f21..5c5a6eccf13 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -44,6 +44,12 @@ export interface ExecAgentTaskParams {/** Resume a previous op paused on `human_approve_required` instead of starting from a fresh user prompt. */resumeApproval?: ResumeApprovalParam;slug?: string;+ /**+ * Override what initiated this operation. Server defaults to `'chat'` when+ * omitted. Pass a more specific value (`'cli'`, `'openapi'`, …) so the+ * `agent_operations.trigger` column reflects the real source.+ */+ trigger?: string;}/**