π€― 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(agent-signal): add CLI trigger command + golden snapshot fixture (#15360)
Arvin Xu7989952d2ed8
diff --git a/apps/cli/e2e/agent-signal.e2e.test.ts b/apps/cli/e2e/agent-signal.e2e.test.tsnew file mode 100644index 00000000000..e4b826006a4--- /dev/null+++ b/apps/cli/e2e/agent-signal.e2e.test.ts@@ -0,0 +1,88 @@+import { execSync } from 'node:child_process';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';++import { describe, expect, it } from 'vitest';++import {+ assertGoldenFinalState,+ extractGoldenOutcomes,+} from './fixtures/agent-signal/assertGoldenFinalState';++/**+ * E2E tests for `lh agent-signal trigger`.+ *+ * The "golden fixture" block runs fully offline β it is the structural+ * regression baseline that the execAgent migration (LOBE-9434 #5/#7) asserts+ * against. The "live trigger" block requires a running server + authenticated+ * CLI and is gated behind AGENT_SIGNAL_AGENT_ID (or AGENT_ID).+ *+ * Prerequisites for the live block:+ * - `lh` (or LH_CLI_PATH) points at the built CLI+ * - User is authenticated (`lh login`) against a dev server with Agent Signal enabled+ * - AGENT_SIGNAL_AGENT_ID=<agentId> identifies a target agent the user owns+ */++const CLI = process.env.LH_CLI_PATH || 'lh';+const AGENT_ID = process.env.AGENT_SIGNAL_AGENT_ID || process.env.AGENT_ID;+const TIMEOUT = 60_000;++const goldenPath = fileURLToPath(+ new URL('./fixtures/agent-signal/nightly-review.golden.json', import.meta.url),+);+const golden = JSON.parse(readFileSync(goldenPath, 'utf-8'));++function run(args: string): string {+ return execSync(`${CLI} ${args}`, {+ encoding: 'utf-8',+ env: { ...process.env, PATH: `${process.env.HOME}/.bun/bin:${process.env.PATH}` },+ timeout: TIMEOUT,+ }).trim();+}++describe('agent-signal golden fixture - structural regression', () => {+ it('captures a recognizable nightly-review source payload', () => {+ expect(golden.source.sourceType).toBe('agent.nightly_review.requested');+ expect(golden.source.payload.agentId).toBeTruthy();+ expect(golden.source.payload.userId).toBeTruthy();+ expect(golden.source.scopeKey).toContain('agent:');+ });++ it('extracts ideas / write outcomes / brief from finalState', () => {+ const outcomes = extractGoldenOutcomes(golden.finalState);++ expect(outcomes.ideas.length).toBeGreaterThanOrEqual(1);+ expect(outcomes.writeOutcomes.length).toBeGreaterThanOrEqual(1);+ expect(outcomes.brief).toBeDefined();+ });++ it('passes the shared structural assertion', () => {+ expect(() => assertGoldenFinalState(golden.finalState)).not.toThrow();+ });++ it('rejects an empty finalState', () => {+ expect(() => assertGoldenFinalState({ messages: [] })).toThrow(/artifact/i);+ });+});++describe.skipIf(!AGENT_ID)('lh agent-signal trigger - live', () => {+ it('triggers a nightly review and returns a workflow run id', () => {+ const output = run(+ `agent-signal trigger --source-type agent.nightly_review.requested --agent ${AGENT_ID} --json`,+ );+ const result = JSON.parse(output);+ expect(result).toHaveProperty('accepted');+ expect(result).toHaveProperty('scopeKey');+ // When Agent Signal is enabled for the account, a workflow run id is returned.+ if (result.accepted) {+ expect(typeof result.workflowRunId).toBe('string');+ expect(result.workflowRunId.length).toBeGreaterThan(0);+ }+ });++ it('exits non-zero on an invalid source type', () => {+ expect(() =>+ run(`agent-signal trigger --source-type not.a.real.type --agent ${AGENT_ID}`),+ ).toThrow();+ });+});diff --git a/apps/cli/e2e/fixtures/agent-signal/assertGoldenFinalState.ts b/apps/cli/e2e/fixtures/agent-signal/assertGoldenFinalState.tsnew file mode 100644index 00000000000..e0c84f79e82--- /dev/null+++ b/apps/cli/e2e/fixtures/agent-signal/assertGoldenFinalState.ts@@ -0,0 +1,127 @@+/**+ * Standalone structural assertions for self-iteration finalState snapshots.+ *+ * Dependency-free on purpose: the execAgent migration PRs (LOBE-9434 #5/#7)+ * import this from server tests AND the CLI e2e suite, so it must not pull in+ * vitest or any server-only module. Mirrors the `kind` discrimination used by+ * `src/server/services/agentSignal/services/selfIteration/finalStateExtractor.ts`.+ */++export type ToolResultKind = 'artifact' | 'mutation' | 'read';++export interface ToolResultWithKind {+ apiName?: string;+ data: Record<string, unknown> | unknown;+ kind: ToolResultKind;+ toolCallId?: string;+}++export interface GoldenOutcomes {+ /** The single brief mutation, if any (apiName matches /brief/i). */+ brief?: ToolResultWithKind;+ /** Artifact tool results whose apiName mentions an idea. */+ ideas: ToolResultWithKind[];+ /** Artifact tool results whose apiName mentions an intent. */+ intents: ToolResultWithKind[];+ /** Durable mutation tool results, excluding the brief. */+ writeOutcomes: ToolResultWithKind[];+}++interface FinalStateLike {+ messages?: unknown[];+}++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;+ }+};++/** Extract every tool result of `kind` from a finalState, in message order. */+export const extractFromFinalState = (+ finalState: FinalStateLike,+ 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;+};++const matchesApiName = (result: ToolResultWithKind, pattern: RegExp): boolean =>+ typeof result.apiName === 'string' && pattern.test(result.apiName);++const briefText = (brief?: ToolResultWithKind): string => {+ if (!brief || !isRecord(brief.data)) return '';+ const summary = typeof brief.data.summary === 'string' ? brief.data.summary : '';+ const body = typeof brief.data.body === 'string' ? brief.data.body : '';+ return `${summary}${body}`.trim();+};++/** Partition a finalState into ideas / intents / writeOutcomes / brief buckets. */+export const extractGoldenOutcomes = (finalState: FinalStateLike): GoldenOutcomes => {+ const artifacts = extractFromFinalState(finalState, 'artifact');+ const mutations = extractFromFinalState(finalState, 'mutation');++ const brief = mutations.find((m) => matchesApiName(m, /brief/i));++ return {+ brief,+ ideas: artifacts.filter((a) => matchesApiName(a, /idea/i)),+ intents: artifacts.filter((a) => matchesApiName(a, /intent/i)),+ writeOutcomes: mutations.filter((m) => !matchesApiName(m, /brief/i)),+ };+};++/**+ * Structural regression assertion for a self-iteration finalState.+ *+ * Throws (with a descriptive message) when the run produced no structured+ * output: it requires at least one artifact (idea or intent), at least one+ * durable write outcome, and a non-empty brief. Never compares text verbatim.+ */+export const assertGoldenFinalState = (finalState: FinalStateLike): GoldenOutcomes => {+ const outcomes = extractGoldenOutcomes(finalState);+ const artifactCount = outcomes.ideas.length + outcomes.intents.length;++ if (artifactCount < 1) {+ throw new Error(`Expected >= 1 artifact (idea/intent) in finalState, found ${artifactCount}`);+ }++ if (outcomes.writeOutcomes.length < 1) {+ throw new Error(+ `Expected >= 1 write outcome (mutation) in finalState, found ${outcomes.writeOutcomes.length}`,+ );+ }++ const text = briefText(outcomes.brief);+ if (text.length === 0) {+ throw new Error('Expected a non-empty brief in finalState, found none');+ }++ return outcomes;+};diff --git a/apps/cli/e2e/fixtures/agent-signal/nightly-review.golden.json b/apps/cli/e2e/fixtures/agent-signal/nightly-review.golden.jsonnew file mode 100644index 00000000000..b2217010902--- /dev/null+++ b/apps/cli/e2e/fixtures/agent-signal/nightly-review.golden.json@@ -0,0 +1,61 @@+{+ "description": "Desensitized golden snapshot of one nightly-review self-iteration run. Used as a structural regression baseline by the execAgent migration (LOBE-9434). Assert structure, never byte-for-byte: the LLM output is non-deterministic.",+ "finalState": {+ "messages": [+ {+ "content": "Run the nightly self-review for the local window.",+ "role": "user"+ },+ {+ "apiName": "getEvidenceDigest",+ "content": "{\"kind\":\"read\",\"topicCount\":3,\"messageCount\":42,\"window\":\"2026-05-30/2026-05-31\"}",+ "role": "tool",+ "tool_call_id": "call_read_1"+ },+ {+ "apiName": "recordSelfReviewIdea",+ "content": "{\"kind\":\"artifact\",\"idempotencyKey\":\"idea:pref:tone\",\"title\":\"Prefer concise replies\",\"rationale\":\"User repeatedly asked to shorten answers in topic tpc_demo\",\"risk\":\"low\"}",+ "role": "tool",+ "tool_call_id": "call_idea_1"+ },+ {+ "apiName": "recordSelfReviewIdea",+ "content": "{\"kind\":\"artifact\",\"idempotencyKey\":\"idea:skill:drizzle\",\"title\":\"Document Drizzle join helper\",\"rationale\":\"Recurring question about leftJoin usage\",\"risk\":\"medium\"}",+ "role": "tool",+ "tool_call_id": "call_idea_2"+ },+ {+ "apiName": "writeMemory",+ "content": "{\"kind\":\"mutation\",\"status\":\"applied\",\"resourceId\":\"mem_001\",\"summary\":\"Stored tone preference: prefer concise replies\"}",+ "pluginState": { "kind": "mutation" },+ "role": "tool",+ "tool_call_id": "call_mut_1"+ },+ {+ "apiName": "createSelfReviewBrief",+ "content": "{\"kind\":\"mutation\",\"briefId\":\"brief_001\",\"summary\":\"Nightly review captured 2 ideas and wrote 1 memory.\",\"body\":\"## Highlights\\n- Prefer concise replies\\n- Document Drizzle join helper\"}",+ "role": "tool",+ "tool_call_id": "call_brief_1"+ },+ {+ "content": "Nightly review complete. Captured 2 ideas and wrote 1 memory.",+ "role": "assistant"+ }+ ]+ },+ "source": {+ "payload": {+ "agentId": "agent_demo",+ "localDate": "2026-05-30",+ "requestedAt": "2026-05-31T04:00:00.000Z",+ "reviewWindowEnd": "2026-05-31T04:00:00.000Z",+ "reviewWindowStart": "2026-05-30T04:00:00.000Z",+ "timezone": "UTC",+ "userId": "user_demo"+ },+ "scopeKey": "agent:agent_demo:user:user_demo",+ "sourceId": "nightly-review:user_demo:agent_demo:2026-05-30",+ "sourceType": "agent.nightly_review.requested",+ "timestamp": 1748664000000+ }+}diff --git a/apps/cli/man/man1/lh.1 b/apps/cli/man/man1/lh.1index f9bbea48936..e79a15a3375 100644--- a/apps/cli/man/man1/lh.1+++ b/apps/cli/man/man1/lh.1@@ -65,6 +65,9 @@ Manage agents.B agent\-groupManage agent groups.TP+.B agent\-signal+Inspect and trigger Agent Signal source events+.TP.B botManage bot integrations.TPdiff --git a/apps/cli/src/commands/agent-signal/index.ts b/apps/cli/src/commands/agent-signal/index.tsnew file mode 100644index 00000000000..dfcee853dde--- /dev/null+++ b/apps/cli/src/commands/agent-signal/index.ts@@ -0,0 +1,129 @@+import type { Command } from 'commander';+import pc from 'picocolors';++import { getTrpcClient } from '../../api/client';+import { log } from '../../utils/logger';++/**+ * Producer source types a developer may trigger manually for local testing.+ * Mirrors `AGENT_SIGNAL_TRIGGER_SOURCE_TYPES` on the server; kept inline so the+ * CLI bundle does not pull in server-only modules.+ */+const TRIGGER_SOURCE_TYPES = [+ 'agent.nightly_review.requested',+ 'agent.self_reflection.requested',+ 'agent.self_feedback_intent.declared',+ 'agent.user.message',+ 'tool.outcome.completed',+ 'tool.outcome.failed',+] as const;++type TriggerSourceType = (typeof TRIGGER_SOURCE_TYPES)[number];++export function registerAgentSignalCommand(program: Command) {+ const agentSignal = program+ .command('agent-signal')+ .description('Inspect and trigger Agent Signal source events');++ agentSignal+ .command('trigger')+ .description('Trigger an Agent Signal source event for the authenticated user')+ .requiredOption(+ '--source-type <type>',+ `Source type to emit. One of:\n ${TRIGGER_SOURCE_TYPES.join('\n ')}`,+ )+ .option('--agent <agentId>', 'Target agent ID (required for agent-scoped source types)')+ .option('--topic <topicId>', 'Topic ID to scope the event to')+ .option('--payload-json <json>', 'JSON object shallow-merged over the default payload')+ .option('--source-id <id>', 'Override the auto-derived dedupe source id')+ .option('--scope-key <key>', 'Override the auto-derived scope key')+ .option('--timestamp <ms>', 'Event timestamp in milliseconds')+ .option('--json', 'Output JSON')+ .action(+ async (options: {+ agent?: string;+ json?: boolean;+ payloadJson?: string;+ scopeKey?: string;+ sourceId?: string;+ sourceType: string;+ timestamp?: string;+ topic?: string;+ }) => {+ const sourceType = options.sourceType as TriggerSourceType;++ if (!TRIGGER_SOURCE_TYPES.includes(sourceType)) {+ console.error(+ `${pc.red('β')} Invalid --source-type "${options.sourceType}". Expected one of: ${TRIGGER_SOURCE_TYPES.join(', ')}`,+ );+ process.exit(1);+ return;+ }++ let payloadOverride: Record<string, unknown> | undefined;+ if (options.payloadJson) {+ try {+ const parsed = JSON.parse(options.payloadJson);+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {+ throw new Error('payload must be a JSON object');+ }+ payloadOverride = parsed as Record<string, unknown>;+ } catch (error: any) {+ console.error(`${pc.red('β')} Failed to parse --payload-json: ${error.message}`);+ process.exit(1);+ return;+ }+ }++ let timestamp: number | undefined;+ if (options.timestamp !== undefined) {+ timestamp = Number(options.timestamp);+ if (!Number.isFinite(timestamp)) {+ console.error(`${pc.red('β')} --timestamp must be a number (milliseconds)`);+ process.exit(1);+ return;+ }+ }++ log.debug(+ 'agent-signal trigger: sourceType=%s agent=%s topic=%s',+ sourceType,+ options.agent,+ options.topic,+ );++ const client = await getTrpcClient();++ try {+ const result = await client.agentSignal.triggerSourceEvent.mutate({+ agentId: options.agent,+ payloadOverride,+ scopeKey: options.scopeKey,+ sourceId: options.sourceId,+ sourceType,+ timestamp,+ topicId: options.topic,+ });++ if (options.json) {+ console.log(JSON.stringify(result, null, 2));+ return;+ }++ if (!result.accepted) {+ console.log(+ `${pc.yellow('!')} Agent Signal is disabled for this account β event was not enqueued (scopeKey: ${pc.bold(result.scopeKey)})`,+ );+ return;+ }++ console.log(`${pc.green('β')} Triggered ${pc.bold(sourceType)}`);+ console.log(` Scope key: ${result.scopeKey}`);+ console.log(` Workflow run id: ${result.workflowRunId}`);+ } catch (error: any) {+ console.error(`${pc.red('β')} Failed to trigger source event: ${error.message}`);+ process.exit(1);+ }+ },+ );+}diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.tsindex 76f7618632d..59d539a75e2 100644--- a/apps/cli/src/program.ts+++ b/apps/cli/src/program.ts@@ -4,6 +4,7 @@ import { Command } from 'commander';import { registerAgentCommand } from './commands/agent';import { registerAgentGroupCommand } from './commands/agent-group';+import { registerAgentSignalCommand } from './commands/agent-signal';import { registerBotCommand } from './commands/bot';import { registerCompletionCommand } from './commands/completion';import { registerConfigCommand } from './commands/config';@@ -58,6 +59,7 @@ export function createProgram() {registerMemoryCommand(program);registerAgentCommand(program);registerAgentGroupCommand(program);+ registerAgentSignalCommand(program);registerBotCommand(program);registerGenerateCommand(program);registerFileCommand(program);diff --git a/src/server/routers/lambda/agentSignal.ts b/src/server/routers/lambda/agentSignal.tsindex 836b9069e72..a69160f0776 100644--- a/src/server/routers/lambda/agentSignal.ts+++ b/src/server/routers/lambda/agentSignal.ts@@ -8,6 +8,10 @@ import { z } from 'zod';import { authedProcedure, router } from '@/libs/trpc/lambda';import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';import { listAgentSignalReceipts } from '@/server/services/agentSignal/services/receiptService';+import {+ AGENT_SIGNAL_TRIGGER_SOURCE_TYPES,+ buildTriggerSourceEvent,+} from '@/server/services/agentSignal/triggerSourceEvent';const log = debug('lobe-server:agent-signal:router');@@ -44,6 +48,41 @@ export const agentSignalRouter = router({userId: ctx.userId,});}),+ triggerSourceEvent: agentSignalProcedure+ .input(+ z.object({+ agentId: z.string().optional(),+ payloadOverride: z.record(z.string(), z.unknown()).optional(),+ scopeKey: z.string().optional(),+ sourceId: z.string().optional(),+ sourceType: z.enum(AGENT_SIGNAL_TRIGGER_SOURCE_TYPES),+ timestamp: z.number().optional(),+ topicId: z.string().optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ const sourceEvent = buildTriggerSourceEvent({+ agentId: input.agentId,+ payloadOverride: input.payloadOverride,+ scopeKey: input.scopeKey,+ sourceId: input.sourceId,+ sourceType: input.sourceType,+ timestamp: input.timestamp,+ topicId: input.topicId,+ userId: ctx.userId,+ });++ log(+ 'Triggering source event sourceType=%s sourceId=%s',+ sourceEvent.sourceType,+ sourceEvent.sourceId,+ );++ return enqueueAgentSignalSourceEvent(sourceEvent, {+ agentId: input.agentId,+ userId: ctx.userId,+ });+ }),listReceipts: agentSignalProcedure.input(z.object({diff --git a/src/server/services/agentSignal/__tests__/triggerSourceEvent.test.ts b/src/server/services/agentSignal/__tests__/triggerSourceEvent.test.tsnew file mode 100644index 00000000000..36b0cad5f59--- /dev/null+++ b/src/server/services/agentSignal/__tests__/triggerSourceEvent.test.ts@@ -0,0 +1,142 @@+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import { describe, expect, it } from 'vitest';++import {+ AGENT_SIGNAL_TRIGGER_SOURCE_TYPES,+ buildTriggerSourceEvent,+ isAgentSignalTriggerSourceType,+} from '../triggerSourceEvent';++// Fixed clock so derived ids / windows are deterministic.+const NOW = Date.parse('2026-05-31T12:00:00.000Z');+const userId = 'user_1';+const agentId = 'agent_1';++describe('isAgentSignalTriggerSourceType', () => {+ it('accepts every advertised trigger source type', () => {+ for (const type of AGENT_SIGNAL_TRIGGER_SOURCE_TYPES) {+ expect(isAgentSignalTriggerSourceType(type)).toBe(true);+ }+ });++ it('rejects client-only / unknown source types', () => {+ expect(isAgentSignalTriggerSourceType('client.runtime.start')).toBe(false);+ expect(isAgentSignalTriggerSourceType('not.a.real.type')).toBe(false);+ });+});++describe('buildTriggerSourceEvent', () => {+ it('builds a nightly review event with a stable source id and derived window', () => {+ const event = buildTriggerSourceEvent({+ agentId,+ now: NOW,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ userId,+ });++ expect(event.sourceType).toBe(AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested);+ expect(event.sourceId).toBe('nightly-review:user_1:agent_1:2026-05-31');+ const payload = event.payload as Record<string, unknown>;+ expect(payload.userId).toBe(userId);+ expect(payload.localDate).toBe('2026-05-31');+ expect(payload.reviewWindowEnd).toBe('2026-05-31T12:00:00.000Z');+ expect(payload.reviewWindowStart).toBe('2026-05-30T12:00:00.000Z');+ });++ it('builds a self-reflection event scoped to the topic when provided', () => {+ const event = buildTriggerSourceEvent({+ agentId,+ now: NOW,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+ topicId: 'tpc_1',+ userId,+ });++ const payload = event.payload as Record<string, unknown>;+ expect(payload.scopeType).toBe('topic');+ expect(payload.scopeId).toBe('tpc_1');+ expect(payload.topicId).toBe('tpc_1');+ expect(event.sourceId).toContain('self-reflection:user_1:agent_1:topic:tpc_1');+ });++ it('builds a self-feedback-intent event with default memory action', () => {+ const event = buildTriggerSourceEvent({+ agentId,+ now: NOW,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,+ userId,+ });++ const payload = event.payload as Record<string, unknown>;+ expect(payload.action).toBe('write');+ expect(payload.kind).toBe('memory');+ expect(payload.confidence).toBe(0.9);+ expect(event.sourceId).toBe(+ 'self-feedback-intent:user_1:agent_1:operation:manual:' + NOW + ':manual-' + NOW,+ );+ });++ it('builds an agent.user.message event without requiring an agent', () => {+ const event = buildTriggerSourceEvent({+ now: NOW,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,+ userId,+ });++ const payload = event.payload as Record<string, unknown>;+ expect(payload.message).toBe('Manual agent.user.message trigger');+ expect(payload.messageId).toBe(`manual-${NOW}`);+ // userId is injected to keep scope-key fallback owner-scoped.+ expect(payload.userId).toBe(userId);+ });++ it.each([+ [AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeCompleted, 'succeeded'],+ [AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed, 'failed'],+ ])('builds a %s event with status %s', (sourceType, status) => {+ const event = buildTriggerSourceEvent({ agentId, now: NOW, sourceType, userId });+ const payload = event.payload as { outcome: { status: string }; tool: { identifier: string } };+ expect(payload.outcome.status).toBe(status);+ expect(payload.tool.identifier).toBe('manual-trigger');+ });++ it('throws a clear error when agentId is missing for agent-scoped types', () => {+ expect(() =>+ buildTriggerSourceEvent({+ now: NOW,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ userId,+ }),+ ).toThrow(/agentId is required/);+ });++ it('merges payload overrides but never lets them repoint userId', () => {+ const event = buildTriggerSourceEvent({+ agentId,+ now: NOW,+ payloadOverride: { timezone: 'Asia/Shanghai', userId: 'attacker' },+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ userId,+ });++ const payload = event.payload as Record<string, unknown>;+ expect(payload.timezone).toBe('Asia/Shanghai');+ expect(payload.userId).toBe(userId);+ });++ it('honors an explicit sourceId / scopeKey / timestamp override', () => {+ const event = buildTriggerSourceEvent({+ agentId,+ now: NOW,+ scopeKey: 'agent:agent_1:user:user_1',+ sourceId: 'custom-source-id',+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ timestamp: 123,+ userId,+ });++ expect(event.sourceId).toBe('custom-source-id');+ expect(event.scopeKey).toBe('agent:agent_1:user:user_1');+ expect(event.timestamp).toBe(123);+ });+});diff --git a/src/server/services/agentSignal/triggerSourceEvent.ts b/src/server/services/agentSignal/triggerSourceEvent.tsnew file mode 100644index 00000000000..edec490da10--- /dev/null+++ b/src/server/services/agentSignal/triggerSourceEvent.ts@@ -0,0 +1,238 @@+import {+ AGENT_SIGNAL_SOURCE_TYPES,+ type AgentSignalSourcePayloadMap,+} from '@lobechat/agent-signal/source';++import type { AgentSignalSourceEventInput } from './emitter';+import {+ buildNightlyReviewSourceId,+ buildSelfFeedbackIntentSourceId,+ buildSelfReflectionSourceId,+} from './services/selfIteration/types';++/**+ * Producer source types a developer may trigger manually (CLI / local testing).+ *+ * These are normally emitted by the server itself (schedulers, runtime, tool+ * runtimes) and are intentionally excluded from `AGENT_SIGNAL_CLIENT_SOURCE_TYPES`.+ * The trigger path re-derives `userId` from the authenticated context so a caller+ * can only fan out signals scoped to their own account.+ */+export const AGENT_SIGNAL_TRIGGER_SOURCE_TYPES = [+ AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested,+ AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested,+ AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared,+ AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage,+ AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeCompleted,+ AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed,+] as const;++export type AgentSignalTriggerSourceType = (typeof AGENT_SIGNAL_TRIGGER_SOURCE_TYPES)[number];++const TRIGGER_SOURCE_TYPE_SET = new Set<string>(AGENT_SIGNAL_TRIGGER_SOURCE_TYPES);++export const isAgentSignalTriggerSourceType = (+ value: string,+): value is AgentSignalTriggerSourceType => TRIGGER_SOURCE_TYPE_SET.has(value);++/** One manual-trigger build request, before defaults are filled in. */+export interface BuildTriggerSourceEventInput {+ /** Agent the signal targets. Required for every source type except runtime debug ones. */+ agentId?: string;+ /** Injected clock, overridable for deterministic tests. Defaults to `Date.now()`. */+ now?: number;+ /** Shallow override merged over the derived default payload (`userId` is ignored). */+ payloadOverride?: Record<string, unknown>;+ /** Explicit scope key. Defaults to payload-derived routing in `createSourceEvent`. */+ scopeKey?: string;+ /** Stable dedupe id. Defaults to a source-type specific deterministic id. */+ sourceId?: string;+ sourceType: AgentSignalTriggerSourceType;+ /** Event timestamp in ms. Defaults to `now` inside `createSourceEvent`. */+ timestamp?: number;+ /** Topic the signal is scoped to, when applicable. */+ topicId?: string;+ /** Owner of the triggered signal. Comes from the authenticated context. */+ userId: string;+}++const HOUR_MS = 60 * 60 * 1000;+const DAY_MS = 24 * HOUR_MS;++const requireAgentId = (sourceType: AgentSignalTriggerSourceType, agentId?: string): string => {+ if (!agentId) {+ throw new Error(`agentId is required to trigger source type "${sourceType}"`);+ }+ return agentId;+};++/**+ * Builds a fully-formed source event input for one manually triggered source type.+ *+ * Use when:+ * - A developer triggers an Agent Signal source from the CLI / a test harness and+ * wants the same normalization boundary production producers use.+ *+ * Expects:+ * - `userId` resolved from the authenticated context (never the payload override).+ * - `agentId` present for agent-scoped source types; throws a clear error otherwise.+ *+ * Returns:+ * - An `AgentSignalSourceEventInput` ready for `enqueueAgentSignalSourceEvent`.+ */+export const buildTriggerSourceEvent = (+ input: BuildTriggerSourceEventInput,+): AgentSignalSourceEventInput<AgentSignalTriggerSourceType> => {+ const { agentId, sourceType, topicId, userId } = input;+ const now = input.now ?? Date.now();+ const nowIso = new Date(now).toISOString();+ const localDate = nowIso.slice(0, 10);++ // `userId` is owner-bound; never let an override repoint it to another account.+ const override = { ...input.payloadOverride };+ delete override.userId;++ let payload: AgentSignalSourcePayloadMap[AgentSignalTriggerSourceType];+ let defaultSourceId: string;++ switch (sourceType) {+ case AGENT_SIGNAL_SOURCE_TYPES.agentNightlyReviewRequested: {+ const resolvedAgentId = requireAgentId(sourceType, agentId);+ const resolvedLocalDate =+ typeof override.localDate === 'string' ? override.localDate : localDate;+ payload = {+ agentId: resolvedAgentId,+ localDate: resolvedLocalDate,+ requestedAt: nowIso,+ reviewWindowEnd: nowIso,+ reviewWindowStart: new Date(now - DAY_MS).toISOString(),+ timezone: 'UTC',+ userId,+ };+ defaultSourceId = buildNightlyReviewSourceId({+ agentId: resolvedAgentId,+ localDate: resolvedLocalDate,+ userId,+ });+ break;+ }++ case AGENT_SIGNAL_SOURCE_TYPES.agentSelfReflectionRequested: {+ const resolvedAgentId = requireAgentId(sourceType, agentId);+ const scopeType = topicId ? 'topic' : 'operation';+ const scopeId = topicId ?? `manual:${now}`;+ const reason = 'manual-trigger';+ const windowStart = new Date(now - HOUR_MS).toISOString();+ payload = {+ agentId: resolvedAgentId,+ reason,+ scopeId,+ scopeType,+ topicId,+ userId,+ windowEnd: nowIso,+ windowStart,+ };+ defaultSourceId = buildSelfReflectionSourceId({+ agentId: resolvedAgentId,+ reason,+ scopeId,+ scopeType,+ userId,+ windowEnd: nowIso,+ windowStart,+ });+ break;+ }++ case AGENT_SIGNAL_SOURCE_TYPES.agentSelfFeedbackIntentDeclared: {+ const resolvedAgentId = requireAgentId(sourceType, agentId);+ const toolCallId = `manual-${now}`;+ const scopeType = topicId ? 'topic' : 'operation';+ const scopeId = topicId ?? `manual:${now}`;+ payload = {+ action: 'write',+ agentId: resolvedAgentId,+ confidence: 0.9,+ kind: 'memory',+ reason: 'manual-trigger',+ summary: 'Manual self-feedback intent trigger',+ toolCallId,+ topicId,+ userId,+ };+ defaultSourceId = buildSelfFeedbackIntentSourceId({+ agentId: resolvedAgentId,+ scopeId,+ scopeType,+ toolCallId,+ userId,+ });+ break;+ }++ case AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage: {+ const messageId = `manual-${now}`;+ payload = {+ agentId,+ message: 'Manual agent.user.message trigger',+ messageId,+ topicId,+ trigger: 'cli-trigger',+ };+ defaultSourceId = `manual-user-message:${userId}:${agentId ?? 'none'}:${now}`;+ break;+ }++ case AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeCompleted: {+ payload = {+ agentId,+ outcome: {+ action: 'manual-trigger',+ status: 'succeeded',+ summary: 'Manual tool outcome trigger',+ },+ tool: { identifier: 'manual-trigger' },+ topicId,+ };+ defaultSourceId = `manual-tool-outcome:succeeded:${userId}:${now}`;+ break;+ }++ case AGENT_SIGNAL_SOURCE_TYPES.toolOutcomeFailed: {+ payload = {+ agentId,+ outcome: {+ action: 'manual-trigger',+ errorReason: 'manual-trigger',+ status: 'failed',+ summary: 'Manual tool failure trigger',+ },+ tool: { identifier: 'manual-trigger' },+ topicId,+ };+ defaultSourceId = `manual-tool-outcome:failed:${userId}:${now}`;+ break;+ }++ default: {+ // Exhaustiveness guard: a new trigger source type must be handled above.+ const exhaustive: never = sourceType;+ throw new Error(`Unsupported trigger source type "${exhaustive as string}"`);+ }+ }++ const mergedPayload = {+ ...(payload as Record<string, unknown>),+ ...override,+ userId,+ } as AgentSignalSourcePayloadMap[AgentSignalTriggerSourceType];++ return {+ payload: mergedPayload,+ scopeKey: input.scopeKey,+ sourceId: input.sourceId ?? defaultSourceId,+ sourceType,+ timestamp: input.timestamp,+ } as AgentSignalSourceEventInput<AgentSignalTriggerSourceType>;+};