𤯠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(channel): configure each Agent's reply strategy and record its wake decisions (#22551)
Arvin Xu2f3181696c66
diff --git a/apps/server/src/routers/lambda/__tests__/channel.wakeConfig.test.ts b/apps/server/src/routers/lambda/__tests__/channel.wakeConfig.test.tsnew file mode 100644index 00000000000..c735349d385--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/channel.wakeConfig.test.ts@@ -0,0 +1,64 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {+ const { authedProcedure } = await import('@/libs/trpc/lambda');+ return { wsCompatProcedure: authedProcedure };+});++vi.mock('@/server/featureFlags', () => ({+ getServerFeatureFlagsStateFromRuntimeConfig: vi.fn(async () => ({ enableChannels: true })),+}));++const repository = vi.hoisted(() => ({+ updateChannelWakeConfig: vi.fn(),+ updateMemberWakeConfig: vi.fn(),+ wakeConfig: vi.fn(),+}));+vi.mock('@/server/services/channel/ChannelService', () => ({+ ChannelService: vi.fn(function () {+ return { repository };+ }),+}));++const { channelRouter } = await import('../channel');++const channelId = 'chn_abcdefghijkl';+const memberId = '3f2b1c4d-5e6f-4a1b-8c9d-0e1f2a3b4c5d';++describe('channelRouter reply strategy', () => {+ const caller = channelRouter.createCaller({ userId: 'user-1' } as any);++ beforeEach(() => vi.clearAllMocks());++ it('writes the channelās strategy, or a memberās own with its id', async () => {+ await caller.updateWakeConfig({ channelId, wake: { pace: 'calm' } });+ await caller.updateWakeConfig({ channelId, memberId, wake: { rules: { scope: 'none' } } });+ await caller.updateWakeConfig({ channelId, memberId, wake: null });++ expect(repository.updateChannelWakeConfig).toHaveBeenCalledWith(channelId, { pace: 'calm' });+ expect(repository.updateMemberWakeConfig).toHaveBeenNthCalledWith(1, channelId, memberId, {+ rules: { scope: 'none' },+ });+ expect(repository.updateMemberWakeConfig).toHaveBeenNthCalledWith(2, channelId, memberId, null);+ });++ it.each([+ { classifier: { threshold: 2 } },+ { rules: { scope: 'everywhere' } },+ { pace: 'fast' },+ { scheduler: { mode: 'enforce' } },+ { unknown: true },+ ])('refuses an invalid strategy instead of storing it: %j', async (wake) => {+ await expect(caller.updateWakeConfig({ channelId, wake: wake as never })).rejects.toMatchObject(+ { code: 'BAD_REQUEST' },+ );+ expect(repository.updateChannelWakeConfig).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/channel.ts b/apps/server/src/routers/lambda/channel.tsindex d085e58f545..8e261d52c0e 100644--- a/apps/server/src/routers/lambda/channel.ts+++ b/apps/server/src/routers/lambda/channel.ts@@ -1,13 +1,21 @@-import { CHANNEL_LIMITS } from '@lobechat/types';+import type { BotWakeDecisionPage } from '@lobechat/types';+import { CHANNEL_LIMITS, SIGNAL_DECISION_OUTCOMES } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';+import { SCOPE_READ_MAX_LIMIT, SignalDecisionModel } from '@/database/models/signalDecision';import { ChannelError } from '@/database/repositories/channel';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { ChannelService } from '@/server/services/channel/ChannelService';import { isChannelEnabled } from '@/server/services/channel/featureGate';+import {+ CHANNEL_WAKE_FOLLOWUP_REASONS,+ channelWakeScopeKey,+} from '@/server/services/channel/wakeRecords';+import { WakeConfigInputSchema } from '@/server/services/conversationWake/config';+import { pickWakeJudgeScore } from '@/server/services/conversationWake/judgeScore';import { channelHistoryProcedures } from './channelHistory';@@ -87,6 +95,85 @@ export const channelRouter = router({),success: true,})),+ /** The channel's reply strategy and each Agent member's own, as stored; admins only. */+ wakeConfig: channelProcedure.input(z.object({ channelId })).query(async ({ ctx, input }) => ({+ data: await ctx.channelService.repository.wakeConfig(input.channelId),+ success: true,+ })),+ /**+ * Replaces the channel's reply strategy, or with `memberId` that Agent member's own over it.+ * `null` returns it to the defaults. Validated by the same schema IM bots' rules are parsed with.+ */+ updateWakeConfig: channelProcedure+ .input(+ z.object({+ channelId,+ memberId: z.uuid().optional(),+ wake: WakeConfigInputSchema.nullable(),+ }),+ )+ .mutation(async ({ ctx, input }) => ({+ data: input.memberId+ ? await ctx.channelService.repository.updateMemberWakeConfig(+ input.channelId,+ input.memberId,+ input.wake,+ )+ : await ctx.channelService.repository.updateChannelWakeConfig(input.channelId, input.wake),+ success: true,+ })),+ /**+ * One Agent member's wake decisions in this channel, newest first, from the default read window+ * of `SignalDecisionModel.listByScope`: the same page an IM bot's wake records render.+ */+ listWakeDecisions: channelProcedure+ .input(+ z.object({+ channelId,+ cursor: z.object({ createdAt: z.string().datetime(), id: z.uuid() }).optional(),+ followupOnly: z.boolean().optional(),+ limit: z.number().int().min(1).max(SCOPE_READ_MAX_LIMIT).optional(),+ memberId: z.uuid(),+ offset: z.number().int().min(0).optional(),+ outcome: z.enum(SIGNAL_DECISION_OUTCOMES).optional(),+ }),+ )+ .query(async ({ ctx, input }): Promise<{ data: BotWakeDecisionPage; success: true }> => {+ const scope = await ctx.channelService.repository.memberWakeRecordScope(+ input.channelId,+ input.memberId,+ );+ if (!scope) return { data: { items: [], total: 0 }, success: true };++ const followups = new Set<string>(CHANNEL_WAKE_FOLLOWUP_REASONS);+ const page = await new SignalDecisionModel(+ ctx.serverDB,+ scope.userId,+ scope.workspaceId ?? undefined,+ ).listByScope({+ cursor: input.cursor,+ finalReasons: input.followupOnly ? [...CHANNEL_WAKE_FOLLOWUP_REASONS] : undefined,+ limit: input.limit,+ offset: input.offset,+ outcome: input.outcome,+ scopeKey: channelWakeScopeKey(input.channelId, input.memberId),+ });++ return {+ data: {+ items: page.items.map(({ labels: _labels, verdicts, ...item }) => ({+ ...item,+ agentLabel: null,+ followup: !!item.finalReason && followups.has(item.finalReason),+ judge: pickWakeJudgeScore(verdicts, item.finalReason) ?? null,+ userLabel: null,+ })),+ nextCursor: page.nextCursor,+ total: page.total,+ },+ success: true,+ };+ }),addUser: channelProcedure.input(z.object({ channelId, userId: z.string().min(1) })).mutation(async ({ ctx, input }) => ({diff --git a/apps/server/src/services/agentSignal/persistence/policy.ts b/apps/server/src/services/agentSignal/persistence/policy.tsindex f4ef77376a6..13b6231d4a1 100644--- a/apps/server/src/services/agentSignal/persistence/policy.ts+++ b/apps/server/src/services/agentSignal/persistence/policy.ts@@ -23,6 +23,8 @@ export const AGENT_SIGNAL_SOURCE_PERSISTENCE: Readonly<[AGENT_SIGNAL_SOURCE_TYPES.agentUserMessage]: 'never',// Chat messages are mostly noise; only the ones a wake decision was made about are worth a row.[AGENT_SIGNAL_SOURCE_TYPES.botMessageMerged]: 'on_decision',+ // Same for Channel: one row per Agent member the wake pipeline judged a message for.+ [AGENT_SIGNAL_SOURCE_TYPES.channelMessageRouted]: 'on_decision',[AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError]: 'never',[AGENT_SIGNAL_SOURCE_TYPES.clientGatewayRuntimeEnd]: 'never',[AGENT_SIGNAL_SOURCE_TYPES.clientGatewayStepComplete]: 'never',diff --git a/apps/server/src/services/channel/ChannelRoutingService.test.ts b/apps/server/src/services/channel/ChannelRoutingService.test.tsindex e785308fe97..0dec90df6de 100644--- a/apps/server/src/services/channel/ChannelRoutingService.test.ts+++ b/apps/server/src/services/channel/ChannelRoutingService.test.ts@@ -8,6 +8,7 @@ import {} from './ChannelRoutingService';const mocks = vi.hoisted(() => ({+ record: vi.fn(),classify: vi.fn(),countCall: vi.fn(),claim: vi.fn(),@@ -46,6 +47,7 @@ vi.mock('@/server/services/redis', () => ({redisService: { botWake: { countClassifierCall: mocks.countCall } },}));vi.mock('./notify', () => ({ notifyChannel: mocks.notify }));+vi.mock('./wakeRecords', () => ({ recordChannelWakeDecisions: mocks.record }));vi.mock('./queue', () => ({ wakeChannel: mocks.wake }));const input = {@@ -99,7 +101,7 @@ beforeEach(() => {mocks.resolveConfig.mockResolvedValue({ model: 'jev-1.14.0', provider: 'typesafe' });mocks.init.mockResolvedValue({ decide: mocks.decide });mocks.decide.mockResolvedValue(response(0.95, 0.05));- mocks.resolve.mockResolvedValue(true);+ mocks.resolve.mockResolvedValue({ recipients: ['coder'], status: 'assigned' });mocks.countCall.mockResolvedValue(1);});afterEach(() => {@@ -287,6 +289,52 @@ describe('routing worker', () => {);});+ it('records the membersā decisions once the routing result is applied, and only then', async () => {+ await run();+ expect(mocks.record).toHaveBeenCalledWith(+ {},+ 'channel',+ expect.objectContaining({ messageId: 'message' }),+ expect.objectContaining({ memberIds: ['coder'], status: 'assigned' }),+ expect.objectContaining({+ answers: response(0.95, 0.05).answers,+ judgements: expect.any(Array),+ }),+ { recipients: ['coder'], status: 'assigned' },+ );++ mocks.record.mockClear();+ mocks.resolve.mockResolvedValue(null);+ await run();+ expect(mocks.record).not.toHaveBeenCalled();+ });++ it('records the recipients the resolver delivered to, not the proposed members', async () => {+ // The reviewer left while the model was running, so only the coder was delivered to.+ mocks.resolve.mockResolvedValue({ recipients: ['coder'], status: 'assigned' });+ await run();+ expect(mocks.record).toHaveBeenCalledWith(+ {},+ 'channel',+ expect.anything(),+ expect.objectContaining({ memberIds: ['coder'], status: 'assigned' }),+ expect.anything(),+ { recipients: ['coder'], status: 'assigned' },+ );++ mocks.record.mockClear();+ mocks.resolve.mockResolvedValue({ recipients: [], status: 'unassigned' });+ await run();+ expect(mocks.record).toHaveBeenCalledWith(+ {},+ 'channel',+ expect.anything(),+ expect.objectContaining({ memberIds: ['coder'], status: 'assigned' }),+ expect.anything(),+ { recipients: [], status: 'unassigned' },+ );+ });+it('does not call the provider if another worker owns the attempt', async () => {mocks.claim.mockResolvedValue(null);await run();@@ -357,7 +405,7 @@ describe('routing worker', () => {});it('does not retry a stale write-back or create jobs itself', async () => {- mocks.resolve.mockResolvedValue(false);+ mocks.resolve.mockResolvedValue(null);await run();expect(mocks.resolve).toHaveBeenCalledTimes(1);expect(mocks.decide).toHaveBeenCalledTimes(1);diff --git a/apps/server/src/services/channel/ChannelRoutingService.ts b/apps/server/src/services/channel/ChannelRoutingService.tsindex b12c9fefd75..214f6144087 100644--- a/apps/server/src/services/channel/ChannelRoutingService.ts+++ b/apps/server/src/services/channel/ChannelRoutingService.ts@@ -23,6 +23,8 @@ import { wakeChannel } from './queue';import { resolveChannelRoutingConfig } from './routingConfig';import type { ChannelRoutingInput as RoutingInput, MemberWakeJudgement } from './wake';import { judgeMemberWake, toChannelJobWake } from './wake';+import type { ChannelRoutingTrace } from './wakeRecords';+import { recordChannelWakeDecisions } from './wakeRecords';export const CHANNEL_ROUTING_TIMEOUT_MS = 10_000;@@ -120,9 +122,20 @@ export class ChannelRoutingService {async ({ id }) => {const input = await this.routing.claim(channelId, id);if (!input) return;- const decision = await this.decide(channelId, input);- if (await this.executions.resolveRouting(channelId, id, input.attempt, decision))+ const trace: ChannelRoutingTrace = {};+ const decision = await this.decide(channelId, input, trace);+ const applied = await this.executions.resolveRouting(+ channelId,+ id,+ input.attempt,+ decision,+ );+ if (applied) {resolved += 1;+ // The resolver rechecks membership: record who was delivered to, not who was proposed,+ // so the wake history never reports a wake that no Agent received.+ await recordChannelWakeDecisions(this.db, channelId, input, decision, trace, applied);+ }},{ concurrency: 3 },);@@ -132,7 +145,11 @@ export class ChannelRoutingService {if (resolved) await wakeChannel(channelId);};- private async decide(channelId: string, input: RoutingInput): Promise<ChannelRoutingDecision> {+ private async decide(+ channelId: string,+ input: RoutingInput,+ trace: ChannelRoutingTrace = {},+ ): Promise<ChannelRoutingDecision> {if (!input.candidates.length) return { reason: 'No Agent can answer here', status: 'skipped' };if (input.fallback)return {@@ -153,6 +170,7 @@ export class ChannelRoutingService {// Bottom-up first: every member's own rules, the same pipeline an IM bot runs. Each model call// in them has its own short deadline, so this settles before the decision model's one starts.const judgements = await this.judgeMembers(channelId, input);+ trace.judgements = judgements;try {return await withTimeout(async () => {const wakes = (members: MemberWakeJudgement[]) =>@@ -232,6 +250,7 @@ export class ChannelRoutingService {user: input.userId,},);+ trace.answers = response.answers;const quiet = new Set(judgements.filter((judgement) => judgement.quiet).map(({ memberId }) => memberId),);diff --git a/apps/server/src/services/channel/README.md b/apps/server/src/services/channel/README.mdindex 56ae701e388..16b85085372 100644--- a/apps/server/src/services/channel/README.md+++ b/apps/server/src/services/channel/README.md@@ -70,6 +70,20 @@ for all members in parallel before the decision model's deadline starts. If arbireturns an unusable answer, the members' own wakes still stand. A follow-up whose run stopped on atool call (out of steps) fails; only a chosen silence, or no output at all, settles as `silent`.+### Configuring and auditing it++`channel.wakeConfig` reads the stored strategies and `channel.updateWakeConfig` replaces the+channel's, or with `memberId` one member's (`null` resets to the defaults). Admins only. Input is+validated strictly by `WakeConfigInputSchema`, the shape the bot settings parse, without a scheduler.+A member's strategy lives beside its environment in `channel_members.config`; replacing either+keeps the other.++Every routed (non-fallback) message records one `signal_decisions` row per judged member, through+the same `recordSignalDecision` as IM bots: source `lobehub`, type `channel.message.routed`,+pipeline `channel-wake@1`, scope `lobehub:<channelId>:<memberId>`, filed under the member's Agent+owner in the channel's workspace. Verdicts are the member's own rules plus the decision model's+answer (`channel:routing`). `channel.listWakeDecisions` pages them in the bots' wake-record shape.+## Decisions and recoveryA single `ModelRuntime.decide()` call asks a boolean question per eligible member. Probabilitiesdiff --git a/apps/server/src/services/channel/wakeRecords.test.ts b/apps/server/src/services/channel/wakeRecords.test.tsnew file mode 100644index 00000000000..155f589e17e--- /dev/null+++ b/apps/server/src/services/channel/wakeRecords.test.ts@@ -0,0 +1,186 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ChannelRoutingInput } from './wake';+import {+ CHANNEL_ROUTING_POLICY_ID,+ CHANNEL_WAKE_PIPELINE_VERSION,+ recordChannelWakeDecisions,+} from './wakeRecords';++const { record } = vi.hoisted(() => ({ record: vi.fn() }));+vi.mock('@/server/services/agentSignal/persistence/recordDecision', () => ({+ recordSignalDecision: record,+}));++const candidate = (memberId: string, ownerId: string | null = 'owner') => ({+ agentId: `agt-${memberId}`,+ description: '',+ memberId,+ name: memberId,+ ownerId,+ silentWakes: 0,+});++const input = {+ attempt: 1,+ candidates: [candidate('coder'), candidate('reviewer'), candidate('orphan', null)],+ fallback: false,+ message: 'Anyone around?',+ messageId: 'msg',+ threadId: null,+ workspaceId: 'ws',+} as unknown as ChannelRoutingInput;++const rowFor = (memberId: string) =>+ record.mock.calls+ .map(([, params]) => params)+ .find((params) => params.scopeKey.endsWith(memberId));++describe('Channel wake decision rows', () => {+ beforeEach(() => vi.clearAllMocks());++ it('files one row per judged member under its Agent owner, with why it woke', async () => {+ await recordChannelWakeDecisions(+ {} as never,+ 'chn',+ input,+ {+ memberIds: ['coder'],+ reason: 'Woken by its own rules',+ status: 'assigned',+ wakes: { coder: { kind: 'followup', reason: 'followup-window' } },+ },+ {+ answers: { reviewer: { probability: 0.1, type: 'boolean' } },+ judgements: [+ {+ excluded: false,+ initiation: { addressed: false, reason: 'followup-window' },+ memberId: 'coder',+ quiet: false,+ verdicts: [+ {+ confidence: 0.9,+ latencyMs: 3,+ mode: 'enforce',+ policyId: 'bot-wake:classifier',+ reason: 'addressed',+ verdict: 'allow',+ version: 1,+ },+ ],+ },+ { excluded: false, memberId: 'reviewer', quiet: false },+ ],+ },+ { recipients: ['coder'], status: 'assigned' },+ );++ // An Agent without an owner has nowhere to be read from.+ expect(record).toHaveBeenCalledTimes(2);+ expect(rowFor('coder')).toMatchObject({+ agentId: 'agt-coder',+ decision: {+ finalReason: 'followup-window',+ outcome: 'wake',+ pipelineVersion: CHANNEL_WAKE_PIPELINE_VERSION,+ verdicts: [expect.objectContaining({ policyId: 'bot-wake:classifier' })],+ },+ scopeKey: 'lobehub:chn:coder',+ signal: { externalId: 'chn:msg:coder:1', payload: { text: 'Anyone around?' } },+ userId: 'owner',+ workspaceId: 'ws',+ });+ expect(rowFor('reviewer')).toMatchObject({+ decision: {+ finalReason: 'not-chosen',+ outcome: 'skip',+ verdicts: [+ expect.objectContaining({+ confidence: 0.1,+ policyId: CHANNEL_ROUTING_POLICY_ID,+ verdict: 'deny',+ }),+ ],+ },+ });+ });++ it('records nothing for fallback routing, and survives a failed write', async () => {+ await recordChannelWakeDecisions(+ {} as never,+ 'chn',+ { ...input, fallback: true },+ { memberIds: ['coder'], reason: 'fallback', status: 'assigned' },+ {},+ { recipients: ['coder'], status: 'assigned' },+ );+ expect(record).not.toHaveBeenCalled();++ record.mockRejectedValue(new Error('db down'));+ vi.spyOn(console, 'error').mockImplementation(() => {});+ await expect(+ recordChannelWakeDecisions(+ {} as never,+ 'chn',+ input,+ { reason: 'Nobody', status: 'skipped' },+ {},+ { recipients: [], status: 'skipped' },+ ),+ ).resolves.toBeUndefined();+ expect(record).toHaveBeenCalledTimes(2);+ });++ it('records what was delivered, not what the decision proposed', async () => {+ await recordChannelWakeDecisions(+ {} as never,+ 'chn',+ input,+ {+ memberIds: ['coder', 'reviewer'],+ reason: 'Both fit',+ status: 'assigned',+ wakes: {+ coder: { kind: 'followup', reason: 'followup-window' },+ reviewer: { kind: 'followup', reason: 'followup-window' },+ },+ },+ { answers: { reviewer: { probability: 0.9, type: 'boolean' } } },+ // The reviewer left while the model was running, so it received nothing.+ { recipients: ['coder'], status: 'assigned' },+ );++ expect(rowFor('coder')).toMatchObject({+ decision: { finalReason: 'followup-window', outcome: 'wake' },+ });+ expect(rowFor('reviewer')).toMatchObject({+ decision: {+ finalReason: 'not-chosen',+ outcome: 'skip',+ verdicts: [expect.objectContaining({ verdict: 'deny' })],+ },+ });+ });++ it('reports an unassigned message as unassigned when no proposed member was delivered to', async () => {+ await recordChannelWakeDecisions(+ {} as never,+ 'chn',+ input,+ {+ memberIds: ['coder'],+ reason: 'Woken by its own rules',+ status: 'assigned',+ wakes: { coder: { kind: 'followup', reason: 'followup-window' } },+ },+ {},+ { recipients: [], status: 'unassigned' },+ );++ expect(rowFor('coder')).toMatchObject({+ decision: { finalReason: 'unassigned', outcome: 'skip' },+ });+ });+});diff --git a/apps/server/src/services/channel/wakeRecords.ts b/apps/server/src/services/channel/wakeRecords.tsnew file mode 100644index 00000000000..e1554476048--- /dev/null+++ b/apps/server/src/services/channel/wakeRecords.ts@@ -0,0 +1,153 @@+import { AGENT_SIGNAL_SOURCE_TYPES } from '@lobechat/agent-signal/source';+import type { DecisionResponse } from '@lobechat/model-runtime';+import type { ChannelMessageRoutingStatus, SignalDecisionVerdict } from '@lobechat/types';++import type {+ AppliedChannelRouting,+ ChannelRoutingDecision,+} from '@/database/repositories/channel';+import type { LobeChatDatabase } from '@/database/type';+import { recordSignalDecision } from '@/server/services/agentSignal/persistence/recordDecision';+import { ROUTING_JUDGE_POLICY_ID } from '@/server/services/conversationWake/judgeScore';++import type { ChannelRoutingInput, MemberWakeJudgement } from './wake';+import { CHANNEL_WAKE_PLATFORM } from './wake';++/** Revision of the Channel wake pipeline recorded on every decision. Bump when the judgement changes. */+export const CHANNEL_WAKE_PIPELINE_VERSION = 'channel-wake@1';++/** Policy id the decision model's answer is recorded under, beside the member's own rules. */+export const CHANNEL_ROUTING_POLICY_ID = ROUTING_JUDGE_POLICY_ID;++/** Every `finalReason` of a wake nobody asked for: the member may have stayed silent. */+export const CHANNEL_WAKE_FOLLOWUP_REASONS = [+ 'followup-window',+ 'in-duty',+ 'named-in-text',+ 'routing-uncertain',+] as const;++/** Longest message text stored in a signal payload. */+const MAX_PAYLOAD_TEXT_LENGTH = 4000;++/**+ * Where one Agent member's wake decisions are filed: a channel member is to Channel what a bot is+ * to an IM platform, so its decisions read like a bot's.+ */+export const channelWakeScopeKey = (channelId: string, memberId: string) =>+ `${CHANNEL_WAKE_PLATFORM}:${channelId}:${memberId}`;++/** What routing saw while it decided, for the decision rows. */+export interface ChannelRoutingTrace {+ answers?: DecisionResponse['answers'];+ judgements?: MemberWakeJudgement[];+}++const finalReasonFor = (+ decision: ChannelRoutingDecision,+ status: ChannelMessageRoutingStatus,+ chosen: boolean,+ memberId: string,+ judgement?: MemberWakeJudgement,+) => {+ if (chosen)+ return (+ (decision.status === 'assigned' ? decision.wakes?.[memberId]?.reason : undefined) ??+ 'routing-selected'+ );+ if (judgement?.excluded) return 'excluded';+ return status === 'unassigned' ? 'unassigned' : 'not-chosen';+};++/**+ * Records one decision row per Agent member a routed message was judged for: its own rules'+ * verdicts and the decision model's answer, with whether it was woken and why. Fallback routing+ * judged nothing and records nothing.+ *+ * Rows are filed under the member's Agent owner and the channel's workspace, which is how its+ * wake records are read back. Never throws: a failed row is logged and dropped, like the bots'.+ */+export const recordChannelWakeDecisions = async (+ db: LobeChatDatabase,+ channelId: string,+ input: ChannelRoutingInput,+ decision: ChannelRoutingDecision,+ trace: ChannelRoutingTrace,+ applied: AppliedChannelRouting,+) => {+ if (input.fallback) return;++ // One row per member, one at a time: at most 20 candidates reach routing.+ for (const candidate of input.candidates) {+ if (!candidate.ownerId) continue;+ const { memberId } = candidate;+ const judgement = trace.judgements?.find((entry) => entry.memberId === memberId);+ // Delivered, not proposed: a member dropped by the resolver's membership recheck got nothing.+ const chosen = applied.status === 'assigned' && applied.recipients.includes(memberId);+ const answer = trace.answers?.[memberId];+ const finalReason = finalReasonFor(decision, applied.status, chosen, memberId, judgement);+ const verdicts: SignalDecisionVerdict[] = [+ ...(judgement?.verdicts ?? []),+ ...(answer?.type === 'boolean'+ ? [+ {+ confidence: answer.probability,+ latencyMs: 0,+ mode: 'enforce' as const,+ policyId: CHANNEL_ROUTING_POLICY_ID,+ reason: decision.reason,+ verdict: chosen ? ('allow' as const) : ('deny' as const),+ version: 1,+ },+ ]+ : []),+ ];++ try {+ await recordSignalDecision(db, {+ agentId: candidate.agentId,+ decision: {+ finalReason,+ metadata: {+ stateSnapshot: {+ excluded: judgement?.excluded ?? false,+ lastReplyAt: candidate.lastReplyAt ?? null,+ quiet: judgement?.quiet ?? false,+ silentWakes: candidate.silentWakes,+ },+ },+ outcome: chosen ? 'wake' : 'skip',+ pipelineVersion: CHANNEL_WAKE_PIPELINE_VERSION,+ toTag: finalReason,+ verdicts,+ },+ scopeKey: channelWakeScopeKey(channelId, memberId),+ signal: {+ // A retried routing judges the message again, so the attempt is part of the key.+ externalId: `${channelId}:${input.messageId}:${memberId}:${input.attempt}`,+ metadata: {+ address: {+ channelId,+ memberId,+ messageId: input.messageId,+ ...(input.threadId && { threadId: input.threadId }),+ },+ entryPoint: 'routing',+ },+ payload: { text: input.message.slice(0, MAX_PAYLOAD_TEXT_LENGTH) },+ source: CHANNEL_WAKE_PLATFORM,+ sourceType: AGENT_SIGNAL_SOURCE_TYPES.channelMessageRouted,+ type: AGENT_SIGNAL_SOURCE_TYPES.channelMessageRouted,+ },+ userId: candidate.ownerId,+ workspaceId: input.workspaceId ?? undefined,+ });+ } catch (error) {+ console.error('[channel:wake-record]', {+ channelId,+ memberId,+ error: error instanceof Error ? error.name : 'RecordError',+ });+ }+ }+};diff --git a/apps/server/src/services/conversationWake/__tests__/judgeScore.test.ts b/apps/server/src/services/conversationWake/__tests__/judgeScore.test.tsindex 3a549a16b4f..d088a8e31c5 100644--- a/apps/server/src/services/conversationWake/__tests__/judgeScore.test.ts+++ b/apps/server/src/services/conversationWake/__tests__/judgeScore.test.ts@@ -28,6 +28,20 @@ describe('pickWakeJudgeScore', () => {).toEqual({ kind: 'duty', score: 0.81, verdict: 'allow' });});+ it('uses the Channel routing modelās score for a decision routing made', () => {+ const routing = v('channel:routing', 'allow', 0.83);+ expect(pickWakeJudgeScore([routing], 'routing-selected')).toEqual({+ kind: 'routing',+ score: 0.83,+ verdict: 'allow',+ });+ // A member its own rules woke shows the rule's model, with routing only as a fallback.+ expect(+ pickWakeJudgeScore([v(CLASSIFIER, 'allow', 0.9), routing], 'followup-window'),+ ).toMatchObject({ kind: 'addressed' });+ expect(pickWakeJudgeScore([routing], 'followup-window')).toMatchObject({ kind: 'routing' });+ });+it('uses the addressed classifier otherwise', () => {expect(pickWakeJudgeScore([v(DUTY, 'deny', 0.3), v(CLASSIFIER, 'allow', 0.74)], 'named-in-text'),diff --git a/apps/server/src/services/conversationWake/config.ts b/apps/server/src/services/conversationWake/config.tsindex 1afad28a053..3b2900cb8fa 100644--- a/apps/server/src/services/conversationWake/config.ts+++ b/apps/server/src/services/conversationWake/config.ts@@ -163,6 +163,49 @@ const SettingsSchema = z}).partial();+/**+ * A reply strategy as an API accepts it: the shape of {@link BotWakeConfig}, validated strictly so+ * a bad value is refused instead of silently falling back the way stored settings do. There is no+ * scheduler: only platforms with a delivery queue (IM bots) collect bursts.+ */+const strictMode = z.enum(['off', 'shadow', 'enforce']);+const probability = z.number().min(0).max(1);+const strictSeconds = z.number().int().min(0).max(86_400);+const strictIdList = z.array(z.string().trim().min(1)).max(MAX_BOT_WAKE_CHANNEL_LIST);+export const WakeConfigInputSchema = z+ .object({+ classifier: z.object({ mode: strictMode, threshold: probability }).partial().strict(),+ customInstructions: z.string().max(MAX_CUSTOM_INSTRUCTIONS_LENGTH),+ customInstructionsEnabled: z.boolean(),+ duties: z+ .object({+ helpfulThreshold: probability,+ mode: strictMode,+ text: z.string().max(MAX_DUTIES_LENGTH),+ threshold: probability,+ })+ .partial()+ .strict(),+ enabled: z.boolean(),+ mode: strictMode,+ pace: z.enum(BOT_WAKE_PACES),+ rules: z+ .object({+ allowChannels: strictIdList,+ denyChannels: strictIdList,+ maxSilentWakes: z.number().int().min(0).max(100),+ ownerPresenceSeconds: strictSeconds,+ scope: z.enum(['all', 'bot-threads', 'none']),+ windowSeconds: strictSeconds,+ })+ .partial()+ .strict(),+ })+ .partial()+ .strict();++export type WakeConfigInput = z.infer<typeof WakeConfigInputSchema>;+/*** The provider setting keys the channel settings form writes. The form renders every field of the* `settings` group flat, so the bot-wake options are flat keys there rather than one nesteddiff --git a/apps/server/src/services/conversationWake/judgeScore.ts b/apps/server/src/services/conversationWake/judgeScore.tsindex 9f5e64060c8..3fe41f21a85 100644--- a/apps/server/src/services/conversationWake/judgeScore.ts+++ b/apps/server/src/services/conversationWake/judgeScore.ts@@ -3,11 +3,18 @@ import type { BotWakeJudgeKind, BotWakeJudgeScore, SignalDecisionVerdict } fromimport { CLASSIFIER_POLICY_ID } from '@/server/services/conversationWake/policies/classifier';import { DUTY_POLICY_ID } from '@/server/services/conversationWake/policies/duty';+/** Policy id a routing decision model's answer is recorded under (Channel). */+export const ROUTING_JUDGE_POLICY_ID = 'channel:routing';+const KIND_BY_POLICY: Record<string, BotWakeJudgeKind> = {[CLASSIFIER_POLICY_ID]: 'addressed',[DUTY_POLICY_ID]: 'duty',+ [ROUTING_JUDGE_POLICY_ID]: 'routing',};+/** Decisions the routing model made, whose score is the one that counts. */+const ROUTING_REASONS = new Set(['not-chosen', 'routing-selected', 'routing-uncertain']);+/*** A verdict that carries no score: the model timed out or failed (`*-timeout`, `*-error: ā¦`), or* the duty judge abstained without asking it (a message too short, a reply to someone else).@@ -20,7 +27,8 @@ const isScored = (verdict: SignalDecisionVerdict) =>** Returns:* - the duty judge's score for an `in-duty` decision, since that is the one that woke the bot- * - otherwise the addressed classifier's, then the duty judge's, whichever scored+ * - the routing model's for a decision routing made (Channel: chosen, unsure, or not chosen)+ * - otherwise the addressed classifier's, then the duty judge's, then routing's, whichever scored* - `undefined` when no model scored (an @-mention, a command, a rule, a failed call)*/export const pickWakeJudgeScore = (@@ -31,7 +39,11 @@ export const pickWakeJudgeScore = (const byKind = (kind: BotWakeJudgeKind) =>scored.find((v) => KIND_BY_POLICY[v.policyId] === kind);const order: BotWakeJudgeKind[] =- finalReason === 'in-duty' ? ['duty', 'addressed'] : ['addressed', 'duty'];+ finalReason === 'in-duty'+ ? ['duty', 'addressed', 'routing']+ : finalReason && ROUTING_REASONS.has(finalReason)+ ? ['routing', 'addressed', 'duty']+ : ['addressed', 'duty', 'routing'];for (const kind of order) {const verdict = byKind(kind);diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex f6a0d98063e..a06ae5a88eb 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -476,6 +476,7 @@"channel.records.judge.deny": "under the threshold","channel.records.judge.duty": "Is it within its duties","channel.records.judge.hint": "{{judge}}: {{verdict}}",+ "channel.records.judge.routing": "Should it be the one to answer","channel.records.mark.correct": "Right call","channel.records.mark.failed": "Couldn't save your mark. Try again.","channel.records.mark.false_wake": "Shouldn't have woken",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex 1f37845f201..9c1e90ed9b8 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -476,6 +476,7 @@"channel.records.judge.deny": "ęŖč¾¾éå¼","channel.records.judge.duty": "å¤ęęÆå¦å±äŗå®ēčč“£","channel.records.judge.hint": "{{judge}}ļ¼{{verdict}}",+ "channel.records.judge.routing": "å¤ę评äøčÆ„ē±å®ę„åē","channel.records.mark.correct": "å¤ęę£ē”®","channel.records.mark.failed": "ę č®°ę²”äæåļ¼čÆ·éčÆ","channel.records.mark.false_wake": "äøčÆ„å¤é",diff --git a/packages/agent-signal/src/source/sourceTypes.ts b/packages/agent-signal/src/source/sourceTypes.tsindex 838261ca973..432f2248a9a 100644--- a/packages/agent-signal/src/source/sourceTypes.ts+++ b/packages/agent-signal/src/source/sourceTypes.ts@@ -10,6 +10,7 @@ export const AGENT_SIGNAL_SOURCE_TYPES = {agentSelfReflectionRequested: 'agent.self_reflection.requested',agentUserMessage: 'agent.user.message',botMessageMerged: 'bot.message.merged',+ channelMessageRouted: 'channel.message.routed',clientGatewayError: 'client.gateway.error',clientGatewayRuntimeEnd: 'client.gateway.runtime_end',clientGatewayStepComplete: 'client.gateway.step_complete',@@ -136,6 +137,14 @@ export interface AgentSignalSourcePayloadMap {serializedContext?: string;topicId?: string;};+ [AGENT_SIGNAL_SOURCE_TYPES.channelMessageRouted]: {+ agentId?: string;+ channelId: string;+ memberId: string;+ message: string;+ messageId: string;+ threadId?: string;+ };[AGENT_SIGNAL_SOURCE_TYPES.clientGatewayError]: {agentId?: string;/** Message the receipt or UI should attach to, usually the assistant response. */diff --git a/packages/database/src/repositories/channel/ChannelRoutingRepository.ts b/packages/database/src/repositories/channel/ChannelRoutingRepository.tsindex 67aaf6d88d9..49546e55421 100644--- a/packages/database/src/repositories/channel/ChannelRoutingRepository.ts+++ b/packages/database/src/repositories/channel/ChannelRoutingRepository.ts@@ -141,6 +141,7 @@ export class ChannelRoutingRepository {agentId: agents.id,agentTitle: agents.title,model: agents.model,+ ownerId: agents.userId,provider: agents.provider,description: channelMembers.description,agentDescription: agents.description,@@ -276,6 +277,7 @@ export class ChannelRoutingRepository {description: member.description || member.agentDescription || '',memberId: member.memberId,name: member.name || 'Agent',+ ownerId: member.ownerId,title: member.agentTitle ?? undefined,wake: member.config?.wake,silentWakes: 0,diff --git a/packages/database/src/repositories/channel/__tests__/ChannelRoutingRepository.test.ts b/packages/database/src/repositories/channel/__tests__/ChannelRoutingRepository.test.tsindex 5c458a9c0a5..d474f249c28 100644--- a/packages/database/src/repositories/channel/__tests__/ChannelRoutingRepository.test.ts+++ b/packages/database/src/repositories/channel/__tests__/ChannelRoutingRepository.test.ts@@ -58,8 +58,11 @@ describe('Channel routing input and lease', () => {expect(input?.candidates.map((item) => item.memberId)).toContain(coder.id);expect(await routing.claim(channel.id, message.id)).toBeNull();const decision = { memberIds: [coder.id], status: 'assigned' as const, reason: 'Fits' };- expect(await execution.resolveRouting(channel.id, message.id, 1, decision)).toBe(true);- expect(await execution.resolveRouting(channel.id, message.id, 1, decision)).toBe(false);+ expect(await execution.resolveRouting(channel.id, message.id, 1, decision)).toMatchObject({+ recipients: [coder.id],+ status: 'assigned',+ });+ expect(await execution.resolveRouting(channel.id, message.id, 1, decision)).toBeNull();expect(await jobsOf(db, message.id)).toHaveLength(1);expect(await routing.pending(channel.id)).toEqual([]);});@@ -114,7 +117,7 @@ describe('Channel routing input and lease', () => {reason: 'Late',status: 'assigned',}),- ).toBe(false);+ ).toBeNull();expect(await jobsOf(db, message.id)).toEqual([]);});@@ -136,7 +139,7 @@ describe('Channel routing input and lease', () => {reason: 'Late',status: 'assigned',}),- ).toBe(false);+ ).toBeNull();});it('does not read a message from another Channel', async () => {diff --git a/packages/database/src/repositories/channel/__tests__/remove.test.ts b/packages/database/src/repositories/channel/__tests__/remove.test.tsindex f7fd1a2e999..3f9caa21845 100644--- a/packages/database/src/repositories/channel/__tests__/remove.test.ts+++ b/packages/database/src/repositories/channel/__tests__/remove.test.ts@@ -136,7 +136,7 @@ describe('Channel soft deletion', () => {reason: 'Late result',status: 'assigned',}),- ).toBe(false);+ ).toBeNull();await expect(executions.publish(channel.id, running.id)).rejects.toMatchObject({code: 'CONFLICT',});diff --git a/packages/database/src/repositories/channel/__tests__/removeThread.test.ts b/packages/database/src/repositories/channel/__tests__/removeThread.test.tsindex 6e8d011ee0f..0c43763694d 100644--- a/packages/database/src/repositories/channel/__tests__/removeThread.test.ts+++ b/packages/database/src/repositories/channel/__tests__/removeThread.test.ts@@ -169,7 +169,7 @@ describe('Thread deletion', () => {reason: 'Late',status: 'assigned',}),- ).toBe(false);+ ).toBeNull();await expect(asOwner.retryRouting(channel.id, pending.id)).rejects.toMatchObject({code: 'NOT_FOUND',});diff --git a/packages/database/src/repositories/channel/__tests__/routingStop.test.ts b/packages/database/src/repositories/channel/__tests__/routingStop.test.tsindex 64a8dc87161..730450e0cd0 100644--- a/packages/database/src/repositories/channel/__tests__/routingStop.test.ts+++ b/packages/database/src/repositories/channel/__tests__/routingStop.test.ts@@ -40,7 +40,7 @@ describe('routing write-back', () => {reason: 'Coder owns this code',status: 'assigned',}),- ).toBe(true);+ ).toEqual({ recipients: [coder.id], status: 'assigned' });expect(await messageById(message.id)).toMatchObject({recipientMemberIds: [coder.id],@@ -73,7 +73,7 @@ describe('routing write-back', () => {reason: 'Late',status: 'assigned',});- expect(late).toBe(false);+ expect(late).toBeNull();expect(await jobsOf(db, message.id)).toEqual([]);});@@ -179,7 +179,7 @@ describe('stop', () => {reason: 'Late',status: 'assigned',}),- ).toBe(false);+ ).toBeNull();const [mainJob] = await jobsOf(db, root.id);const [threadJob] = await jobsOf(db, inThread.id);expect(mainJob.status).toBe('cancelled');diff --git a/packages/database/src/repositories/channel/__tests__/wakeConfig.test.ts b/packages/database/src/repositories/channel/__tests__/wakeConfig.test.tsnew file mode 100644index 00000000000..6ea223bcd82--- /dev/null+++ b/packages/database/src/repositories/channel/__tests__/wakeConfig.test.ts@@ -0,0 +1,99 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { agents, channelMembers, channels } from '../../../schemas';+import { createChannelFixture, deviceConfig } from './testUtils';++const db = await getTestDB();+const fixture = createChannelFixture(db, 'channel-wake-config');+beforeEach(fixture.setup);+afterEach(fixture.cleanup);++const memberConfig = async (memberId: string) => {+ const [member] = await db.select().from(channelMembers).where(eq(channelMembers.id, memberId));+ return member.config;+};++describe('a Channelās reply strategy', () => {+ it('stores the channelās and each memberās own, and resets them to the defaults', async () => {+ const team = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(team.channel.id, 'Coder', deviceConfig('/repo'));++ expect(await team.asOwner.wakeConfig(team.channel.id)).toEqual({+ channel: null,+ members: [{ memberId: agent.id, wake: null }],+ });++ await team.asOwner.updateChannelWakeConfig(team.channel.id, { pace: 'calm' });+ await team.asOwner.updateMemberWakeConfig(team.channel.id, agent.id, {+ rules: { scope: 'none' },+ });+ expect(await team.asOwner.wakeConfig(team.channel.id)).toEqual({+ channel: { pace: 'calm' },+ members: [{ memberId: agent.id, wake: { rules: { scope: 'none' } } }],+ });+ // The member's environment is untouched by its reply strategy.+ expect(await memberConfig(agent.id)).toEqual({+ deviceId: 'device-1',+ wake: { rules: { scope: 'none' } },+ workingDirectory: '/repo',+ });++ await team.asOwner.updateChannelWakeConfig(team.channel.id, null);+ await team.asOwner.updateMemberWakeConfig(team.channel.id, agent.id, null);+ const [channel] = await db.select().from(channels).where(eq(channels.id, team.channel.id));+ expect(channel.config).toBeNull();+ expect(await memberConfig(agent.id)).toEqual({+ deviceId: 'device-1',+ workingDirectory: '/repo',+ });+ });++ it('keeps a memberās reply strategy when its environment changes', async () => {+ const team = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(team.channel.id, 'Coder', deviceConfig('/repo'));+ await team.asOwner.updateMemberWakeConfig(team.channel.id, agent.id, { pace: 'active' });++ await team.asOwner.updateAgentEnvironment(team.channel.id, agent.id, {+ deviceId: 'device-1',+ workingDirectory: '/other',+ });++ expect(await memberConfig(agent.id)).toEqual({+ deviceId: 'device-1',+ wake: { pace: 'active' },+ workingDirectory: '/other',+ });+ });++ it('files a memberās wake records under its Agent owner in the channelās workspace', async () => {+ const team = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(team.channel.id, 'Coder');+ const [owner] = await db+ .select({ userId: agents.userId })+ .from(agents)+ .where(eq(agents.id, agent.agentId!));++ expect(await team.asOwner.memberWakeRecordScope(team.channel.id, agent.id)).toEqual({+ userId: owner.userId,+ workspaceId: team.channel.workspaceId,+ });+ await expect(+ team.asMember.memberWakeRecordScope(team.channel.id, agent.id),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });++ it('lets only admins read or change it', async () => {+ const team = await fixture.createTeamChannel();+ const agent = await fixture.addAgent(team.channel.id, 'Coder');++ for (const call of [+ () => team.asMember.wakeConfig(team.channel.id),+ () => team.asMember.updateChannelWakeConfig(team.channel.id, { pace: 'calm' }),+ () => team.asMember.updateMemberWakeConfig(team.channel.id, agent.id, { pace: 'calm' }),+ ])+ await expect(call()).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });+});diff --git a/packages/database/src/repositories/channel/execution.ts b/packages/database/src/repositories/channel/execution.tsindex b8a6b60e4a6..07563d1714d 100644--- a/packages/database/src/repositories/channel/execution.ts+++ b/packages/database/src/repositories/channel/execution.ts@@ -174,7 +174,7 @@ export class ChannelExecutionRepository {return true;});- /** Writes back a routing decision for `attempt`; false when the result is stale. */+ /** Writes back a routing decision for `attempt`; null when the result is stale. */resolveRouting = async (channelId: string,messageId: string,diff --git a/packages/database/src/repositories/channel/index.ts b/packages/database/src/repositories/channel/index.tsindex 588d909cadc..05bb7f638b6 100644--- a/packages/database/src/repositories/channel/index.ts+++ b/packages/database/src/repositories/channel/index.ts@@ -4,6 +4,7 @@ import { and, desc, eq, inArray, isNull, or, sql } from 'drizzle-orm';import { TrashModel } from '../../models/trash';import type { ChannelItem, ChannelJobItem, ChannelMessageItem } from '../../schemas';import {+ agents,channelJobs,channelMembers,channelMessages,@@ -43,7 +44,7 @@ export type { ChannelErrorCode } from './error';export { ChannelError } from './error';export { ChannelExecutionRepository } from './execution';export { ChannelHistoryRepository } from './history';-export type { ChannelRoutingDecision } from './routing';+export type { AppliedChannelRouting, ChannelRoutingDecision } from './routing';export type { ChannelSendInput } from './send';export type { ChannelStopScope } from './stop';export type { ChannelAccess, ChannelWriteOptions } from './types';@@ -66,6 +67,12 @@ const hasRole = (role: ChannelMemberRole | null, minRole: ChannelMemberRole) =>/** Characters of the latest message a Channel list item carries as its preview. */const LIST_PREVIEW_LENGTH = 200;+/** A member config with its reply strategy set, or without one when `wake` is empty. */+const withMemberWake = (+ config: ChannelMemberConfig,+ wake: Record<string, unknown> | null | undefined,+): ChannelMemberConfig => (wake ? { ...config, wake } : config);+export class ChannelRepository {private readonly workspaceId: string | null;@@ -217,10 +224,11 @@ export class ChannelRepository {this.write(channelId,async (tx) => {- await requireAgentMember(tx, channelId, memberId);+ const current = await requireAgentMember(tx, channelId, memberId);const [member] = await tx.update(channelMembers)- .set({ config: memberEnvironment(config) })+ // The environment is replaced; the member's reply strategy is not part of it.+ .set({ config: withMemberWake(memberEnvironment(config), current.config?.wake) }).where(eq(channelMembers.id, memberId)).returning();await audit(tx, channelId, 'member_environment_changed', memberId);@@ -229,6 +237,95 @@ export class ChannelRepository {{ minRole: 'admin' },);+ /**+ * The channel's reply strategy and each active Agent member's own, as stored (not parsed):+ * `null` means the defaults apply. Validation belongs to the shared wake schema in the caller.+ */+ wakeConfig = async (channelId: string) =>+ this.write(+ channelId,+ async (tx, { channel }) => {+ const members = await tx+ .select({ config: channelMembers.config, id: channelMembers.id })+ .from(channelMembers)+ .where(+ and(+ eq(channelMembers.channelId, channelId),+ eq(channelMembers.actorType, 'agent'),+ eq(channelMembers.status, 'active'),+ ),+ );+ return {+ channel: channel.config?.wake ?? null,+ members: members.map((member) => ({+ memberId: member.id,+ wake: member.config?.wake ?? null,+ })),+ };+ },+ { minRole: 'admin' },+ );++ /**+ * Whose records one Agent member's wake decisions are filed under: its Agent's owner, in the+ * channel's workspace. `null` when the Agent has no owner left to file them under.+ */+ memberWakeRecordScope = async (channelId: string, memberId: string) =>+ this.write(+ channelId,+ async (tx, { channel }) => {+ const member = await requireAgentMember(tx, channelId, memberId);+ const [agent] = await tx+ .select({ userId: agents.userId })+ .from(agents)+ .where(eq(agents.id, member.agentId));+ return agent?.userId ? { userId: agent.userId, workspaceId: channel.workspaceId } : null;+ },+ { minRole: 'admin' },+ );++ /** Replaces the channel's reply strategy; `null` returns it to the defaults. */+ updateChannelWakeConfig = async (channelId: string, wake: Record<string, unknown> | null) =>+ this.write(+ channelId,+ async (tx, { channel }) => {+ const { wake: _previous, ...rest } = channel.config ?? {};+ const config = wake ? { ...rest, wake } : rest;+ const [updated] = await tx+ .update(channels)+ .set({ config: Object.keys(config).length ? config : null })+ .where(eq(channels.id, channelId))+ .returning();+ await audit(tx, channelId, 'wake_config_changed', channelId, { reset: !wake });+ return updated.config?.wake ?? null;+ },+ { minRole: 'admin' },+ );++ /**+ * Replaces one Agent member's own reply strategy over the channel's; `null` removes it. Its+ * environment is kept as it is.+ */+ updateMemberWakeConfig = async (+ channelId: string,+ memberId: string,+ wake: Record<string, unknown> | null,+ ) =>+ this.write(+ channelId,+ async (tx) => {+ const current = await requireAgentMember(tx, channelId, memberId);+ const [member] = await tx+ .update(channelMembers)+ .set({ config: withMemberWake(memberEnvironment(current.config), wake) })+ .where(eq(channelMembers.id, memberId))+ .returning();+ await audit(tx, channelId, 'member_wake_config_changed', memberId, { reset: !wake });+ return member.config?.wake ?? null;+ },+ { minRole: 'admin' },+ );+rename = async (channelId: string, title: string) =>this.write(channelId,diff --git a/packages/database/src/repositories/channel/routing.ts b/packages/database/src/repositories/channel/routing.tsindex 53c0388a280..0fa483624bf 100644--- a/packages/database/src/repositories/channel/routing.ts+++ b/packages/database/src/repositories/channel/routing.ts@@ -34,10 +34,19 @@ const findMessage = async (tx: Transaction, channelId: string, messageId: stringreturn message;};+/** What a routing decision actually applied, after membership was rechecked. */+export interface AppliedChannelRouting {+ /** Members the message was delivered to; may be fewer than the decision proposed. */+ recipients: string[];+ /** Status the message ended with: `unassigned` when no proposed member could be delivered. */+ status: ChannelMessageRoutingStatus;+}+/*** Writes back a routing decision. Applies only while the message is still `pending` at the same* attempt, so a late answer can never overwrite a retry or a stop. Chosen members that are- * no longer candidates are dropped. Returns false when the result was stale.+ * no longer candidates are dropped. Returns null when the result was stale, otherwise what was+ * actually applied ā the decision itself may name members that received nothing.*/export const resolveRouting = async (tx: Transaction,@@ -45,9 +54,9 @@ export const resolveRouting = async (messageId: string,attempt: number,decision: ChannelRoutingDecision,-): Promise<boolean> => {+): Promise<AppliedChannelRouting | null> => {const message = await findMessage(tx, channelId, messageId);- if (message.routingStatus !== 'pending' || message.routingAttempt !== attempt) return false;+ if (message.routingStatus !== 'pending' || message.routingAttempt !== attempt) return null;const thread = await findThread(tx, channelId, message.threadId);const chosen =@@ -122,7 +131,7 @@ export const resolveRouting = async (status,});- return true;+ return { recipients: delivered, status };};/** Sends an `unassigned` message back to the decision model under a new attempt number. */diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex 295c09f672c..eb685da9caa 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -736,6 +736,7 @@ export default {'channel.records.column.score': 'Score','channel.records.judge.addressed': 'Is it meant for the bot','channel.records.judge.duty': 'Is it within its duties',+ 'channel.records.judge.routing': 'Should it be the one to answer','channel.records.judge.allow': 'over the threshold','channel.records.judge.deny': 'under the threshold','channel.records.judge.hint': '{{judge}}: {{verdict}}',diff --git a/packages/types/src/signal.ts b/packages/types/src/signal.tsindex 6ea34f98201..b804b90be32 100644--- a/packages/types/src/signal.ts+++ b/packages/types/src/signal.ts@@ -138,7 +138,11 @@ export const BOT_WAKE_USER_LABELS_BY_OUTCOME: Record<};/** Which model scored a wake decision: is the message for the bot, or within its duties. */-export type BotWakeJudgeKind = 'addressed' | 'duty';+/**+ * Which model scored a wake: the addressed classifier, the duty judge, or (Channel) the routing+ * decision model choosing among members.+ */+export type BotWakeJudgeKind = 'addressed' | 'duty' | 'routing';/** The model score behind a wake decision, as the owner sees it next to the decision. */export interface BotWakeJudgeScore {