Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
feat(agent-routing): wake only the named agents when a message is addressed
Xialie Zhuange96d5434cb47
diff --git a/server/src/__tests__/agents-routing.test.ts b/server/src/__tests__/agents-routing.test.tsnew file mode 100644index 0000000..a248dcf--- /dev/null+++ b/server/src/__tests__/agents-routing.test.ts@@ -0,0 +1,95 @@+/**+ * Message-level routing (#70).+ *+ * Narrowing a wake is the one mistake that is SILENT: an agent that should have+ * answered and was never woken leaves no reply, no typing indicator, and no+ * agent_runs row. So these tests spend most of their weight on the paths that+ * must NOT narrow, not on the happy one.+ *+ * Run: node --import tsx --test server/src/__tests__/agents-routing.test.ts+ */+import { test } from 'node:test'+import assert from 'node:assert/strict'+import { buildRouteRequest, parseRoute, recipientsForRoute } from '../agents/routing.js'++const ROOM = ['nova-12', 'iris-9', 'atlas-7']++// ── when the model is not even asked ─────────────────────────────────────────++test('@all is never narrowed', () => {+ const r = buildRouteRequest({ body: '@all standup in 5 @nova-12', conversationKind: 'group', candidates: ROOM, targets: ['nova-12'] })+ assert.equal(r.mode, 'each')+ assert.equal(r.instructions, undefined, 'a broadcast must not cost a model call')+})++test('a message that names nobody is never narrowed', () => {+ // The important one: narrowing with no targets would wake no one at all.+ const r = buildRouteRequest({ body: 'can someone take the Q3 deck?', conversationKind: 'group', candidates: ROOM, targets: [] })+ assert.equal(r.mode, 'each')+ assert.equal(r.instructions, undefined)+})++test('a DM is never narrowed', () => {+ const r = buildRouteRequest({ body: 'hey @nova-12', conversationKind: 'direct', candidates: ['nova-12'], targets: ['nova-12'] })+ assert.equal(r.mode, 'each')+})++test('naming the whole room costs no model call', () => {+ const r = buildRouteRequest({ body: '@nova-12 @iris-9 @atlas-7 thoughts?', conversationKind: 'group', candidates: ROOM, targets: ROOM })+ assert.equal(r.mode, 'each')+ assert.equal(r.instructions, undefined, 'there is nothing to save')+})++test('a named subset is the only case that asks the model', () => {+ const r = buildRouteRequest({ body: '@nova-12 draft the launch email', conversationKind: 'group', candidates: ROOM, targets: ['nova-12'] })+ assert.equal(r.mode, undefined)+ assert.match(r.instructions ?? '', /responseMode/)+ assert.match(r.input ?? '', /nova-12/)+ assert.match(r.input ?? '', /iris-9, atlas-7/, 'the model should see who else would be woken')+})++// ── parsing: anything unexpected means "change nothing" ───────────────────────++test('an explicit me is honoured', () => {+ assert.equal(parseRoute('{"responseMode": "me"}'), 'me')+})++test('each, unknown modes, junk and empty all read as each', () => {+ for (const raw of [+ '{"responseMode": "each"}',+ '{"responseMode": "one-of-us"}', // step two, not wired — must not narrow yet+ '{"responseMode": "nonsense"}',+ 'the model wrote prose instead',+ '',+ ]) {+ assert.equal(parseRoute(raw), 'each', `should not narrow on: ${JSON.stringify(raw)}`)+ }+})++test('me is found inside a fenced or chatty completion', () => {+ assert.equal(parseRoute('```json\n{"responseMode": "me", "why": "direct request"}\n```'), 'me')+})++// ── the narrowing rule itself ────────────────────────────────────────────────++test('me narrows to the named agents', () => {+ assert.deepEqual(recipientsForRoute('me', ROOM, ['nova-12']), ['nova-12'])+})++test('each leaves the room untouched', () => {+ assert.deepEqual(recipientsForRoute('each', ROOM, ['nova-12']), ROOM)+})++test('a target who is not a candidate never shrinks the room to nothing', () => {+ // Named someone who is muted out, departed, or is the author themselves.+ assert.deepEqual(recipientsForRoute('me', ROOM, ['someone-else']), ROOM)+})++test('only the candidate targets survive when some are not in the room', () => {+ assert.deepEqual(recipientsForRoute('me', ROOM, ['nova-12', 'ghost-1']), ['nova-12'])+})++test('one-of-us does not narrow yet', () => {+ // Step two in the issue; wiring it needs a lease, so it must be inert here.+ assert.deepEqual(recipientsForRoute('one-of-us', ROOM, ['nova-12']), ROOM)+})diff --git a/server/src/agents/llm-ledger.ts b/server/src/agents/llm-ledger.tsindex d0bafdb..7a4606b 100644--- a/server/src/agents/llm-ledger.ts+++ b/server/src/agents/llm-ledger.ts@@ -59,6 +59,9 @@ export type LlmCallPurpose =| 'completion-verify'| 'steer-summary'| 'convene-decision'+ // One decision per MESSAGE rather than per agent — it exists to avoid N+ // big-brain turns, so its own cost belongs next to theirs in the rollup.+ | 'message-routing'// One-shot utilities (rare per call, but unaccounted before this ledger).| 'palette'| 'gender'diff --git a/server/src/agents/model-policy.ts b/server/src/agents/model-policy.tsindex 4fc714b..ee35d61 100644--- a/server/src/agents/model-policy.ts+++ b/server/src/agents/model-policy.ts@@ -26,6 +26,7 @@ export type ModelPurpose =| 'agenda'| 'palette'| 'gender'+ | 'message-routing'const REAL_TASK_PURPOSES: ReadonlySet<ModelPurpose> = new Set<ModelPurpose>(['agent-turn',diff --git a/server/src/agents/routing.ts b/server/src/agents/routing.tsnew file mode 100644index 0000000..218ef57--- /dev/null+++ b/server/src/agents/routing.ts@@ -0,0 +1,126 @@+/**+ * Message-level routing: does an ordinary human group message need EVERY agent+ * in the room to wake up, or is it addressed at specific people?+ *+ * Today the scheduler picks recipients purely by membership, so a five-agent+ * room pays five big-brain turns for `@nova draft the launch email` — and+ * production measures ~26% of group wakes producing no reply at all.+ *+ * The decision is deliberately shaped so the model has the SMALLEST possible+ * job. Targets are derived deterministically (an exact @mention, a quote-reply)+ * — the cerebellum only says whether the message is aimed at those people+ * ("me") or at the room ("each"). It never picks who.+ *+ * Everything here fails OPEN. Narrowing a wake is the one mistake that is+ * silent: an agent that should have answered and was never woken leaves no+ * reply, no typing indicator, and no agent_runs row. So every uncertainty —+ * no targets, an @all, a model error, an unparseable answer — resolves to+ * today's full fan-out.+ */+import type { ResponseMode } from './triage-core.js'++/** `@all` is a broadcast: it must never be narrowed, whatever else the message+ * says. Same token rule the turn prompt uses to tag a broadcast. */+const ALL_MENTION_RE = /(?<![\w@])@all(?![\w-])/i++export interface RouteRequest {+ /** Set when the answer is known WITHOUT a model call. */+ mode?: ResponseMode+ /** Set when a model call is needed. */+ instructions?: string+ input?: string+}++/** Decide the route, or build the request that decides it.+ *+ * `candidates` is the set of agents the scheduler would wake today;+ * `targets` is the deterministically-addressed subset of them. */+export function buildRouteRequest(args: {+ body: string+ conversationKind: string+ candidates: readonly string[]+ targets: readonly string[]+}): RouteRequest {+ // A broadcast is for everyone, by definition.+ if (ALL_MENTION_RE.test(args.body)) return { mode: 'each' }+ // A DM has one recipient; there is nothing to narrow and the existing+ // human-DM triage note already covers it.+ if (args.conversationKind === 'direct') return { mode: 'each' }+ // Nothing to narrow TO. This is the important one: if the message names+ // nobody, narrowing would wake no one at all.+ if (args.targets.length === 0) return { mode: 'each' }+ // Narrowing saves nothing when the targets already are the whole room.+ if (args.targets.length >= args.candidates.length) return { mode: 'each' }++ return {+ instructions: [+ 'You route ONE message in a team chat where some teammates are AI agents.',+ 'The message explicitly names one or more agents. Decide whether it is aimed at THEM, or at the room.',+ 'Answer "me" when the named agents are the ones expected to act or reply — a direct request, an assignment, a question put to them.',+ 'Answer "each" when the whole room is still expected to engage — an open question that merely cites someone, a broadcast, a roll call, a request for several independent opinions.',+ 'When you are unsure, answer "each". Waking an extra agent costs tokens; failing to wake the right one loses the message.',+ 'Respond ONLY with a single JSON object: {"responseMode": "me"|"each"}.',+ ].join('\n'),+ input: [+ `Named agents: ${args.targets.join(', ')}`,+ `Other agents in the room: ${args.candidates.filter((c) => !args.targets.includes(c)).join(', ') || '(none)'}`,+ '',+ 'Message:',+ args.body.slice(0, 2000),+ ].join('\n'),+ }+}++/** Parse the router's answer. Anything unexpected — malformed JSON, a mode we+ * don't know, an empty completion — reads as `each`, i.e. change nothing. */+export function parseRoute(raw: string): ResponseMode {+ const match = raw.match(/"responseMode"\s*:\s*"(me|each|one-of-us)"/i)+ const mode = match?.[1]?.toLowerCase()+ return mode === 'me' ? 'me' : 'each'+}++/** The recipients to actually wake. Separated from the model call so the+ * narrowing rule itself is testable without one.+ *+ * Returns `candidates` unchanged unless the route is `me` AND every target is+ * a real candidate — a target that is not in the wake set (departed, muted out,+ * the author themselves) must never shrink the room to nothing. */+export function recipientsForRoute(+ mode: ResponseMode,+ candidates: readonly string[],+ targets: readonly string[],+): string[] {+ if (mode !== 'me') return [...candidates]+ const narrowed = targets.filter((t) => candidates.includes(t))+ return narrowed.length > 0 ? narrowed : [...candidates]+}++/** Run the router on the cloud SMALL model. Returns `each` — i.e. today's+ * behaviour — on any failure, including a model that is rate-limited or down.+ * Tracked so the call lands in llm_calls with purpose='message-routing' and+ * its cost is visible next to the turns it is meant to save. */+export async function routeMessage(args: {+ companyId: string | null+ body: string+ conversationKind: string+ candidates: readonly string[]+ targets: readonly string[]+}): Promise<ResponseMode> {+ const req = buildRouteRequest(args)+ if (req.mode) return req.mode+ try {+ const { getTrackedLlmClient } = await import('./llm-ledger.js')+ const { supportModel } = await import('./model-policy.js')+ const client = await getTrackedLlmClient({ purpose: 'message-routing', companyId: args.companyId })+ const r = await client.responses.create({+ model: supportModel(),+ instructions: req.instructions,+ input: req.input ?? '',+ max_output_tokens: 200,+ })+ return parseRoute(r.output_text ?? '')+ } catch (err) {+ console.warn(`[routing] router unavailable; waking everyone: ${err instanceof Error ? err.message : String(err)}`)+ return 'each'+ }+}diff --git a/server/src/agents/scheduler.ts b/server/src/agents/scheduler.tsindex 5c9dc31..4666210 100644--- a/server/src/agents/scheduler.ts+++ b/server/src/agents/scheduler.ts@@ -32,6 +32,7 @@ import { deliver as deliverWake, deliverSteer, type PollWakeBrief } from './runtimport { inprocClient, isAgentBusy } from './runtime/inproc-client.js'import { classifyInboxTriage, type InboxTriageVerdict } from './inbox-triage.js'import type { AgentTurnOptions } from './turn.js'+import { recipientsForRoute, routeMessage } from './routing.js'import { Semaphore } from '../concurrency.js'/** Bounds how many recipients the wake fan-out triages + wakes at once@@ -602,6 +603,40 @@ async function wake(payload: MessageNewEvent): Promise<void> {}}+ // ROUTING (#70). A human message that explicitly NAMES agents is usually for+ // them, and waking the rest of the room costs a full big-brain turn each to+ // reach "not mine" — production measures ~26% of group wakes replying with+ // nothing. Ask the cerebellum ONCE per message (not once per agent) whether the+ // named agents are the intended audience, and narrow only then.+ //+ // Deliberately conservative, because narrowing is the one mistake that is+ // SILENT — a agent that should have answered and was never woken leaves no+ // reply, no typing indicator, no agent_runs row. So this only ever runs for a+ // human-authored group message with a real named subset, and every uncertainty+ // (@all, no targets, a model error, an unparseable answer) keeps today's full+ // fan-out. See routing.ts.+ if (!authorIsAgent && (conversation?.kind ?? 'group') !== 'direct' && recipients.length > 1) {+ const targets = [+ ...mentionedAgentIds(messageBody, recipients),+ ...(quotedAuthorId && recipients.includes(quotedAuthorId) ? [quotedAuthorId] : []),+ ]+ const uniqueTargets = [...new Set(targets)]+ if (uniqueTargets.length > 0) {+ const mode = await routeMessage({+ companyId: payload.companyId ?? null,+ body: messageBody,+ conversationKind: conversation?.kind ?? 'group',+ candidates: recipients,+ targets: uniqueTargets,+ })+ const routed = recipientsForRoute(mode, recipients, uniqueTargets)+ if (routed.length !== recipients.length) {+ console.log(`[scheduler] routed ${conversationId} to ${routed.join(', ')} (mode=${mode}, ${recipients.length - routed.length} wake(s) avoided)`)+ }+ recipients = routed+ }+ }+// Always parallel fan-out. We tried a scheduler-side serial queue// for @all (stagger → event-driven Redis state machine) — both// worked mechanically but felt like nothing a real team would do.