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.

🐛 fix: support local Agent Signal workflows (#17681)

YuTengjingcb10dd3a3118
diff --git a/.agents/skills/agent-signal/references/architecture.md b/.agents/skills/agent-signal/references/architecture.md
index 27536d649d1..7f7f67635de 100644
--- a/.agents/skills/agent-signal/references/architecture.md
+++ b/.agents/skills/agent-signal/references/architecture.md
@@ -193,6 +193,14 @@ Use `enqueueAgentSignalSourceEvent(...)` when the work should stay quiet and out
3. triggers `AgentSignalWorkflow`
4. executes later in `runAgentSignalWorkflow`
+Delivery follows `AGENT_RUNTIME_MODE`: queue mode uses Upstash Workflow for
+durable execution, retries, and flow control; local mode defers an in-process
+run with `setTimeout`, returns a synthetic `workflowRunId`, and intentionally
+does not provide persistence or retries. Local mode uses a process-scoped
+source-event store and runtime guard for dedupe, scope locks, windows, and action
+idempotency so it remains functional without Redis while preserving those
+guarantees for the server process lifetime.
+
This is the preferred path when the UI request should finish immediately and the policy can run in the background.
Read:
diff --git a/apps/server/src/services/agentSignal/runtime/backend/memoryGuard.test.ts b/apps/server/src/services/agentSignal/runtime/backend/memoryGuard.test.ts
new file mode 100644
index 00000000000..6fb80eeb2ca
--- /dev/null
+++ b/apps/server/src/services/agentSignal/runtime/backend/memoryGuard.test.ts
@@ -0,0 +1,35 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { AGENT_SIGNAL_DEFAULTS } from '../../constants';
+import { inMemoryRuntimeGuardBackend } from './memoryGuard';
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+});
+
+describe('inMemoryRuntimeGuardBackend', () => {
+ it('should share action guard state until the local TTL expires', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1_000);
+
+ await expect(
+ inMemoryRuntimeGuardBackend.touchGuardState('scope-1', 'action-1', 1_000),
+ ).resolves.toEqual({
+ lastEventAt: 1_000,
+ startedAt: 1_000,
+ });
+ await expect(inMemoryRuntimeGuardBackend.getGuardState('scope-1', 'action-1')).resolves.toEqual(
+ {
+ lastEventAt: 1_000,
+ startedAt: 1_000,
+ },
+ );
+
+ await vi.advanceTimersByTimeAsync(AGENT_SIGNAL_DEFAULTS.runtimeGuardTtlSeconds * 1000 + 1);
+
+ await expect(inMemoryRuntimeGuardBackend.getGuardState('scope-1', 'action-1')).resolves.toEqual(
+ {},
+ );
+ });
+});
diff --git a/apps/server/src/services/agentSignal/runtime/backend/memoryGuard.ts b/apps/server/src/services/agentSignal/runtime/backend/memoryGuard.ts
new file mode 100644
index 00000000000..a6d809f642b
--- /dev/null
+++ b/apps/server/src/services/agentSignal/runtime/backend/memoryGuard.ts
@@ -0,0 +1,29 @@
+import { AGENT_SIGNAL_DEFAULTS } from '../../constants';
+import { ExpiringMap } from '../../store/adapters/memory/expiringMap';
+import type { RuntimeGuardBackend, RuntimeGuardState } from '../AgentSignalRuntime';
+
+const guardStates = new ExpiringMap<RuntimeGuardState>();
+
+/**
+ * Process-local runtime guard state for non-durable Agent Signal execution.
+ *
+ * Local workflow invocations share this backend for the server process lifetime,
+ * while TTL cleanup mirrors the expiry boundary of the Redis-backed guard.
+ */
+export const inMemoryRuntimeGuardBackend: RuntimeGuardBackend = {
+ async getGuardState(scopeKey, lane) {
+ return guardStates.get(`${scopeKey}:${lane}`) ?? {};
+ },
+ async touchGuardState(scopeKey, lane, now) {
+ const key = `${scopeKey}:${lane}`;
+ const current = guardStates.get(key) ?? {};
+ const next = {
+ lastEventAt: now,
+ startedAt: current.startedAt ?? now,
+ } satisfies RuntimeGuardState;
+
+ guardStates.set(key, next, AGENT_SIGNAL_DEFAULTS.runtimeGuardTtlSeconds * 1000);
+
+ return next;
+ },
+};
diff --git a/apps/server/src/services/agentSignal/store/adapters/memory/expiringMap.test.ts b/apps/server/src/services/agentSignal/store/adapters/memory/expiringMap.test.ts
new file mode 100644
index 00000000000..361fe938c1c
--- /dev/null
+++ b/apps/server/src/services/agentSignal/store/adapters/memory/expiringMap.test.ts
@@ -0,0 +1,25 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { ExpiringMap } from './expiringMap';
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+});
+
+describe('ExpiringMap', () => {
+ it('should actively prune unique expired keys without another read', async () => {
+ vi.useFakeTimers();
+ const entries = new ExpiringMap<string>();
+
+ entries.set('unique-1', 'one', 10_000);
+ entries.set('unique-2', 'two', 20_000);
+ expect(entries.size).toBe(2);
+
+ await vi.advanceTimersByTimeAsync(10_001);
+ expect(entries.size).toBe(1);
+
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(entries.size).toBe(0);
+ });
+});
diff --git a/apps/server/src/services/agentSignal/store/adapters/memory/expiringMap.ts b/apps/server/src/services/agentSignal/store/adapters/memory/expiringMap.ts
new file mode 100644
index 00000000000..5f17057f7f3
--- /dev/null
+++ b/apps/server/src/services/agentSignal/store/adapters/memory/expiringMap.ts
@@ -0,0 +1,81 @@
+interface ExpiringEntry<T> {
+ expiresAt: number;
+ value: T;
+}
+
+const MAX_SWEEP_INTERVAL_MS = 60_000;
+
+/**
+ * Small process-local TTL map with one unref'ed cleanup timer.
+ *
+ * The bounded sweep interval prevents unique, never-read keys from accumulating
+ * indefinitely while avoiding one timer per Agent Signal entry.
+ */
+export class ExpiringMap<T> {
+ private entries = new Map<string, ExpiringEntry<T>>();
+ private nextSweepAt?: number;
+ private sweepTimer?: ReturnType<typeof setTimeout>;
+
+ get size() {
+ return this.entries.size;
+ }
+
+ clear() {
+ if (this.sweepTimer) clearTimeout(this.sweepTimer);
+ this.entries.clear();
+ this.nextSweepAt = undefined;
+ this.sweepTimer = undefined;
+ }
+
+ delete(key: string) {
+ return this.entries.delete(key);
+ }
+
+ get(key: string) {
+ const entry = this.entries.get(key);
+ if (!entry) return undefined;
+ if (entry.expiresAt <= Date.now()) {
+ this.entries.delete(key);
+ return undefined;
+ }
+
+ return entry.value;
+ }
+
+ set(key: string, value: T, ttlMs: number) {
+ const expiresAt = Date.now() + Math.max(0, ttlMs);
+ this.entries.set(key, { expiresAt, value });
+
+ if (this.nextSweepAt === undefined || expiresAt < this.nextSweepAt) {
+ if (this.sweepTimer) clearTimeout(this.sweepTimer);
+ this.scheduleSweep();
+ }
+ }
+
+ private scheduleSweep() {
+ if (this.entries.size === 0) return;
+
+ const now = Date.now();
+ const earliestExpiration = Math.min(
+ ...Array.from(this.entries.values(), ({ expiresAt }) => expiresAt),
+ );
+ this.nextSweepAt = Math.min(earliestExpiration, now + MAX_SWEEP_INTERVAL_MS);
+ this.sweepTimer = setTimeout(
+ () => {
+ this.nextSweepAt = undefined;
+ this.sweepTimer = undefined;
+ this.sweep();
+ this.scheduleSweep();
+ },
+ Math.max(0, this.nextSweepAt - now),
+ );
+ this.sweepTimer.unref();
+ }
+
+ private sweep() {
+ const now = Date.now();
+ for (const [key, entry] of this.entries) {
+ if (entry.expiresAt <= now) this.entries.delete(key);
+ }
+ }
+}
diff --git a/apps/server/src/services/agentSignal/store/adapters/memory/sourceEventStore.test.ts b/apps/server/src/services/agentSignal/store/adapters/memory/sourceEventStore.test.ts
new file mode 100644
index 00000000000..ca639df965a
--- /dev/null
+++ b/apps/server/src/services/agentSignal/store/adapters/memory/sourceEventStore.test.ts
@@ -0,0 +1,38 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { inMemorySourceEventStore } from './sourceEventStore';
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+});
+
+describe('inMemorySourceEventStore', () => {
+ it('should preserve dedupe and scope locks until their TTL expires', async () => {
+ vi.useFakeTimers();
+
+ await expect(inMemorySourceEventStore.tryDedupe('event-1', 10)).resolves.toBe(true);
+ await expect(inMemorySourceEventStore.tryDedupe('event-1', 10)).resolves.toBe(false);
+ await expect(inMemorySourceEventStore.acquireScopeLock('scope-1', 10)).resolves.toBe(true);
+ await expect(inMemorySourceEventStore.acquireScopeLock('scope-1', 10)).resolves.toBe(false);
+
+ await vi.advanceTimersByTimeAsync(10_001);
+
+ await expect(inMemorySourceEventStore.tryDedupe('event-1', 10)).resolves.toBe(true);
+ await expect(inMemorySourceEventStore.acquireScopeLock('scope-1', 10)).resolves.toBe(true);
+ });
+
+ it('should copy window payloads and expire them', async () => {
+ vi.useFakeTimers();
+ const data = { count: '1' };
+
+ await inMemorySourceEventStore.writeWindow('scope-2', data, 10);
+ data.count = '2';
+
+ await expect(inMemorySourceEventStore.readWindow('scope-2')).resolves.toEqual({ count: '1' });
+
+ await vi.advanceTimersByTimeAsync(10_001);
+
+ await expect(inMemorySourceEventStore.readWindow('scope-2')).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/agentSignal/store/adapters/memory/sourceEventStore.ts b/apps/server/src/services/agentSignal/store/adapters/memory/sourceEventStore.ts
new file mode 100644
index 00000000000..78f17ead9a8
--- /dev/null
+++ b/apps/server/src/services/agentSignal/store/adapters/memory/sourceEventStore.ts
@@ -0,0 +1,37 @@
+import type { AgentSignalSourceEventStore, AgentSignalSourceEventWindowPayload } from '../../types';
+import { ExpiringMap } from './expiringMap';
+
+const dedupeEntries = new ExpiringMap<boolean>();
+const scopeLocks = new ExpiringMap<boolean>();
+const windows = new ExpiringMap<AgentSignalSourceEventWindowPayload>();
+
+const getTtlMs = (ttlSeconds: number) => ttlSeconds * 1000;
+
+const reserve = (entries: ExpiringMap<boolean>, key: string, ttlSeconds: number) => {
+ if (entries.get(key)) return false;
+
+ entries.set(key, true, getTtlMs(ttlSeconds));
+ return true;
+};
+
+/**
+ * Process-local source-event state for non-durable Agent Signal execution.
+ *
+ * Local workflow mode deliberately avoids Redis and QStash. Keeping this store
+ * at module scope preserves dedupe, scope locks, and source windows for the
+ * lifetime of the server process without implying cross-process durability.
+ */
+export const inMemorySourceEventStore: AgentSignalSourceEventStore = {
+ acquireScopeLock: async (scopeKey, ttlSeconds) => reserve(scopeLocks, scopeKey, ttlSeconds),
+ readWindow: async (scopeKey) => {
+ const data = windows.get(scopeKey);
+ return data ? { ...data } : undefined;
+ },
+ releaseScopeLock: async (scopeKey) => {
+ scopeLocks.delete(scopeKey);
+ },
+ tryDedupe: async (eventId, ttlSeconds) => reserve(dedupeEntries, eventId, ttlSeconds),
+ writeWindow: async (scopeKey, data, ttlSeconds) => {
+ windows.set(scopeKey, { ...data }, getTtlMs(ttlSeconds));
+ },
+};
diff --git a/apps/server/src/workflows/agentSignal.test.ts b/apps/server/src/workflows/agentSignal.test.ts
index 7332d97bca5..e1e76497be1 100644
--- a/apps/server/src/workflows/agentSignal.test.ts
+++ b/apps/server/src/workflows/agentSignal.test.ts
@@ -6,6 +6,7 @@ const triggerMock = vi.fn();
vi.mock('@/envs/app', () => ({
appEnv: {
APP_URL: 'http://localhost:3011',
+ enableQueueAgentRuntime: true,
INTERNAL_APP_URL: 'http://localhost:3011',
},
}));
diff --git a/apps/server/src/workflows/agentSignal/__tests__/index.test.ts b/apps/server/src/workflows/agentSignal/__tests__/index.test.ts
new file mode 100644
index 00000000000..54b6acdad7f
--- /dev/null
+++ b/apps/server/src/workflows/agentSignal/__tests__/index.test.ts
@@ -0,0 +1,182 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { AgentSignalWorkflowRunPayload } from '@/server/workflows/agentSignal';
+import { AgentSignalWorkflow } from '@/server/workflows/agentSignal';
+
+const mocks = vi.hoisted(() => ({
+ appEnv: {
+ APP_URL: 'http://localhost:3010',
+ enableQueueAgentRuntime: false,
+ INTERNAL_APP_URL: undefined as string | undefined,
+ },
+ executeAgentSignalSourceEvent: vi.fn(),
+ inMemorySourceEventStore: {
+ kind: 'memory',
+ },
+ inMemoryRuntimeGuardBackend: {
+ kind: 'memory-guard',
+ },
+ injectActiveTraceHeaders: vi.fn(),
+ runAgentSignalWorkflow: vi.fn(),
+ trigger: vi.fn(),
+}));
+
+vi.mock('@/envs/app', () => ({
+ appEnv: mocks.appEnv,
+}));
+
+vi.mock('@/libs/observability/traceparent', () => ({
+ injectActiveTraceHeaders: mocks.injectActiveTraceHeaders,
+}));
+
+vi.mock('@/libs/qstash', () => ({
+ workflowClient: {
+ trigger: mocks.trigger,
+ },
+}));
+
+vi.mock('@/server/services/agentSignal/orchestrator', () => ({
+ executeAgentSignalSourceEvent: mocks.executeAgentSignalSourceEvent,
+}));
+
+vi.mock('@/server/services/agentSignal/store/adapters/memory/sourceEventStore', () => ({
+ inMemorySourceEventStore: mocks.inMemorySourceEventStore,
+}));
+
+vi.mock('@/server/services/agentSignal/runtime/backend/memoryGuard', () => ({
+ inMemoryRuntimeGuardBackend: mocks.inMemoryRuntimeGuardBackend,
+}));
+
+vi.mock('@/server/workflows/agentSignal/run', () => ({
+ runAgentSignalWorkflow: mocks.runAgentSignalWorkflow,
+}));
+
+const createPayload = (): AgentSignalWorkflowRunPayload => ({
+ agentId: 'agent-1',
+ sourceEvent: {
+ payload: {
+ agentId: 'agent-1',
+ message: 'hello',
+ messageId: 'message-1',
+ topicId: 'topic-1',
+ },
+ scopeKey: 'topic:topic-1',
+ sourceId: 'source-1',
+ sourceType: 'agent.user.message',
+ timestamp: 1,
+ },
+ userId: 'user-1',
+});
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ mocks.appEnv.enableQueueAgentRuntime = false;
+ mocks.runAgentSignalWorkflow.mockResolvedValue({ success: true });
+ mocks.trigger.mockResolvedValue({ workflowRunId: 'workflow-1' });
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+});
+
+describe('AgentSignalWorkflow', () => {
+ it('runs locally without contacting QStash when queue runtime is disabled', async () => {
+ const payload = createPayload();
+
+ await expect(AgentSignalWorkflow.triggerRun(payload)).resolves.toEqual({
+ workflowRunId: 'local-source-1',
+ });
+ expect(mocks.runAgentSignalWorkflow).not.toHaveBeenCalled();
+ expect(mocks.trigger).not.toHaveBeenCalled();
+
+ await vi.runAllTimersAsync();
+
+ expect(mocks.runAgentSignalWorkflow).toHaveBeenCalledOnce();
+ expect(mocks.runAgentSignalWorkflow).toHaveBeenCalledWith(
+ expect.objectContaining({ requestPayload: payload }),
+ expect.objectContaining({
+ createRuntimeGuardBackend: expect.any(Function),
+ executeSourceEvent: expect.any(Function),
+ }),
+ );
+
+ const dependencies = mocks.runAgentSignalWorkflow.mock.calls[0][1];
+ expect(dependencies.createRuntimeGuardBackend()).toBe(mocks.inMemoryRuntimeGuardBackend);
+
+ const executeSourceEvent = dependencies.executeSourceEvent;
+ const input = { sourceId: 'source-1' };
+ const context = { userId: 'user-1' };
+ const options = { runtimeGuardBackend: { kind: 'memory' } };
+
+ await executeSourceEvent(input, context, options);
+
+ expect(mocks.executeAgentSignalSourceEvent).toHaveBeenCalledWith(input, context, {
+ ...options,
+ store: mocks.inMemorySourceEventStore,
+ });
+ });
+
+ it('logs local workflow failures with correlation identifiers', async () => {
+ const error = new Error('local workflow failed');
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mocks.runAgentSignalWorkflow.mockRejectedValueOnce(error);
+
+ await AgentSignalWorkflow.triggerRun(createPayload());
+ await vi.runAllTimersAsync();
+
+ expect(consoleError).toHaveBeenCalledWith('[AgentSignal] Local workflow execution failed:', {
+ agentId: 'agent-1',
+ error,
+ sourceId: 'source-1',
+ userId: 'user-1',
+ workflowRunId: 'local-source-1',
+ });
+ });
+
+ it('serializes local workflow runs sharing the same scope', async () => {
+ let finishFirstRun: (() => void) | undefined;
+ const firstRun = new Promise<void>((resolve) => {
+ finishFirstRun = resolve;
+ });
+ mocks.runAgentSignalWorkflow
+ .mockImplementationOnce(() => firstRun)
+ .mockResolvedValueOnce({ success: true });
+
+ const firstPayload = createPayload();
+ const secondPayload = {
+ ...createPayload(),
+ sourceEvent: {
+ ...createPayload().sourceEvent,
+ sourceId: 'source-2',
+ },
+ };
+
+ await AgentSignalWorkflow.triggerRun(firstPayload);
+ await AgentSignalWorkflow.triggerRun(secondPayload);
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(mocks.runAgentSignalWorkflow).toHaveBeenCalledOnce();
+
+ finishFirstRun?.();
+ await vi.runAllTimersAsync();
+
+ expect(mocks.runAgentSignalWorkflow).toHaveBeenCalledTimes(2);
+ expect(mocks.runAgentSignalWorkflow.mock.calls[1][0]).toEqual(
+ expect.objectContaining({ requestPayload: secondPayload }),
+ );
+ });
+
+ it('keeps using Upstash Workflow when queue runtime is enabled', async () => {
+ mocks.appEnv.enableQueueAgentRuntime = true;
+
+ await expect(AgentSignalWorkflow.triggerRun(createPayload())).resolves.toEqual({
+ workflowRunId: 'workflow-1',
+ });
+
+ expect(mocks.trigger).toHaveBeenCalledOnce();
+ expect(mocks.runAgentSignalWorkflow).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/workflows/agentSignal/impls/index.ts b/apps/server/src/workflows/agentSignal/impls/index.ts
new file mode 100644
index 00000000000..8cf71751aad
--- /dev/null
+++ b/apps/server/src/workflows/agentSignal/impls/index.ts
@@ -0,0 +1 @@
+export { scheduleLocalAgentSignalRun } from './local';
diff --git a/apps/server/src/workflows/agentSignal/impls/local.ts b/apps/server/src/workflows/agentSignal/impls/local.ts
new file mode 100644
index 00000000000..72dbd81c8be
--- /dev/null
+++ b/apps/server/src/workflows/agentSignal/impls/local.ts
@@ -0,0 +1,86 @@
+import debug from 'debug';
+
+import type { AgentSignalWorkflowRunPayload } from '../types';
+
+const log = debug('lobe-server:workflows:agent-signal');
+const localRunQueues = new Map<string, Promise<void>>();
+
+const deferLocalRun = () =>
+ new Promise<void>((resolve) => {
+ setTimeout(resolve, 0);
+ });
+
+/**
+ * Schedules one non-durable Agent Signal workflow inside the current server process.
+ *
+ * Local Agent Runtime deliberately avoids QStash. Deferring execution lets the ingress request
+ * return before the pipeline starts, matching the foreground/background boundary of Upstash
+ * Workflow without pretending to provide its durability guarantees. Runs sharing a scope are
+ * chained to preserve the queue runtime's `parallelism: 1` behavior; otherwise a later local event
+ * can hit the first run's scope lock and be dropped instead of waiting.
+ */
+export const scheduleLocalAgentSignalRun = (
+ payload: AgentSignalWorkflowRunPayload,
+ headers: Headers,
+): { workflowRunId: string } => {
+ const workflowRunId = `local-${payload.sourceEvent.sourceId}`;
+ const logContext = {
+ agentId: payload.agentId,
+ sourceId: payload.sourceEvent.sourceId,
+ userId: payload.userId,
+ workflowRunId,
+ };
+
+ log('Scheduling local workflow payload=%O', logContext);
+
+ const previousRun = localRunQueues.get(payload.sourceEvent.scopeKey) ?? Promise.resolve();
+ const currentRun = previousRun
+ .catch(() => undefined)
+ .then(deferLocalRun)
+ .then(async () => {
+ try {
+ const [
+ { executeAgentSignalSourceEvent },
+ { inMemorySourceEventStore },
+ { inMemoryRuntimeGuardBackend },
+ { runAgentSignalWorkflow },
+ ] = await Promise.all([
+ import('@/server/services/agentSignal/orchestrator'),
+ import('@/server/services/agentSignal/store/adapters/memory/sourceEventStore'),
+ import('@/server/services/agentSignal/runtime/backend/memoryGuard'),
+ import('../run'),
+ ]);
+
+ await runAgentSignalWorkflow(
+ {
+ headers,
+ requestPayload: payload,
+ run: async (_stepId, handler) => handler(),
+ },
+ {
+ createRuntimeGuardBackend: () => inMemoryRuntimeGuardBackend,
+ executeSourceEvent: (input, context, options) =>
+ executeAgentSignalSourceEvent(input, context, {
+ ...options,
+ store: inMemorySourceEventStore,
+ }),
+ },
+ );
+ } catch (error) {
+ console.error('[AgentSignal] Local workflow execution failed:', {
+ ...logContext,
+ error,
+ });
+ }
+ });
+
+ localRunQueues.set(payload.sourceEvent.scopeKey, currentRun);
+
+ void currentRun.finally(() => {
+ if (localRunQueues.get(payload.sourceEvent.scopeKey) === currentRun) {
+ localRunQueues.delete(payload.sourceEvent.scopeKey);
+ }
+ });
+
+ return { workflowRunId };
+};
diff --git a/apps/server/src/workflows/agentSignal/index.ts b/apps/server/src/workflows/agentSignal/index.ts
index 00bf28f6806..991c3587d07 100644
--- a/apps/server/src/workflows/agentSignal/index.ts
+++ b/apps/server/src/workflows/agentSignal/index.ts
@@ -2,8 +2,8 @@ import debug from 'debug';
import { appEnv } from '@/envs/app';
import { injectActiveTraceHeaders } from '@/libs/observability/traceparent';
-import { workflowClient } from '@/libs/qstash';
+import { scheduleLocalAgentSignalRun } from './impls';
import type { AgentSignalWorkflowRunPayload } from './types';
export type { AgentSignalWorkflowRunPayload, AgentSignalWorkflowSourceEventInput } from './types';
@@ -32,18 +32,18 @@ const getWorkflowUrl = (path: string): string => {
* Agent Signal workflow trigger helper.
*
* Use when:
- * - Server-owned ingress wants to hand off execution to Upstash Workflow
+ * - Server-owned ingress wants to hand off execution to the configured background runtime
* - The caller already normalized the source event
*
* Expects:
* - `sourceEvent.scopeKey` is stable for the policy coordination scope
*
* Returns:
- * - Upstash workflow trigger metadata including `workflowRunId`
+ * - Queue mode returns Upstash workflow trigger metadata
+ * - Local mode returns a synthetic `workflowRunId` and executes in-process without durability
*/
export class AgentSignalWorkflow {
- static triggerRun(payload: AgentSignalWorkflowRunPayload) {
- const url = getWorkflowUrl(WORKFLOW_PATHS.run);
+ static async triggerRun(payload: AgentSignalWorkflowRunPayload) {
const traceHeaders = new Headers();
// NOTICE:
@@ -58,6 +58,13 @@ export class AgentSignalWorkflow {
// triggers or we stop relying on Workflow/QStash as the async hop.
injectActiveTraceHeaders(traceHeaders);
+ if (!appEnv.enableQueueAgentRuntime) {
+ return scheduleLocalAgentSignalRun(payload, traceHeaders);
+ }
+
+ const url = getWorkflowUrl(WORKFLOW_PATHS.run);
+ const { workflowClient } = await import('@/libs/qstash');
+
log('Triggering run workflow payload=%O', {
agentId: payload.agentId,
headers: Object.fromEntries(traceHeaders.entries()),