Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

📬 feat: Establish Background Continuation Admission (#15348)

Danny Avila16c2bb41493e
diff --git a/CONTEXT.md b/CONTEXT.md
index 2d6b137ad4..62c0566947 100644
--- a/CONTEXT.md
+++ b/CONTEXT.md
@@ -8,6 +8,7 @@
- **Subagent thread**: a durable, view-only child conversation owned by one parent conversation and subagent identity. A parent agent may continue it by stable `threadId`; each continuation uses a fresh execution lease restored from the canonical child transcript. It is not an ordinary human-writable chat.
- **Live subagent task owner**: the one API process holding a detached child execution, its abort controller, and its bounded control queue. Redis may route trusted poll/control envelopes to that owner, but it does not migrate or persist the executor; Mongo persists only the logical child thread and its continuation fence.
- **Subagent completion wakeup**: a durable internal `continue` trigger pre-registered before detached child execution so a process crash cannot lose the wakeup. Delivery defers until the child's terminal transcript is persisted, targets the initiating agent and exact parent response branch, carries task metadata rather than child output, waits for the parent generation to settle, and starts the parent turn that collects the result through the existing task store.
+- **Agent continuation preparation**: the single source-dispatch seam that resolves a durable `continue` delivery immediately before admission. Bound Event Actor work selects its binding adapter; internal completion work selects an adapter by stable source identity. Preparation may resolve authoritative input and branch state or settle already-consumed work, but it does not own source result truth, delivery ordering, or generation execution.
- **Subagent activity stream**: an observational, task-scoped live projection of bounded child progress for the currently open private panel. It may cross API replicas through Redis, never carries hidden reasoning text, and never controls or settles execution. The durable child thread remains canonical and its existing polling view is the fallback for missed or unavailable live events.
- **Agent event handling outcome**: the durable, generation-fenced result of a previously accepted event delivery. `started` proves generation admission; terminal states distinguish verified tool application, clean completion without action, failure, and cancellation. Transport success remains separate so an accepted event cannot masquerade as completed work.
- **Agent event expected action**: an optional source-declared tool name and bounded argument subset evaluated against host-observed completed run steps. It is evidence policy, not authorization and not a model-authored success claim.
diff --git a/api/server/services/Agents/triggers.js b/api/server/services/Agents/triggers.js
index 406d43553a..bcddf032f8 100644
--- a/api/server/services/Agents/triggers.js
+++ b/api/server/services/Agents/triggers.js
@@ -1,12 +1,18 @@
const {
createAgentTriggerService,
+ createAgentContinuationResolver,
createAgentEventContinueResolver,
createSubagentCompletionWakeupResolver,
+ SUBAGENT_COMPLETION_SOURCE,
GenerationJobManager,
} = require('@librechat/api');
const methods = require('~/models');
-const completionResolver = createSubagentCompletionWakeupResolver({
+const subagentCompletionAdapter = createSubagentCompletionWakeupResolver({
+ methods,
+ getGenerationJob: (conversationId) => GenerationJobManager.getJob(conversationId),
+});
+const eventActorAdapter = createAgentEventContinueResolver({
methods,
getGenerationJob: (conversationId) => GenerationJobManager.getJob(conversationId),
});
@@ -15,10 +21,9 @@ const service = createAgentTriggerService({
methods,
isPrincipalActive: methods.isAgentTriggerPrincipalActive,
supportsDetachedActionCompletion: () => GenerationJobManager.supportsDetachedAgentEventActions,
- prepareContinue: createAgentEventContinueResolver({
- methods,
- getGenerationJob: (conversationId) => GenerationJobManager.getJob(conversationId),
- fallback: completionResolver,
+ prepareContinue: createAgentContinuationResolver({
+ eventActor: eventActorAdapter,
+ internalSources: new Map([[SUBAGENT_COMPLETION_SOURCE, subagentCompletionAdapter]]),
}),
});
diff --git a/api/server/services/Agents/triggers.spec.js b/api/server/services/Agents/triggers.spec.js
index 6eeba98996..9aa6e88f3c 100644
--- a/api/server/services/Agents/triggers.spec.js
+++ b/api/server/services/Agents/triggers.spec.js
@@ -6,8 +6,10 @@ const mockGenerationJobManager = {
jest.mock('@librechat/api', () => ({
createAgentTriggerService: (...args) => mockCreateAgentTriggerService(...args),
+ createAgentContinuationResolver: jest.fn(() => jest.fn()),
createAgentEventContinueResolver: jest.fn(() => jest.fn()),
createSubagentCompletionWakeupResolver: jest.fn(() => jest.fn()),
+ SUBAGENT_COMPLETION_SOURCE: 'subagent-completion',
GenerationJobManager: mockGenerationJobManager,
}));
diff --git a/api/server/services/Endpoints/agents/initialize.js b/api/server/services/Endpoints/agents/initialize.js
index a60a17dc7a..aabb3c7e32 100644
--- a/api/server/services/Endpoints/agents/initialize.js
+++ b/api/server/services/Endpoints/agents/initialize.js
@@ -23,6 +23,7 @@ const {
getLazySubagentConfigId,
createStatefulCodeEnvironmentPolicyError,
buildSubagentThreadTaskConfig,
+ backgroundCompletionWakeupsEnabled,
} = require('@librechat/api');
const {
ResourceType,
@@ -157,6 +158,9 @@ const initializeClient = async ({
throw new Error('Endpoint option not provided');
}
const appConfig = req.config;
+ const completionWakeupsEnabled = backgroundCompletionWakeupsEnabled(
+ appConfig?.endpoints?.[EModelEndpoint.agents],
+ );
/** The normal controller resolves this once for timestamp anchoring. Reuse
* that trusted document for child-thread execution policy; resume and direct
* callers fall back to the same owner-scoped lookup. */
@@ -1330,13 +1334,13 @@ const initializeClient = async ({
? { tenantId: req.user.tenantId }
: {}),
},
- { completionWakeups: true },
+ { completionWakeups: completionWakeupsEnabled },
)
: undefined;
let hasExistingSubagentTask = false;
if (trustedSubagentTasks != null && !(subagentsAvailableForRun && hasSpawnableSubagent)) {
try {
- hasExistingSubagentTask = await subagentThreadTaskStore.hasTasks(
+ hasExistingSubagentTask = await trustedSubagentTasks.store.hasTasks(
trustedSubagentTasks.scopeId,
);
} catch (error) {
diff --git a/librechat.example.yaml b/librechat.example.yaml
index aacd68aa8c..162b17a0d1 100644
--- a/librechat.example.yaml
+++ b/librechat.example.yaml
@@ -570,6 +570,10 @@ endpoints:
# # uses its own bound listener; override only for an internal TLS/front-door route.
# eventDriven:
# # selfUrl: 'https://librechat.internal'
+ # # (optional) Automatic conversational delivery for supported completed background tasks.
+ # # Enabled by default; set false to keep background tools and subagents poll-only.
+ # backgroundTasks:
+ # completionWakeups: true
# # "run_in_background" makes Code Interpreter tools eligible by default and enables per-tool MCP opt-in.
# # "tool_intents" enables live model-written labels for native tools and opted-in MCP tools.
# # (optional) Require user approval before matching tool calls. Disabled by default.
diff --git a/packages/api/src/agents/subagentCompletionWakeup.ts b/packages/api/src/agents/subagentCompletionWakeup.ts
index 915351cc30..612e22c0c0 100644
--- a/packages/api/src/agents/subagentCompletionWakeup.ts
+++ b/packages/api/src/agents/subagentCompletionWakeup.ts
@@ -16,7 +16,7 @@ import { AgentTriggerExecutionError } from './triggers/host';
const WAKEUP_ADMISSION_DELAY_MS = 250;
/** SDK tasks time out after 30 minutes; this grace covers terminal persistence. */
const CHILD_READY_WAIT_MS = 35 * 60_000;
-const SOURCE_ID = 'subagent-completion';
+export const SUBAGENT_COMPLETION_SOURCE = 'subagent-completion';
const EVENT_TYPE = 'subagent.completion';
const MESSAGE_SELECT = 'messageId parentMessageId isCreatedByUser createdAt';
const TASK_SELECT =
@@ -88,7 +88,7 @@ function payloadRegistration(
): Pick<SubagentTaskWakeupRegistration, 'taskId' | 'threadId' | 'subagentType'> | null | undefined {
if (
envelope.event.source.type !== 'internal' ||
- envelope.event.source.id !== SOURCE_ID ||
+ envelope.event.source.id !== SUBAGENT_COMPLETION_SOURCE ||
envelope.event.type !== EVENT_TYPE
) {
return;
@@ -817,7 +817,7 @@ export function createSubagentCompletionWakeupHandler(
id: eventId,
type: EVENT_TYPE,
occurredAt: registration.createdAt,
- source: { id: SOURCE_ID, type: 'internal' },
+ source: { id: SUBAGENT_COMPLETION_SOURCE, type: 'internal' },
payload: {
taskId: registration.taskId,
threadId: registration.threadId,
diff --git a/packages/api/src/agents/subagentCrossReplica.integration.spec.ts b/packages/api/src/agents/subagentCrossReplica.integration.spec.ts
index 64703793d1..fc946ddfab 100644
--- a/packages/api/src/agents/subagentCrossReplica.integration.spec.ts
+++ b/packages/api/src/agents/subagentCrossReplica.integration.spec.ts
@@ -279,11 +279,11 @@ describeWithRedis('subagent cross-replica orchestration', () => {
);
ownerStore.configureActivityStream(await createActivityStream());
requesterStore.configureActivityStream(await createActivityStream());
- const config = buildSubagentThreadTaskConfig(ownerStore, {
- userId,
- tenantId,
- parentConversationId,
- });
+ const config = buildSubagentThreadTaskConfig(
+ ownerStore,
+ { userId, tenantId, parentConversationId },
+ { completionWakeups: true },
+ );
const releases: Array<() => void> = [];
const entered: Promise<void>[] = [];
@@ -313,7 +313,7 @@ describeWithRedis('subagent cross-replica orchestration', () => {
);
};
};
- const first = ownerStore.start(
+ const first = config.store.start(
taskRequest(
config.scopeId,
'first child task',
@@ -321,7 +321,7 @@ describeWithRedis('subagent cross-replica orchestration', () => {
childRun('First durable result.'),
),
);
- const second = ownerStore.start(
+ const second = config.store.start(
taskRequest(
config.scopeId,
'second child task',
diff --git a/packages/api/src/agents/subagentDelivery.spec.ts b/packages/api/src/agents/subagentDelivery.spec.ts
index 60ba967b56..ec036708a3 100644
--- a/packages/api/src/agents/subagentDelivery.spec.ts
+++ b/packages/api/src/agents/subagentDelivery.spec.ts
@@ -1,5 +1,22 @@
+import type { TAgentsEndpoint } from 'librechat-data-provider';
import type { PostToolUseHookInput } from '@librechat/agents';
-import { SUBAGENT_WAKEUP_GUIDANCE, createSubagentWakeupHandleHook } from './subagentDelivery';
+import {
+ SUBAGENT_WAKEUP_GUIDANCE,
+ backgroundCompletionWakeupsEnabled,
+ createSubagentWakeupHandleHook,
+} from './subagentDelivery';
+
+describe('background completion wakeup policy', () => {
+ it('defaults to automatic delivery and honors the administrator opt-out', () => {
+ expect(backgroundCompletionWakeupsEnabled(undefined)).toBe(true);
+ expect(backgroundCompletionWakeupsEnabled({} as TAgentsEndpoint)).toBe(true);
+ expect(
+ backgroundCompletionWakeupsEnabled({
+ backgroundTasks: { completionWakeups: false },
+ } as TAgentsEndpoint),
+ ).toBe(false);
+ });
+});
const hookSignal = new AbortController().signal;
diff --git a/packages/api/src/agents/subagentDelivery.ts b/packages/api/src/agents/subagentDelivery.ts
index 28fe3f7476..568a360d6a 100644
--- a/packages/api/src/agents/subagentDelivery.ts
+++ b/packages/api/src/agents/subagentDelivery.ts
@@ -1,6 +1,7 @@
import { Constants } from '@librechat/agents';
import { isEphemeralAgentId } from 'librechat-data-provider';
import type { HookCallback, PostToolUseHookOutput, SubagentTaskConfig } from '@librechat/agents';
+import type { TAgentsEndpoint } from 'librechat-data-provider';
export const SUBAGENT_COMPLETION_DELIVERY = 'wakeup';
@@ -12,6 +13,11 @@ export interface HostSubagentTaskConfig extends SubagentTaskConfig {
export const SUBAGENT_WAKEUP_GUIDANCE =
'Automatic completion delivery is enabled for this subagent task. Continue independent work if available; otherwise end this turn and the host will resume you when the task finishes. Do not repeatedly poll an unchanged running task. Use check_background_task only for explicit status or control, or as a fallback if automatic delivery is unavailable.';
+/** Automatic conversational completion is default-on and has one administrator opt-out. */
+export function backgroundCompletionWakeupsEnabled(config: TAgentsEndpoint | undefined): boolean {
+ return config?.backgroundTasks?.completionWakeups !== false;
+}
+
export function usesSubagentCompletionWakeups(
config: SubagentTaskConfig | undefined,
): config is HostSubagentTaskConfig {
diff --git a/packages/api/src/agents/subagentThreads.spec.ts b/packages/api/src/agents/subagentThreads.spec.ts
index 238bf02019..1eb1434693 100644
--- a/packages/api/src/agents/subagentThreads.spec.ts
+++ b/packages/api/src/agents/subagentThreads.spec.ts
@@ -285,14 +285,24 @@ beforeEach(async () => {
});
describe('SubagentThreadTaskStore', () => {
- it('records the host-selected automatic delivery contract only when wakeups are enabled', () => {
+ it('records the automatic delivery contract without hiding routed store operations', async () => {
const store = new SubagentThreadTaskStore(methods);
const scope = { userId: 'delivery-user', parentConversationId: randomUUID() };
-
- expect(buildSubagentThreadTaskConfig(store, scope).completionDelivery).toBeUndefined();
- expect(
- buildSubagentThreadTaskConfig(store, scope, { completionWakeups: true }).completionDelivery,
- ).toBe(SUBAGENT_COMPLETION_DELIVERY);
+ const pollOnly = buildSubagentThreadTaskConfig(store, scope);
+ const automatic = buildSubagentThreadTaskConfig(store, scope, { completionWakeups: true });
+ const automaticAgain = buildSubagentThreadTaskConfig(store, scope, {
+ completionWakeups: true,
+ });
+
+ expect(pollOnly.store).toBe(store);
+ expect(pollOnly.completionDelivery).toBeUndefined();
+ expect(automatic.store).toBe(automaticAgain.store);
+ expect(automatic.completionDelivery).toBe(SUBAGENT_COMPLETION_DELIVERY);
+ const automaticStore = automatic.store as SubagentThreadTaskStore;
+ expect(automaticStore.claimTask).toEqual(expect.any(Function));
+ expect(automaticStore.controlTask).toEqual(expect.any(Function));
+ await expect(automaticStore.hasTasks(automatic.scopeId)).resolves.toBe(false);
+ await expect(automaticStore.listTasks(automatic.scopeId)).resolves.toEqual([]);
});
it('maps one logical SDK thread to a durable, view-only LibreChat conversation', async () => {
@@ -356,8 +366,12 @@ describe('SubagentThreadTaskStore', () => {
expect(run).not.toHaveBeenCalled();
});
const store = new SubagentThreadTaskStore(methods, { onTaskPrepared });
- const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
- const started = store.start(
+ const config = buildSubagentThreadTaskConfig(
+ store,
+ { userId, parentConversationId },
+ { completionWakeups: true },
+ );
+ const started = config.store.start(
taskRequest(config.scopeId, {
parentRunId: 'parent-response-1',
parentAgentId: 'agent_parent_1',
@@ -383,6 +397,23 @@ describe('SubagentThreadTaskStore', () => {
});
});
+ it('keeps subagent completion delivery poll-only when wakeups are disabled', async () => {
+ const userId = 'poll-only-user';
+ const parentConversationId = randomUUID();
+ await saveParent(userId, parentConversationId);
+ const onTaskPrepared = jest.fn();
+ const store = new SubagentThreadTaskStore(methods, { onTaskPrepared });
+ const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
+
+ const started = config.store.start(taskRequest(config.scopeId));
+ await waitForSettled(store, config.scopeId, started);
+
+ expect(onTaskPrepared).not.toHaveBeenCalled();
+ expect(store.get(config.scopeId, requireAccepted(started).task.taskId)?.status).toBe(
+ 'completed',
+ );
+ });
+
it('streams child activity and closes only after the terminal result is durable', async () => {
const userId = 'activity-stream-user';
const parentConversationId = randomUUID();
@@ -654,8 +685,12 @@ describe('SubagentThreadTaskStore', () => {
const store = new SubagentThreadTaskStore(methods, {
onTaskPrepared: async () => Promise.reject(new Error('trigger queue unavailable')),
});
- const config = buildSubagentThreadTaskConfig(store, { userId, parentConversationId });
- const started = store.start(taskRequest(config.scopeId, { run }));
+ const config = buildSubagentThreadTaskConfig(
+ store,
+ { userId, parentConversationId },
+ { completionWakeups: true },
+ );
+ const started = config.store.start(taskRequest(config.scopeId, { run }));
await waitForSettled(store, config.scopeId, started);
expect(run).not.toHaveBeenCalled();
@@ -883,13 +918,22 @@ describe('SubagentThreadTaskStore', () => {
);
const firstWorker = new SubagentThreadTaskStore(methods, { onTaskPrepared: firstWakeup });
const secondWorker = new SubagentThreadTaskStore(methods, { onTaskPrepared: replayWakeup });
- const config = buildSubagentThreadTaskConfig(firstWorker, { userId, parentConversationId });
+ const config = buildSubagentThreadTaskConfig(
+ firstWorker,
+ { userId, parentConversationId },
+ { completionWakeups: true },
+ );
+ const replayConfig = buildSubagentThreadTaskConfig(
+ secondWorker,
+ { userId, parentConversationId },
+ { completionWakeups: true },
+ );
const firstRun = jest.fn(async () => ({
content: 'Original durable result.',
messages: [new HumanMessage('Run once.'), new AIMessage('Original durable result.')],
}));
const firstParentRunId = 'original-parent-response';
- const first = firstWorker.start(
+ const first = config.store.start(
taskRequest(config.scopeId, {
idempotencyKey: 'cross-worker-attempt',
parentRunId: firstParentRunId,
@@ -908,7 +952,7 @@ describe('SubagentThreadTaskStore', () => {
);
const replayRun = jest.fn(taskRequest(config.scopeId).run);
- const replay = secondWorker.start(
+ const replay = replayConfig.store.start(
taskRequest(config.scopeId, {
idempotencyKey: 'cross-worker-attempt',
requestFingerprint: 'same-inputs',
diff --git a/packages/api/src/agents/subagentThreads.ts b/packages/api/src/agents/subagentThreads.ts
index 5fed02cfdd..98f436b95f 100644
--- a/packages/api/src/agents/subagentThreads.ts
+++ b/packages/api/src/agents/subagentThreads.ts
@@ -15,6 +15,7 @@ import type {
SubagentTaskSnapshot,
SubagentTaskStartRequest,
SubagentTaskStartResult,
+ SubagentTaskStore,
SubagentUpdateEvent,
} from '@librechat/agents';
import type {
@@ -142,6 +143,10 @@ interface PreparedThread {
};
}
+interface HostSubagentTaskStartRequest extends SubagentTaskStartRequest {
+ completionDelivery?: typeof SUBAGENT_COMPLETION_DELIVERY;
+}
+
type ThreadMessage = Pick<
IMessage,
'messageId' | 'parentMessageId' | 'text' | 'createdAt' | 'subagentTranscript' | 'subagentTask'
@@ -3167,7 +3172,10 @@ export class SubagentThreadTaskStore extends InMemorySubagentTaskStore {
request: SubagentTaskStartRequest,
task: { taskId: string; parentRunId: string; createdAt: number },
): Promise<void> {
- if (this.onTaskPrepared == null) {
+ if (
+ this.onTaskPrepared == null ||
+ (request as HostSubagentTaskStartRequest).completionDelivery !== SUBAGENT_COMPLETION_DELIVERY
+ ) {
return;
}
await this.onTaskPrepared({
@@ -3416,13 +3424,47 @@ export function createSubagentThreadTaskStore(
return new SubagentThreadTaskStore(methods, options);
}
+type CompletionWakeupStore = SubagentTaskStore &
+ Pick<SubagentThreadTaskStore, 'claimTask' | 'controlTask' | 'hasTasks' | 'listTasks'>;
+
+const completionWakeupStores = new WeakMap<SubagentThreadTaskStore, CompletionWakeupStore>();
+
+function completionWakeupStore(store: SubagentThreadTaskStore): CompletionWakeupStore {
+ const existing = completionWakeupStores.get(store);
+ if (existing != null) {
+ return existing;
+ }
+ const adapter: CompletionWakeupStore = {
+ supportsThreadContinuation: store.supportsThreadContinuation,
+ start: (request) => {
+ const hostRequest: HostSubagentTaskStartRequest = {
+ ...request,
+ completionDelivery: SUBAGENT_COMPLETION_DELIVERY,
+ };
+ return store.start(hostRequest);
+ },
+ get: (scopeId, taskId) => store.get(scopeId, taskId),
+ list: (scopeId) => store.list(scopeId),
+ claim: (scopeId, taskId) => store.claim(scopeId, taskId),
+ control: (scopeId, taskId, command) => store.control(scopeId, taskId, command),
+ claimTask: (scopeId, taskId, invocationId) => store.claimTask(scopeId, taskId, invocationId),
+ controlTask: (scopeId, taskId, command, invocationId) =>
+ store.controlTask(scopeId, taskId, command, invocationId),
+ hasTasks: (scopeId) => store.hasTasks(scopeId),
+ listTasks: (scopeId) => store.listTasks(scopeId),
+ };
+ completionWakeupStores.set(store, adapter);
+ return adapter;
+}
+
export function buildSubagentThreadTaskConfig(
store: SubagentThreadTaskStore,
scope: Omit<SubagentThreadScope, 'version'>,
options: { completionWakeups?: boolean } = {},
): HostSubagentTaskConfig {
+ const taskStore = options.completionWakeups === true ? completionWakeupStore(store) : store;
return {
- store,
+ store: taskStore,
scopeId: serializeScope(scope),
...(options.completionWakeups === true
? { completionDelivery: SUBAGENT_COMPLETION_DELIVERY }
diff --git a/packages/api/src/agents/triggers/bindingResolver.ts b/packages/api/src/agents/triggers/bindingResolver.ts
index cfa964abf0..da8a9f0fc8 100644
--- a/packages/api/src/agents/triggers/bindingResolver.ts
+++ b/packages/api/src/agents/triggers/bindingResolver.ts
@@ -25,7 +25,6 @@ export interface AgentEventContinueResolverDeps {
| null
| undefined
>;
- fallback?: ContinueResolver;
}
function invalidBinding(message: string, retryable = false): AgentTriggerExecutionError {
@@ -42,15 +41,14 @@ function invalidBinding(message: string, retryable = false): AgentTriggerExecuti
export function createAgentEventContinueResolver({
methods,
getGenerationJob,
- fallback,
}: AgentEventContinueResolverDeps): ContinueResolver {
return async (
envelope: AgentContinueTriggerEnvelope,
- context: AgentTriggerDispatchContext,
+ _context: AgentTriggerDispatchContext,
): Promise<AgentTriggerContinuePreparation | undefined> => {
const { bindingId, sourceKeyId } = envelope.target;
if (bindingId == null || sourceKeyId == null) {
- return fallback?.(envelope, context);
+ return;
}
let binding;
let latestAssistant;
diff --git a/packages/api/src/agents/triggers/continuation.spec.ts b/packages/api/src/agents/triggers/continuation.spec.ts
new file mode 100644
index 0000000000..1cc9d3defa
--- /dev/null
+++ b/packages/api/src/agents/triggers/continuation.spec.ts
@@ -0,0 +1,82 @@
+import type { AgentContinueTriggerEnvelope } from './envelope';
+import type { AgentTriggerDispatchContext } from './dispatch';
+import { createAgentContinuationResolver } from './continuation';
+
+function envelope(options: {
+ sourceId: string;
+ sourceType?: 'internal' | 'webhook';
+ binding?: boolean;
+}): AgentContinueTriggerEnvelope {
+ return {
+ mode: 'continue',
+ requestId: 'request-1',
+ deliveryId: 'delivery-1',
+ receivedAt: 1,
+ principal: { userId: 'user-1' },
+ event: {
+ id: 'event-1',
+ type: 'task.completed',
+ occurredAt: 1,
+ source: { id: options.sourceId, type: options.sourceType ?? 'internal' },
+ },
+ target: {
+ agentId: 'agent-1',
+ conversationId: 'conversation-1',
+ parentMessageId: 'message-1',
+ ...(options.binding
+ ? { bindingId: 'evtbind_123', sourceKeyId: '507f191e810c19729de860eb' }
+ : {}),
+ },
+ input: 'Continue.',
+ } as AgentContinueTriggerEnvelope;
+}
+
+describe('agent continuation admission', () => {
+ const context = { idempotencyKey: 'delivery-1' } as AgentTriggerDispatchContext;
+
+ it('routes bound work exclusively through the event actor adapter', async () => {
+ const eventActor = jest.fn(async () => ({ status: 'settled' as const }));
+ const internal = jest.fn(async () => ({ status: 'settled' as const }));
+ const resolve = createAgentContinuationResolver({
+ eventActor,
+ internalSources: new Map([['completion', internal]]),
+ });
+
+ await expect(
+ resolve(envelope({ sourceId: 'completion', binding: true }), context),
+ ).resolves.toEqual({ status: 'settled' });
+ expect(eventActor).toHaveBeenCalledTimes(1);
+ expect(internal).not.toHaveBeenCalled();
+ });
+
+ it('routes internal work by its stable source identity', async () => {
+ const eventActor = jest.fn();
+ const internal = jest.fn(async () => ({ status: 'settled' as const }));
+ const resolve = createAgentContinuationResolver({
+ eventActor,
+ internalSources: new Map([['completion', internal]]),
+ });
+
+ await expect(resolve(envelope({ sourceId: 'completion' }), context)).resolves.toEqual({
+ status: 'settled',
+ });
+ expect(internal).toHaveBeenCalledTimes(1);
+ expect(eventActor).not.toHaveBeenCalled();
+ });
+
+ it('leaves unknown and external source-neutral continuations unchanged', async () => {
+ const eventActor = jest.fn();
+ const internal = jest.fn();
+ const resolve = createAgentContinuationResolver({
+ eventActor,
+ internalSources: new Map([['completion', internal]]),
+ });
+
+ expect(resolve(envelope({ sourceId: 'unknown' }), context)).toBeUndefined();
+ expect(
+ resolve(envelope({ sourceId: 'completion', sourceType: 'webhook' }), context),
+ ).toBeUndefined();
+ expect(eventActor).not.toHaveBeenCalled();
+ expect(internal).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/api/src/agents/triggers/continuation.ts b/packages/api/src/agents/triggers/continuation.ts
new file mode 100644
index 0000000000..2501ea81f4
--- /dev/null
+++ b/packages/api/src/agents/triggers/continuation.ts
@@ -0,0 +1,24 @@
+import type { AgentTriggerExecutionHostDeps } from './host';
+
+type ContinueResolver = NonNullable<AgentTriggerExecutionHostDeps['prepareContinue']>;
+
+export interface AgentContinuationResolverDeps {
+ eventActor: ContinueResolver;
+ internalSources: ReadonlyMap<string, ContinueResolver>;
+}
+
+/** Selects the single continuation adapter authorized for this delivery. */
+export function createAgentContinuationResolver({
+ eventActor,
+ internalSources,
+}: AgentContinuationResolverDeps): ContinueResolver {
+ return (envelope, context) => {
+ if (envelope.target.bindingId != null && envelope.target.sourceKeyId != null) {
+ return eventActor(envelope, context);
+ }
+ if (envelope.event.source.type !== 'internal') {
+ return;
+ }
+ return internalSources.get(envelope.event.source.id)?.(envelope, context);
+ };
+}
diff --git a/packages/api/src/agents/triggers/index.ts b/packages/api/src/agents/triggers/index.ts
index 6a17e7b6e3..036fb6f1a9 100644
--- a/packages/api/src/agents/triggers/index.ts
+++ b/packages/api/src/agents/triggers/index.ts
@@ -2,6 +2,7 @@ export * from './dispatch';
export * from './bindings';
export * from './actor';
export * from './bindingResolver';
+export * from './continuation';
export * from './delivery';
export * from './detachedAction';
export * from './envelope';
diff --git a/packages/data-provider/src/config.spec.ts b/packages/data-provider/src/config.spec.ts
index e154e83fe8..016a69db42 100644
--- a/packages/data-provider/src/config.spec.ts
+++ b/packages/data-provider/src/config.spec.ts
@@ -121,6 +121,34 @@ describe('agent event runtime config', () => {
});
});
+describe('agent background task config', () => {
+ it('enables completion wakeups by default when the policy block is present', () => {
+ const result = configSchema.safeParse({
+ version: '1.0',
+ endpoints: { agents: { backgroundTasks: {} } },
+ });
+
+ expect(result.success).toBe(true);
+ if (!result.success) {
+ return;
+ }
+ expect(result.data.endpoints?.agents?.backgroundTasks).toEqual({ completionWakeups: true });
+ });
+
+ it('accepts an administrator poll-only policy', () => {
+ const result = configSchema.safeParse({
+ version: '1.0',
+ endpoints: { agents: { backgroundTasks: { completionWakeups: false } } },
+ });
+
+ expect(result.success).toBe(true);
+ if (!result.success) {
+ return;
+ }
+ expect(result.data.endpoints?.agents?.backgroundTasks).toEqual({ completionWakeups: false });
+ });
+});
+
describe('speechTab schema', () => {
it.each(['browser', 'external', 'openai', 'azureOpenAI'])(
'accepts the speech-to-text engine "%s"',
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index bec45ea212..125ed07795 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -1049,6 +1049,13 @@ export const agentsEndpointSchema = baseEndpointSchema
selfUrl: z.string().url().optional(),
})
.optional(),
+ /** Conversational background-task delivery policy. Automatic completion wakeups are
+ * enabled unless an administrator explicitly restores poll-only behavior. */
+ backgroundTasks: z
+ .object({
+ completionWakeups: z.boolean().optional().default(true),
+ })
+ .optional(),
skills: z
.object({
maxCatalogSkills: z.number().int().min(1).max(100).optional(),