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.

✨ feat(agent-signal): add execAgent plumbing for self-iteration migration (#15187)

Arvin Xu8d4c48749ff6
diff --git a/packages/builtin-agents/src/agents/self-iteration/index.ts b/packages/builtin-agents/src/agents/self-iteration/index.ts
new file mode 100644
index 00000000000..c32219e6b8c
--- /dev/null
+++ b/packages/builtin-agents/src/agents/self-iteration/index.ts
@@ -0,0 +1,21 @@
+import type { BuiltinAgentDefinition } from '../../types';
+import { BUILTIN_AGENT_SLUGS } from '../../types';
+
+const SELF_ITERATION_TOOL_IDENTIFIER = 'agent-signal-self-iteration';
+
+/**
+ * Self-Iteration Agent - shared execAgent target for nightly review, post-turn
+ * reflection, and declared feedback intents.
+ *
+ * All three flows share the same tool surface (`agent-signal-self-iteration`);
+ * the mode-specific guidance is supplied per-call by the caller's prompt builder,
+ * so the agent itself stays neutral.
+ */
+export const SELF_ITERATION: BuiltinAgentDefinition = {
+ runtime: {
+ plugins: [SELF_ITERATION_TOOL_IDENTIFIER],
+ systemRole:
+ 'You are the self-iteration agent. Follow the mode-specific instructions in the user prompt and apply safe resource operations using the provided self-iteration tools. Be concise and evidence-driven.',
+ },
+ slug: BUILTIN_AGENT_SLUGS.selfIteration,
+};
diff --git a/packages/builtin-agents/src/index.ts b/packages/builtin-agents/src/index.ts
index 8edbcbac6e3..681cde99b8a 100644
--- a/packages/builtin-agents/src/index.ts
+++ b/packages/builtin-agents/src/index.ts
@@ -3,6 +3,7 @@ import { GROUP_AGENT_BUILDER } from './agents/group-agent-builder';
import { GROUP_SUPERVISOR } from './agents/group-supervisor';
import { INBOX } from './agents/inbox';
import { PAGE_AGENT } from './agents/page-agent';
+import { SELF_ITERATION } from './agents/self-iteration';
import { TASK_AGENT } from './agents/task-agent';
import { WEB_ONBOARDING } from './agents/web-onboarding';
import type { BuiltinAgentDefinition, BuiltinAgentSlug, RuntimeContext } from './types';
@@ -16,6 +17,7 @@ export { GROUP_AGENT_BUILDER } from './agents/group-agent-builder';
export { GROUP_SUPERVISOR } from './agents/group-supervisor';
export { INBOX } from './agents/inbox';
export { PAGE_AGENT } from './agents/page-agent';
+export { SELF_ITERATION } from './agents/self-iteration';
export { TASK_AGENT } from './agents/task-agent';
export { WEB_ONBOARDING } from './agents/web-onboarding';
@@ -28,10 +30,20 @@ export const BUILTIN_AGENTS: Record<BuiltinAgentSlug, BuiltinAgentDefinition> =
[BUILTIN_AGENT_SLUGS.groupSupervisor]: GROUP_SUPERVISOR,
[BUILTIN_AGENT_SLUGS.inbox]: INBOX,
[BUILTIN_AGENT_SLUGS.pageAgent]: PAGE_AGENT,
+ [BUILTIN_AGENT_SLUGS.selfIteration]: SELF_ITERATION,
[BUILTIN_AGENT_SLUGS.taskAgent]: TASK_AGENT,
[BUILTIN_AGENT_SLUGS.webOnboarding]: WEB_ONBOARDING,
};
+/**
+ * Slugs that belong to the self-iteration family.
+ * Used by AgentSignal to skip re-triggering signal events
+ * for builtin background runs (suppressSignal behaviour).
+ */
+export const SELF_ITERATION_AGENT_SLUGS = new Set<BuiltinAgentSlug>([
+ BUILTIN_AGENT_SLUGS.selfIteration,
+]);
+
/**
* Get persist config for a builtin agent (for DB operations)
* @param slug - The builtin agent slug
diff --git a/packages/builtin-agents/src/types.ts b/packages/builtin-agents/src/types.ts
index 60123d1c35a..0e942574594 100644
--- a/packages/builtin-agents/src/types.ts
+++ b/packages/builtin-agents/src/types.ts
@@ -11,6 +11,7 @@ export const BUILTIN_AGENT_SLUGS = {
groupSupervisor: 'group-supervisor',
inbox: 'inbox',
pageAgent: 'page-agent',
+ selfIteration: 'self-iteration',
taskAgent: 'task-agent',
webOnboarding: 'web-onboarding',
} as const;
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 763493ebcd1..ad14d1a9e9e 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -23,6 +23,14 @@ export interface ExecAgentAppContext {
scope?: string | null;
/** Session ID */
sessionId?: string;
+ /** Optional assistant message id that anchors the run (e.g. parent for an isolated thread). */
+ sourceMessageId?: string;
+ /**
+ * Suppresses AgentSignal `agent.user.message` re-emission when this run is itself driven by a
+ * background/builtin agent. Required for self-iteration / memory-writer / skill-manager runs to
+ * avoid recursion into the analyzeIntent pipeline.
+ */
+ suppressSignal?: boolean;
/** Current task identifier when executing from a task detail surface */
taskId?: string | null;
/** Thread ID for threaded conversations */
diff --git a/src/server/services/agentSignal/__tests__/suppressSignal.test.ts b/src/server/services/agentSignal/__tests__/suppressSignal.test.ts
new file mode 100644
index 00000000000..dfc729ccf08
--- /dev/null
+++ b/src/server/services/agentSignal/__tests__/suppressSignal.test.ts
@@ -0,0 +1,29 @@
+// @vitest-environment node
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { describe, expect, it } from 'vitest';
+
+import { shouldSuppressSignal } from '../suppressSignal';
+
+describe('shouldSuppressSignal', () => {
+ it('returns true when appContext.suppressSignal is explicitly true', () => {
+ expect(shouldSuppressSignal({ appContext: { suppressSignal: true } })).toBe(true);
+ });
+
+ it('returns true when slug is in SELF_ITERATION_AGENT_SLUGS', () => {
+ expect(shouldSuppressSignal({ slug: BUILTIN_AGENT_SLUGS.selfIteration })).toBe(true);
+ });
+
+ it('returns false for ordinary user-facing slugs', () => {
+ expect(shouldSuppressSignal({ slug: BUILTIN_AGENT_SLUGS.inbox })).toBe(false);
+ });
+
+ it('returns false when neither suppressSignal nor a matching slug is set', () => {
+ expect(shouldSuppressSignal({})).toBe(false);
+ expect(shouldSuppressSignal({ appContext: {} })).toBe(false);
+ expect(shouldSuppressSignal({ appContext: { suppressSignal: false } })).toBe(false);
+ });
+
+ it('ignores unknown slugs', () => {
+ expect(shouldSuppressSignal({ slug: 'unknown-slug' })).toBe(false);
+ });
+});
diff --git a/src/server/services/agentSignal/policies/completionPolicy.test.ts b/src/server/services/agentSignal/policies/completionPolicy.test.ts
new file mode 100644
index 00000000000..3d3c3c36975
--- /dev/null
+++ b/src/server/services/agentSignal/policies/completionPolicy.test.ts
@@ -0,0 +1,108 @@
+// @vitest-environment node
+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+import { describe, expect, it, vi } from 'vitest';
+
+import { createCompletionPolicy } from './completionPolicy';
+
+interface CapturedHandler {
+ handle: (source: { payload: Record<string, unknown> }) => Promise<void>;
+ id: string;
+ listen: string;
+}
+
+const installAndCapture = (middleware: ReturnType<typeof createCompletionPolicy>) => {
+ const sourceHandlers: CapturedHandler[] = [];
+
+ middleware.install({
+ handleAction: vi.fn(),
+ handleSignal: vi.fn(),
+ handleSource: (handler: unknown) => {
+ sourceHandlers.push(handler as CapturedHandler);
+ },
+ } as never);
+
+ return sourceHandlers;
+};
+
+describe('createCompletionPolicy', () => {
+ it('registers a single source handler on agent.execution.completed', () => {
+ const handlers = installAndCapture(createCompletionPolicy());
+
+ expect(handlers).toHaveLength(1);
+ expect(handlers[0].listen).toBe(AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted);
+ expect(handlers[0].id).toBe('agent.execution.completed:completion-fanout');
+ });
+
+ it('is a no-op when the callback is not provided', async () => {
+ const [handler] = installAndCapture(createCompletionPolicy());
+
+ await expect(
+ handler.handle({
+ payload: {
+ agentId: BUILTIN_AGENT_SLUGS.selfIteration,
+ operationId: 'op_1',
+ },
+ }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('ignores non-self-iteration agents even when a callback is provided', async () => {
+ const onSelfIterationCompleted = vi.fn();
+ const [handler] = installAndCapture(createCompletionPolicy({ onSelfIterationCompleted }));
+
+ await handler.handle({
+ payload: { agentId: BUILTIN_AGENT_SLUGS.inbox, operationId: 'op_2' },
+ });
+
+ expect(onSelfIterationCompleted).not.toHaveBeenCalled();
+ });
+
+ it('invokes the callback for self-iteration runs', async () => {
+ const onSelfIterationCompleted = vi.fn().mockResolvedValue(undefined);
+ const [handler] = installAndCapture(createCompletionPolicy({ onSelfIterationCompleted }));
+
+ await handler.handle({
+ payload: {
+ agentId: BUILTIN_AGENT_SLUGS.selfIteration,
+ operationId: 'op_3',
+ topicId: 'topic_3',
+ },
+ });
+
+ expect(onSelfIterationCompleted).toHaveBeenCalledWith({
+ agentId: BUILTIN_AGENT_SLUGS.selfIteration,
+ operationId: 'op_3',
+ topicId: 'topic_3',
+ });
+ });
+
+ it('swallows callback errors so the worker is not blocked', async () => {
+ const error = new Error('boom');
+ const onSelfIterationCompleted = vi.fn().mockRejectedValue(error);
+ const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const [handler] = installAndCapture(createCompletionPolicy({ onSelfIterationCompleted }));
+
+ await expect(
+ handler.handle({
+ payload: {
+ agentId: BUILTIN_AGENT_SLUGS.selfIteration,
+ operationId: 'op_4',
+ },
+ }),
+ ).resolves.toBeUndefined();
+
+ expect(consoleSpy).toHaveBeenCalled();
+ consoleSpy.mockRestore();
+ });
+
+ it('skips when required fields are missing', async () => {
+ const onSelfIterationCompleted = vi.fn();
+ const [handler] = installAndCapture(createCompletionPolicy({ onSelfIterationCompleted }));
+
+ await handler.handle({ payload: { operationId: 'op_5' } });
+ await handler.handle({ payload: { agentId: BUILTIN_AGENT_SLUGS.selfIteration } });
+
+ expect(onSelfIterationCompleted).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/services/agentSignal/policies/completionPolicy.ts b/src/server/services/agentSignal/policies/completionPolicy.ts
new file mode 100644
index 00000000000..5c36b52f7d7
--- /dev/null
+++ b/src/server/services/agentSignal/policies/completionPolicy.ts
@@ -0,0 +1,62 @@
+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';
+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';
+
+import { defineAgentSignalHandlers, defineSourceHandler } from '../runtime/middleware';
+
+/**
+ * Handles `agent.execution.completed` source events emitted after every execAgent run
+ * (including builtin background agents). Routes builtin self-iteration runs to an
+ * optional caller callback so side-effects (brief writing, receipt projection,
+ * idempotency marker) can happen asynchronously after the agent run finishes.
+ *
+ * Mode-specific dispatch (review / reflection / feedback) is deferred — the
+ * caller can demultiplex by looking up the operation row and inspecting the
+ * stored scope / iteration mode at callback time.
+ *
+ * The callback is fire-and-forget from the worker's perspective; failures are
+ * logged but never re-trigger the source pipeline.
+ *
+ * NOTE on userId: the `agent.execution.completed` source payload does not carry
+ * userId, and `AgentSignalSource.scope` is not populated by renderers. Callers
+ * that need userId should look it up via the operations table by `operationId`.
+ */
+export interface CompletionCallbackParams {
+ agentId: string;
+ operationId: string;
+ /** Optional topic id forwarded from the source payload. */
+ topicId?: string;
+}
+
+export interface CreateCompletionPolicyOptions {
+ /** Called when a self-iteration run completes (any mode: review / reflection / feedback). */
+ onSelfIterationCompleted?: (params: CompletionCallbackParams) => Promise<void>;
+}
+
+export const createCompletionPolicy = (options: CreateCompletionPolicyOptions = {}) =>
+ defineAgentSignalHandlers([
+ defineSourceHandler(
+ AGENT_SIGNAL_SOURCE_TYPES.agentExecutionCompleted,
+ 'agent.execution.completed:completion-fanout',
+ async (source) => {
+ const { agentId, operationId, topicId } = source.payload;
+
+ if (!agentId || !operationId) return;
+ if (agentId !== BUILTIN_AGENT_SLUGS.selfIteration) return;
+ if (!options.onSelfIterationCompleted) return;
+
+ const params: CompletionCallbackParams = {
+ agentId,
+ operationId,
+ ...(topicId ? { topicId } : {}),
+ };
+
+ try {
+ await options.onSelfIterationCompleted(params);
+ } catch (error) {
+ // Non-fatal: completion policy failures must not block the AgentSignal worker
+ // or cause source re-processing.
+ console.error('[completionPolicy] post-completion handler failed', { agentId, error });
+ }
+ },
+ ),
+ ]);
diff --git a/src/server/services/agentSignal/policies/index.ts b/src/server/services/agentSignal/policies/index.ts
index fc3cdee622b..5110ba45ef5 100644
--- a/src/server/services/agentSignal/policies/index.ts
+++ b/src/server/services/agentSignal/policies/index.ts
@@ -7,6 +7,8 @@ import type {
} from './analyzeIntent/actions';
import type { CreateFeedbackDomainJudgePolicyOptions } from './analyzeIntent/feedbackDomain';
import type { CreateFeedbackSatisfactionJudgePolicyOptions } from './analyzeIntent/feedbackSatisfaction';
+import type { CreateCompletionPolicyOptions } from './completionPolicy';
+import { createCompletionPolicy } from './completionPolicy';
import type { CreateReviewNightlyPolicyOptions } from './reviewNightly';
import { createReviewNightlyPolicy } from './reviewNightly';
@@ -17,11 +19,14 @@ export * from './analyzeIntent/feedbackAction';
export * from './analyzeIntent/feedbackDomain';
export * from './analyzeIntent/feedbackDomainAgent';
export * from './analyzeIntent/feedbackSatisfaction';
+export * from './completionPolicy';
export * from './reviewNightly';
export * from './types';
export interface CreateDefaultAgentSignalPoliciesOptions extends CreateFeedbackDomainJudgePolicyOptions {
classifierDiagnostics?: CreateAnalyzeIntentPolicyOptions['classifierDiagnostics'];
+ /** Optional callbacks invoked after agent.execution.completed for builtin self-iteration agents. */
+ completion?: CreateCompletionPolicyOptions;
feedbackSatisfactionJudge?: CreateFeedbackSatisfactionJudgePolicyOptions;
nightlyReview?: CreateReviewNightlyPolicyOptions['nightlyReview'];
procedure?: CreateAnalyzeIntentPolicyOptions['procedure'];
@@ -44,6 +49,7 @@ const DEFAULT_AGENT_SIGNAL_POLICY_FACTORIES: DefaultAgentSignalPolicyFactory[] =
selfFeedbackIntent: options.selfFeedbackIntent,
selfReflection: options.selfReflection,
}),
+ (options) => [createCompletionPolicy(options.completion ?? {})],
];
/**
diff --git a/src/server/services/agentSignal/services/selfIteration/__test__/finalStateExtractor.test.ts b/src/server/services/agentSignal/services/selfIteration/__test__/finalStateExtractor.test.ts
new file mode 100644
index 00000000000..a712e333aaf
--- /dev/null
+++ b/src/server/services/agentSignal/services/selfIteration/__test__/finalStateExtractor.test.ts
@@ -0,0 +1,92 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+import { describe, expect, it } from 'vitest';
+
+import { extractArtifacts, extractFromFinalState, extractMutations } from '../finalStateExtractor';
+
+const buildState = (messages: unknown[]): AgentState =>
+ ({
+ messages,
+ }) as never;
+
+describe('extractFromFinalState', () => {
+ it('returns matching results when kind is encoded inline in the content JSON', () => {
+ const state = buildState([
+ {
+ apiName: 'writeMemory',
+ content: JSON.stringify({ kind: 'mutation', memoryId: 'mem_1' }),
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ {
+ apiName: 'recordIdea',
+ content: JSON.stringify({ ideaId: 'idea_1', kind: 'artifact' }),
+ role: 'tool',
+ tool_call_id: 'call_2',
+ },
+ ]);
+
+ const mutations = extractFromFinalState(state, 'mutation');
+
+ expect(mutations).toEqual([
+ {
+ apiName: 'writeMemory',
+ data: { kind: 'mutation', memoryId: 'mem_1' },
+ kind: 'mutation',
+ toolCallId: 'call_1',
+ },
+ ]);
+ });
+
+ it('falls back to pluginState.kind when content is not a JSON object', () => {
+ const state = buildState([
+ {
+ content: 'Memory saved successfully',
+ pluginState: { kind: 'mutation', memoryId: 'mem_2' },
+ role: 'tool',
+ tool_call_id: 'call_3',
+ },
+ ]);
+
+ const result = extractFromFinalState(state, 'mutation');
+
+ expect(result).toHaveLength(1);
+ expect(result[0].kind).toBe('mutation');
+ expect(result[0].toolCallId).toBe('call_3');
+ });
+
+ it('skips messages with no kind, wrong kind, or non-tool role', () => {
+ const state = buildState([
+ { content: 'no kind here', role: 'tool', tool_call_id: 'a' },
+ { content: JSON.stringify({ kind: 'read' }), role: 'tool', tool_call_id: 'b' },
+ { content: JSON.stringify({ kind: 'mutation' }), role: 'assistant', tool_call_id: 'c' },
+ ]);
+
+ expect(extractFromFinalState(state, 'mutation')).toEqual([]);
+ });
+
+ it('returns an empty array when state.messages is missing', () => {
+ expect(extractFromFinalState({} as AgentState, 'mutation')).toEqual([]);
+ });
+
+ it('preserves message order', () => {
+ const state = buildState([
+ { content: JSON.stringify({ id: 1, kind: 'artifact' }), role: 'tool' },
+ { content: JSON.stringify({ id: 2, kind: 'artifact' }), role: 'tool' },
+ { content: JSON.stringify({ id: 3, kind: 'mutation' }), role: 'tool' },
+ { content: JSON.stringify({ id: 4, kind: 'artifact' }), role: 'tool' },
+ ]);
+
+ const artifacts = extractArtifacts(state);
+ expect(artifacts.map((r) => (r.data as { id: number }).id)).toEqual([1, 2, 4]);
+ });
+
+ it('extractMutations / extractArtifacts are convenience wrappers', () => {
+ const state = buildState([
+ { content: JSON.stringify({ kind: 'mutation' }), role: 'tool' },
+ { content: JSON.stringify({ kind: 'artifact' }), role: 'tool' },
+ ]);
+
+ expect(extractMutations(state)).toHaveLength(1);
+ expect(extractArtifacts(state)).toHaveLength(1);
+ });
+});
diff --git a/src/server/services/agentSignal/services/selfIteration/finalStateExtractor.ts b/src/server/services/agentSignal/services/selfIteration/finalStateExtractor.ts
new file mode 100644
index 00000000000..1c9b2b361e8
--- /dev/null
+++ b/src/server/services/agentSignal/services/selfIteration/finalStateExtractor.ts
@@ -0,0 +1,97 @@
+import type { AgentState } from '@lobechat/agent-runtime';
+
+/**
+ * Tool result kind discriminator.
+ *
+ * - `read` : read-only evidence tools (getEvidenceDigest, getManagedSkill, …)
+ * - `artifact` : side-effect-free output tools (recordReflectionIdea, recordSelfReviewIdea,
+ * recordSelfFeedbackIntent)
+ * - `mutation` : durable resource write tools (writeMemory, createSkillIfAbsent,
+ * replaceSkillContentCAS, createSelfReviewProposal, …)
+ *
+ * Attach this field to every tool result returned by self-iteration tools so
+ * that extractFromFinalState can efficiently partition outcomes without
+ * inspecting tool names.
+ */
+export type ToolResultKind = 'artifact' | 'mutation' | 'read';
+
+export interface ToolResultWithKind {
+ /** Tool API name (e.g. 'writeMemory'). */
+ apiName?: string;
+ /** Parsed tool result data. */
+ data: unknown;
+ /** Discrimination tag set by the tool implementation. */
+ kind: ToolResultKind;
+ /** Tool call id this result belongs to. */
+ toolCallId?: string;
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === 'object' && value !== null && !Array.isArray(value);
+
+const parseContent = (content: unknown): unknown => {
+ if (typeof content !== 'string') return content;
+ try {
+ return JSON.parse(content);
+ } catch {
+ return content;
+ }
+};
+
+/**
+ * Extracts tool results of a specific kind from AgentState finalState.
+ *
+ * Use when:
+ * - Completion policy writers need to reconstruct structured output after an
+ * execAgent run completes (replacing the old side-channel closure accumulators).
+ * - Replay / eval tooling needs to inspect idea / intent / write outcomes from
+ * a persisted snapshot without re-running the agent.
+ *
+ * Expects:
+ * - Tool messages in state.messages carry a `pluginState.kind` or a top-level
+ * `kind` field set by the self-iteration tool implementation.
+ * - Messages without a `kind` field are silently skipped.
+ *
+ * Returns:
+ * - Array of ToolResultWithKind matching the requested kind, in message order.
+ */
+export const extractFromFinalState = (
+ finalState: AgentState,
+ kind: ToolResultKind,
+): ToolResultWithKind[] => {
+ const results: ToolResultWithKind[] = [];
+
+ for (const message of finalState.messages ?? []) {
+ if (!isRecord(message)) continue;
+ if (message.role !== 'tool') continue;
+
+ const content = parseContent(message.content);
+ const contentRecord = isRecord(content) ? content : undefined;
+
+ const pluginState = isRecord(message.pluginState) ? message.pluginState : undefined;
+ const resultKind = contentRecord?.kind ?? pluginState?.kind;
+
+ if (resultKind !== kind) continue;
+
+ results.push({
+ apiName: typeof message.apiName === 'string' ? message.apiName : undefined,
+ data: contentRecord ?? content,
+ kind,
+ toolCallId: typeof message.tool_call_id === 'string' ? message.tool_call_id : undefined,
+ });
+ }
+
+ return results;
+};
+
+/**
+ * Convenience: extract all mutation outcomes from finalState.
+ */
+export const extractMutations = (finalState: AgentState) =>
+ extractFromFinalState(finalState, 'mutation');
+
+/**
+ * Convenience: extract all artifact outcomes (ideas, intents) from finalState.
+ */
+export const extractArtifacts = (finalState: AgentState) =>
+ extractFromFinalState(finalState, 'artifact');
diff --git a/src/server/services/agentSignal/suppressSignal.ts b/src/server/services/agentSignal/suppressSignal.ts
new file mode 100644
index 00000000000..7f02a902f27
--- /dev/null
+++ b/src/server/services/agentSignal/suppressSignal.ts
@@ -0,0 +1,23 @@
+import { SELF_ITERATION_AGENT_SLUGS } from '@lobechat/builtin-agents';
+
+/**
+ * Returns true when the agent run should not trigger downstream
+ * AgentSignal source events.
+ *
+ * Suppression applies when:
+ * - The slug belongs to SELF_ITERATION_AGENT_SLUGS (currently just `self-iteration`).
+ * - The caller passes `appContext.suppressSignal: true` explicitly.
+ *
+ * Background system agents must always pass this so that their own
+ * execAgent invocations do not re-enter the AgentSignal pipeline and
+ * trigger infinite self-iteration loops.
+ */
+export const shouldSuppressSignal = (options: {
+ appContext?: { suppressSignal?: boolean };
+ slug?: string;
+}): boolean => {
+ if (options.appContext?.suppressSignal === true) return true;
+ if (options.slug && SELF_ITERATION_AGENT_SLUGS.has(options.slug as never)) return true;
+
+ return false;
+};
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index 8068f84c455..332a5733a58 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -74,6 +74,7 @@ import {
isLobeAiAgentSlug,
resolveAgentSelfIterationCapability,
} from '@/server/services/agentSignal/featureGate';
+import { shouldSuppressSignal } from '@/server/services/agentSignal/suppressSignal';
import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';
@@ -1843,26 +1844,33 @@ export class AiAgentService {
// It must not block the primary agent execution path; local Workflow/QStash
// stalls would otherwise leave the conversation with only the user message
// persisted and no assistant placeholder or operation row.
- void enqueueAgentSignalSourceEvent(
- {
- payload: {
+ //
+ // Skip when this execAgent invocation is itself an Agent Signal background run
+ // (e.g. memory writer, self-iteration reviewer). Otherwise the analyzeIntent
+ // policy would re-analyze the synthesised user prompt and recursively trigger
+ // another Agent Signal pass.
+ if (!shouldSuppressSignal({ appContext, slug: agentSlug ?? undefined })) {
+ void enqueueAgentSignalSourceEvent(
+ {
+ payload: {
+ agentId: resolvedAgentId,
+ message: prompt,
+ threadId: appContext?.threadId ?? undefined,
+ topicId,
+ trigger,
+ messageId: userMessageRecord.id,
+ },
+ sourceId: userMessageRecord.id,
+ sourceType: 'agent.user.message',
+ },
+ {
agentId: resolvedAgentId,
- message: prompt,
- threadId: appContext?.threadId ?? undefined,
- topicId,
- trigger,
- messageId: userMessageRecord.id,
+ userId: this.userId,
},
- sourceId: userMessageRecord.id,
- sourceType: 'agent.user.message',
- },
- {
- agentId: resolvedAgentId,
- userId: this.userId,
- },
- ).catch((error) => {
- log('execAgent: failed to enqueue user message Agent Signal source event: %O', error);
- });
+ ).catch((error) => {
+ log('execAgent: failed to enqueue user message Agent Signal source event: %O', error);
+ });
+ }
}
// 14. Create assistant message placeholder in database