Open-source AI coworkers that each get a computer of their own: a browser, files and tools, with every action decided before it happens and recorded after. Bring any AG-UI agent.
Route to the coworker somebody named, and stop building a Bot four ways (#296)
Jerel Velardef4bc60bf9b12
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 242ecf1e..a824d9a4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,18 +8,19 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged.## Unreleased-- A cancellation the native host never collected is now dropped instead of being reported as- pending forever. Every timed-out, stopped or revoked host operation queues a cancel for the desktop- worker, and only that worker ever removed it: a worker that stopped polling left the entry in- memory for the life of the process, so the Host access panel showed an operation that could never- finish. A desktop that reconnects within the operation timeout is still told to stop.-- A Bot's shell now honours a Stop that landed before the command was spawned, not only one that- arrives afterwards. A person who pressed Stop in the window between the request reaching the- computer and the command starting got no answer until that command finished on its own.-- A file download refused because the computer's response carried no usable byte length now releases- the connection before reporting the refusal. The unread body could be as large as the whole- download budget, so a computer reached through a proxy that re-chunks left a transfer running and a- connection checked out of the pool on every attempt.+### A coworker the message speaks to is routed to without asking a model++Addressing a coworker by name went to the intent router like any other message, so the deployment+paid a model call to be told what the person had already said, and sometimes was told something+else. A message that speaks to a coworker by its full name now routes straight to them: it opens+with the name ("Risk Analyst, please check this"), names it with `@`, or asks it ("ask Risk Analyst+to review this"). It is recorded as `matched a coworker’s name in the message` with+`viaNameMatch: true` on the same `channel.routed` row. A name in passing ("don't send this to Risk+Analyst") and a word that only ends a name ("review this contract", "my meeting notes") still go+to the router. When the message addresses more than one coworker, or two share the addressed name,+it is refused with distinct labels, and the composer keeps the draft and asks the person to choose+instead of starting the default coworker. Explicit picker choices still use `viaMention: true`.+### A Bot's turn in a group is no longer offered coordination tools it cannot callA Bot answering another Bot in a group conversation was offered `ask_person`, and `message_bot`diff --git a/app/src/lib/channels/route.ts b/app/src/lib/channels/route.tsindex e1f4a3fa..a214429a 100644--- a/app/src/lib/channels/route.ts+++ b/app/src/lib/channels/route.ts@@ -1,4 +1,4 @@-import { client } from "@/lib/client";+import { tryClient } from "@/lib/client";/*** Which coworker a message should go to.@@ -6,8 +6,8 @@ import { client } from "@/lib/client";* The server reads the roster for the person asking and picks by what each coworker is for, so this* can only ever return a coworker they are already allowed to reach. `fallback` is true when it is* the default rather than an inferred match, which the caller can say out loud. A thrown error here- * is not fatal: the caller falls back to the default coworker, which is exactly what the server- * does too.+ * permits the caller to fall back to the default coworker. An ambiguous name instead asks the+ * person to choose and must stop the send.** Pass `agentId` when the draft named somebody with `@`. Nothing is inferred in that case and no* model is called; the call exists so the choice reaches the audit trail, which otherwise had a row@@ -21,6 +21,9 @@ export type RoutingDecision = {viaMention: boolean;};+/** A routing decision that must be resolved before a conversation can start. */+export class CoworkerRoutingRefusedError extends Error {}+/*** The most of a message `POST /api/route` reads, and a message's opening cut to it.*@@ -49,10 +52,29 @@ export async function routeMessage(agentId?: string,): Promise<RoutingDecision> {const asked = routingText(text);- const response = await client("/api/route", {+ const response = await tryClient("/api/route", {method: "POST",body: agentId ? { text: asked, agentId } : { text: asked },- fallback: "Could not choose a coworker.",});+ if (!response.ok) {+ const body = (await response.json().catch(() => null)) as {+ error?: unknown;+ names?: unknown;+ } | null;+ const message =+ typeof body?.error === "string"+ ? body.error+ : "Could not choose a coworker.";+ if (+ response.status === 409 &&+ Array.isArray(body?.names) &&+ body.names.every((name) => typeof name === "string")+ ) {+ throw new CoworkerRoutingRefusedError(+ `${message} ${body.names.join(", ")}. Choose one with @.`,+ );+ }+ throw new Error(message);+ }return (await response.json()) as RoutingDecision;}diff --git a/app/src/routes/_authed/_app/index.tsx b/app/src/routes/_authed/_app/index.tsxindex 647ed852..792a9537 100644--- a/app/src/routes/_authed/_app/index.tsx+++ b/app/src/routes/_authed/_app/index.tsx@@ -15,7 +15,10 @@ import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";import { Skeleton } from "@/components/ui/skeleton";import { defaultAgentProfile } from "@/lib/agents/default-agent";import { agentListQueryOptions, isSharedWithYou } from "@/lib/agents/queries";-import { routeMessage } from "@/lib/channels/route";+import {+ CoworkerRoutingRefusedError,+ routeMessage,+} from "@/lib/channels/route";import { useStartChannel } from "@/lib/channels/start";import { appConfig } from "@/lib/generated/application-config";@@ -72,7 +75,9 @@ function RouteComponent() {let agentId: string | undefined;try {agentId = (await routeMessage(draft.text)).agentId;- } catch {+ } catch (caught) {+ if (caught instanceof CoworkerRoutingRefusedError)+ throw caught;agentId = fallback?.id;}if (!agentId) return;diff --git a/app/tests/home-fallback-routing.test.tsx b/app/tests/home-fallback-routing.test.tsxindex e0d0ff42..eec57dd9 100644--- a/app/tests/home-fallback-routing.test.tsx+++ b/app/tests/home-fallback-routing.test.tsx@@ -168,3 +168,35 @@ test("/ keeps a successful route decision ahead of the fallback", async () => {await waitFor(() => expect(starts).toEqual([["shared-public"]]));});++for (const refusal of [+ {+ status: 409,+ body: {+ error: "More than one coworker matches that name.",+ names: ["Data Analyst", "Risk Analyst"],+ },+ message: "Data Analyst, Risk Analyst",+ },+]) {+ test(`routing refusal ${refusal.status} preserves the draft and shows the explanation without starting a fallback`, async () => {+ const starts: string[][] = [];+ installHomeRoutingFetch({+ routeResponse: Response.json(refusal.body, { status: refusal.status }),+ starts,+ });+ const view = renderHome(+ queryClientWithAgents([+ agent({ id: "default", name: "Default", visibility: "public" }),+ ]),+ );+ await submitHomeMessage(view, "ask analyst");+ await waitFor(() =>+ expect(view.getByRole("alert").textContent).toContain(refusal.message),+ );+ expect(starts).toEqual([]);+ expect(view.getByRole("textbox", { name: "Message" }).textContent).toBe(+ "ask analyst",+ );+ });+}diff --git a/app/tests/route-long-message.test.ts b/app/tests/route-long-message.test.tsindex a1d97372..9db45d85 100644--- a/app/tests/route-long-message.test.ts+++ b/app/tests/route-long-message.test.ts@@ -1,8 +1,10 @@import { afterEach, expect, test } from "bun:test";import type { AgentProfileStore } from "../../server/src/agents/profile-store";+import type { AgentProfile } from "../../server/src/agents/profile-types";import type { AuditStore } from "../../server/src/audit";import type { IntentRouter } from "../../server/src/routing/classify";import { createRoutingRoutes } from "../../server/src/routing/routes";+import { createCoworkerRoutingService } from "../../server/src/routing/service";import { routeMessage } from "../src/lib/channels/route";/**@@ -42,7 +44,7 @@ function serve() {const asked: string[] = [];const written: { eventType: string; payload: Record<string, unknown> }[] = [];- const asActor: Parameters<typeof createRoutingRoutes>[2] = async (+ const asActor: Parameters<typeof createRoutingRoutes>[1] = async (context,next,) => {@@ -53,7 +55,23 @@ function serve() {});await next();};- const store = { list: async () => ROSTER } as unknown as AgentProfileStore;+ const store = {+ list: async (): Promise<AgentProfile[]> =>+ ROSTER.map((item) => ({+ ...item,+ visibility: "public",+ title: item.name,+ avatarSeed: item.id,+ ownerUserId: null,+ deletedAt: null,+ hidden: false,+ pinned: false,+ systemOwned: false,+ endpoint: null,+ hasAuth: false,+ hasCallbackToken: false,+ })),+ } as unknown as AgentProfileStore;const router = {route: async (text: string) => {asked.push(text);@@ -75,7 +93,10 @@ function serve() {},} as unknown as AuditStore;- const routes = createRoutingRoutes(store, router, asActor, auditStore);+ const routes = createRoutingRoutes(+ createCoworkerRoutingService({ store, router, auditStore }),+ asActor,+ );globalThis.fetch = Object.assign(async (path: Parameters<typeof fetch>[0],diff --git a/server/src/agents/agent-resolver.ts b/server/src/agents/agent-resolver.tsnew file mode 100644index 00000000..1314d444--- /dev/null+++ b/server/src/agents/agent-resolver.ts@@ -0,0 +1,147 @@+import type { AbstractAgent } from "@ag-ui/client";+import type { AuditInitiator } from "../audit";+import type { AgentFetch, StallGuard } from "../channels/stall-guard";+import {+ type HandoffForRun,+ type LoadAgentsForActor,+ type LoadAttachment,+ type LoadInstructions,+ type LoadToolsForBot,+ type MarkAttachmentsSent,+ type RuntimeModel,+ resolveRuntimeAgents,+ type SignRun,+ type ToolSelection,+} from "../copilot";+import type { AcquireLearnedSkills } from "../learning/runtime";+import type { LoadPersonalMemory } from "../memory/tools";+import type { AgentActor } from "./profile-types";++export type AgentResolutionContext = {+ initiator?: AuditInitiator;+ depth?: number;+};++export class CoworkerUnavailableError extends Error {}++export type ActorAgentResolver = {+ resolveAgentsForActor(+ actor: AgentActor,+ ): Promise<Record<string, AbstractAgent>>;+ resolveAgentForActor(+ actor: AgentActor,+ agentId: string,+ context?: AgentResolutionContext,+ ): Promise<AbstractAgent>;+};++export type ActorAgentResolverDependencies = {+ loadAgents: LoadAgentsForActor;+ model: RuntimeModel;+ resolveModelApiKey: () => Promise<string | null>;+ stallGuard?: StallGuard;+ loadToolsForActor?: (+ actorId: string,+ initiator?: AuditInitiator,+ ) => LoadToolsForBot;+ signRunForActor?: (+ actorId: string,+ initiator?: AuditInitiator,+ depth?: number,+ ) => SignRun;+ computerGuidance?: string;+ loadVendors?: () => Promise<readonly string[]>;+ selectionForActor?: (actorId: string) => ToolSelection;+ agentFetch?: AgentFetch;+ /**+ * What a Bot may reach past itself for, resolved for whoever is asking.+ *+ * Per actor for the same reason the tools are: which Bots may be reached is decided against the+ * roster that person can see, so a Bot must never be able to address one they cannot.+ */+ handoffForActor?: (+ actorId: string,+ initiator?: AuditInitiator,+ depth?: number,+ ) => HandoffForRun;+ loadInstructionsForActor?: (actorId: string) => LoadInstructions;+ loadAttachmentForActor?: (actorId: string) => LoadAttachment;+ markAttachmentsSentForActor?: (actorId: string) => MarkAttachmentsSent;+ acquireLearnedSkills?: AcquireLearnedSkills;+ loadPersonalMemoryForActor?: (actorId: string) => LoadPersonalMemory;+};++/**+ * Resolves the coworkers available to one OpenBot actor.+ *+ * Every surface enters through this boundary so it shares the same visibility, grants, assertions,+ * skill selection, and endpoint dial policy for a person.+ */+export function createActorAgentResolver(+ deps: ActorAgentResolverDependencies,+): ActorAgentResolver {+ const resolveRegisteredAgents = (+ actor: AgentActor,+ registered: Awaited<ReturnType<LoadAgentsForActor>>,+ /**+ * Build only this Bot, when the caller already knows which one it wants.+ *+ * The roster is still read in full, so a Bot this person cannot see is still absent. The others+ * are simply neither built nor asked what they hold, which is a query per Bot a headless turn+ * or a Slack thread has no use for.+ */+ onlyAgentId?: string,+ context?: AgentResolutionContext,+ ) =>+ resolveRuntimeAgents(+ () => Promise.resolve(registered),+ deps.model,+ deps.resolveModelApiKey,+ deps.stallGuard,+ deps.loadToolsForActor?.(actor.id, context?.initiator),+ deps.signRunForActor?.(actor.id, context?.initiator, context?.depth),+ deps.computerGuidance,+ deps.loadVendors,+ deps.selectionForActor?.(actor.id),+ deps.agentFetch,+ deps.handoffForActor?.(actor.id, context?.initiator, context?.depth),+ onlyAgentId,+ deps.loadInstructionsForActor?.(actor.id),+ context?.initiator,+ deps.loadAttachmentForActor?.(actor.id),+ deps.markAttachmentsSentForActor?.(actor.id),+ deps.acquireLearnedSkills,+ deps.loadPersonalMemoryForActor?.(actor.id),+ );++ const resolveAgentsForActor = async (actor: AgentActor) =>+ resolveRegisteredAgents(actor, await deps.loadAgents(actor));++ return {+ resolveAgentsForActor,+ async resolveAgentForActor(actor, agentId, context) {+ const registered = await deps.loadAgents(actor);+ if (!registered.some((agent) => agent.id === agentId)) {+ throw new CoworkerUnavailableError(+ `Coworker ${agentId} is unavailable to this user.`,+ );+ }++ const agents = await resolveRegisteredAgents(+ actor,+ registered,+ agentId,+ context,+ );+ const agent = Object.hasOwn(agents, agentId)+ ? agents[agentId]+ : undefined;+ if (!agent) {+ throw new CoworkerUnavailableError(+ `Coworker ${agentId} is unavailable to this user.`,+ );+ }+ return agent;+ },+ };+}diff --git a/server/src/app.ts b/server/src/app.tsindex 8e39653b..636b8a3e 100644--- a/server/src/app.ts+++ b/server/src/app.ts@@ -81,7 +81,6 @@ import { createDictationRoutes } from "./dictation/routes";import type { HostAccessBroker } from "./host-access/broker";import { createHostAccessRoutes } from "./host-access/routes";import { createIntelligenceClient } from "./intelligence-client";-import type { SelfHostBanner } from "./self-host-banner";import {createLearningRoutes,type LearningAdminDependencies,@@ -119,6 +118,8 @@ import { createRoutineRoutes, type RoutineStore } from "./routines/routes";import type { RoutineRunner } from "./routines/runner";import type { IntentRouter } from "./routing/classify";import { createRoutingRoutes } from "./routing/routes";+import { createCoworkerRoutingService } from "./routing/service";+import type { SelfHostBanner } from "./self-host-banner";import { createTeamBotRoutes } from "./team-bots/routes";import type { TeamBots } from "./team-bots/team-bots";import type { PackageStatusReader } from "./tenant-package";@@ -1338,29 +1339,31 @@ export function createApp(app.route("/api/route",createRoutingRoutes(- agentProfileStore,- intentRouter,- requireUser,- auditStore,- /*- * Which vendors each coworker holds tools for, so the router weighs what a coworker can- * reach and not only what somebody wrote it was for. Only when there is a plugin store to- * ask: a deployment with no connectors routes exactly as it did.- */- pluginStore- ? async (agentId) => {- const granted = await pluginStore.listForAgent(agentId);- return [- ...new Set(- granted.tools.map(- (tool) =>- tool.toolName.replace(/^mcp__/, "").split("__")[0] ??- tool.toolName,+ createCoworkerRoutingService({+ store: agentProfileStore,+ router: intentRouter,+ auditStore,+ /*+ * Which vendors each coworker holds tools for, so the router weighs what a coworker can+ * reach and not only what somebody wrote it was for. Only when there is a plugin store to+ * ask: a deployment with no connectors routes exactly as it did.+ */+ reachableSystems: pluginStore+ ? async (agentId) => {+ const granted = await pluginStore.listForAgent(agentId);+ return [+ ...new Set(+ granted.tools.map(+ (tool) =>+ tool.toolName.replace(/^mcp__/, "").split("__")[0] ??+ tool.toolName,+ ),),- ),- ];- }- : undefined,+ ];+ }+ : undefined,+ }),+ requireUser,),);}diff --git a/server/src/copilot.ts b/server/src/copilot.tsindex 1a52b7f5..3ccd5a8f 100644--- a/server/src/copilot.ts+++ b/server/src/copilot.ts@@ -10,10 +10,11 @@ import { createCopilotHonoHandler } from "@copilotkit/runtime/v2/hono";import type { Observable } from "rxjs";import { defer, finalize, from, fromEvent, switchMap, takeUntil } from "rxjs";import { z } from "zod";+import { PROVENANCE_GUIDANCE } from "../../shared/bot-prompt";import {- COMPUTER_GUIDANCE,- PROVENANCE_GUIDANCE,-} from "../../shared/bot-prompt";+ type ActorAgentResolver,+ CoworkerUnavailableError,+} from "./agents/agent-resolver";import { sanitizeSeededHistory } from "./agents/history-sanitize";import {PLAN_RUN_COMPLETED,@@ -1944,101 +1945,10 @@ export type LoadAgentsForActor = (*/export function createRequestAgents(identifyActor: IdentifyActor,- loadAgents: LoadAgentsForActor,- model: RuntimeModel,- resolveModelApiKey: () => Promise<string | null>,- /**- * Shared across every request rather than built per run, because it is the thing that has to- * outlive one: the sweep that notices a silent stream has to still be running after the request- * that opened it has been answered.- */- stallGuard?: StallGuard,- /** What each Bot may call, resolved for whoever is asking. Absent means no tools. */- loadToolsForActor?: (- actorId: string,- initiator?: AuditInitiator,- ) => LoadToolsForBot,- /** Resolved per request, because what it signs is who this request turned out to be. */- signRunForActor?: (actorId: string, initiator?: AuditInitiator) => SignRun,- /** What every built-in Bot is told about the computer. Absent means this deployment has none. */- computerGuidance?: string,- /** Which vendors this deployment connects to, held by a Bot or not. Absent means none. */- loadVendors?: () => Promise<readonly string[]>,- /**- * How a run's tools are narrowed, resolved for whoever is asking.- *- * Per actor like the tools themselves, because the skills a Bot holds are read through the same- * grants, and because the discovery row has to name the person the run belongs to.- */- selectionForActor?: (actorId: string) => ToolSelection,- /** The fetch remote agents are dialled with. See {@link buildAgents}. */- agentFetch?: AgentFetch,- /**- * How a run gets its tool for handing work to another Bot, resolved for whoever is asking.- *- * Per actor for the same reason the tools are: which Bots may be reached is decided against the- * roster that person can see, so a Bot must never be able to address one they cannot.- */- handoffForActor?: (actorId: string) => HandoffForRun,- /**- * What this person has told every coworker they run, resolved for whoever is asking.- *- * Per actor, and through `identifyActor` rather than anything in the request body, for the same- * reason the grants are: this text goes into a prompt that then speaks as that person's coworker,- * so which person it belongs to has to be decided by the session and never by the caller.- */- loadInstructionsForActor?: (actorId: string) => LoadInstructions,- /**- * How the files on a person's message are put in front of the model, resolved for whoever is- * asking.- *- * Per actor, and through `identifyActor` rather than anything in the request body, for the reason- * `loadInstructionsForActor` is: the ids arrive inside `input.messages`, which the browser wrote,- * so a turn can name an attachment in a channel the asker was never in. Which rows this may read- * has to be decided by the session, exactly as the fetch route decides it. Appended last for the- * positional reason above. Absent means nothing is inlined, which is what every deployment did- * before this existed.- */- loadAttachmentForActor?: (actorId: string) => LoadAttachment,- /**- * How a send is recorded against the files it carried, resolved for whoever is asking.- *- * Per actor for a stricter reason than the reader beside it: this one WRITES `attachedAt`, and- * `markAttachmentsSent` will only stamp rows the acting person uploaded themselves. Deciding who- * that is from the session rather than from the request body is what keeps one member from- * recording a send against a colleague's staged file. Appended last, positionally. Absent means- * nothing is recorded.- */- markAttachmentsSentForActor?: (actorId: string) => MarkAttachmentsSent,- acquireLearnedSkills?: AcquireLearnedSkills,- loadPersonalMemoryForActor?: (actorId: string) => LoadPersonalMemory,+ resolver: ActorAgentResolver,) {- return async ({ request }: { request: Request }) => {- const actor = await identifyActor(request);- return resolveRuntimeAgents(- () => loadAgents(actor),- model,- resolveModelApiKey,- stallGuard,- loadToolsForActor?.(actor.id),- signRunForActor?.(actor.id),- computerGuidance,- loadVendors,- selectionForActor?.(actor.id),- agentFetch,- handoffForActor?.(actor.id),- // Every Bot this person can see, so no `onlyBotId` here; the instructions follow it.- undefined,- loadInstructionsForActor?.(actor.id),- // No initiator: a request is a person asking, which is the default this path has always- // carried. Named only so the attachments after it land in the right position.- undefined,- loadAttachmentForActor?.(actor.id),- markAttachmentsSentForActor?.(actor.id),- acquireLearnedSkills,- loadPersonalMemoryForActor?.(actor.id),- );- };+ return async ({ request }: { request: Request }) =>+ resolver.resolveAgentsForActor(await identifyActor(request));}/**@@ -2127,71 +2037,17 @@ const THREAD_LOCK_TTL_SECONDS = 120;export function mountCopilotRuntime(config: DeploymentConfig,- model: RuntimeModel,- loadAgents: LoadAgentsForActor,- resolveModelApiKey: () => Promise<string | null>,+ resolver: ActorAgentResolver,identifyUser: IdentifyUser,identifyActor: IdentifyActor,- /**- * The watch on Bot streams. Not optional, unlike the parameter it forwards to: a guard built from- * a timeout of zero already watches nothing, so an unconfigured deployment has one to hand and- * there is no reason for a caller to have to say `undefined` here to reach `basePath`.- */- stallGuard: StallGuard,- loadToolsForActor?: (- actorId: string,- initiator?: AuditInitiator,- ) => LoadToolsForBot,- signRunForActor?: (actorId: string, initiator?: AuditInitiator) => SignRun,- basePath = "/api/copilotkit",- loadVendors?: () => Promise<readonly string[]>,- selectionForActor?: (actorId: string) => ToolSelection,- /** The fetch remote agents are dialled with. See {@link buildAgents}. */- agentFetch?: AgentFetch,- /** How a run gets its tool for handing work on. Absent means no Bot is offered one. */- handoffForActor?: (actorId: string) => HandoffForRun,- /**- * Told when a run starts and ends on a thread, so a channel can show it is working.- *- * The universal seam: every run the runtime processes — a person's own turn, a headless hop —- * takes and gives back the thread lock, and it does so on the server, so a person who sends a- * message and navigates away still lights the channel they left. A side effect only: it is never- * awaited in the lock path and a failure in it never touches whether the lock was taken.- */- onRunBusy?: (input: { threadId: string; busy: boolean }) => void,- /**- * What the person asking has told every built-in coworker they run, resolved per person.- *- * Given to both the request path and `agentFor` below, so a hop delivered to a Bot at three in the- * morning carries the same standing instructions the Bot in front of the person does. A seam wired- * into only one of them would be the drift `agentFor` exists to prevent.- */- loadInstructionsForActor?: (actorId: string) => LoadInstructions,- /**- * How the files on a message are put in front of the model, resolved per person, on both paths- * below.- *- * Given to the request path and to `agentFor` alike, for the reason `loadInstructionsForActor` is:- * a routine's turn at three in the morning has to inline exactly as a person's chat turn does, and- * a seam wired into only one of them is the drift `agentFor` exists to prevent. Actor-keyed for- * the same reason every other collaborator here is — the ids come out of browser-supplied message- * content, so the person the run belongs to is what decides which attachments it may read.- * Appended last because these are positional. Absent means nothing is inlined.- */- loadAttachmentForActor?: (actorId: string) => LoadAttachment,- /**- * How a send is recorded against the files it carried, resolved per person, on both paths below.- *- * Given to the request path and to `agentFor` alike, for the reason `loadAttachmentForActor` is:- * a routine's turn at three in the morning sends exactly as a person's chat turn does, and a seam- * wired into only one of them is the drift `agentFor` exists to prevent. Actor-keyed because the- * write is scoped to rows that person uploaded. Appended last. Absent means nothing is recorded.- */- markAttachmentsSentForActor?: (actorId: string) => MarkAttachmentsSent,- learningSettings?: LearningSettingsStore,- loadPersonalMemoryForActor?: (actorId: string) => LoadPersonalMemory,+ options: {+ basePath?: string;+ onRunBusy?: (input: { threadId: string; busy: boolean }) => void;+ learningSettings?: LearningSettingsStore;+ } = {},) {const { intelligence } = config.runtime;+ const { basePath = "/api/copilotkit", onRunBusy, learningSettings } = options;/*** The same Bot a person's run would get, built without a request.@@ -2216,31 +2072,14 @@ export function mountCopilotRuntime(botId: string;initiator?: AuditInitiator;}): Promise<AbstractAgent | null> => {- const { actor } = input;- const agents = await resolveRuntimeAgents(- () => loadAgents(actor),- model,- resolveModelApiKey,- stallGuard,- loadToolsForActor?.(actor.id, input.initiator),- signRunForActor?.(actor.id, input.initiator),- config.computer ? COMPUTER_GUIDANCE : undefined,- loadVendors,- selectionForActor?.(actor.id),- agentFetch,- handoffForActor?.(actor.id),- // Only the Bot this hop is for. The roster is still read in full, so a Bot this person cannot- // see is still absent; what this skips is constructing the other Bots and asking the database- // what each of them was granted, on every delivery and again on every retry.- input.botId,- loadInstructionsForActor?.(actor.id),- input.initiator,- loadAttachmentForActor?.(actor.id),- markAttachmentsSentForActor?.(actor.id),- learning?.acquire,- loadPersonalMemoryForActor?.(actor.id),- );- return agents[input.botId] ?? null;+ try {+ return await resolver.resolveAgentForActor(input.actor, input.botId, {+ initiator: input.initiator,+ });+ } catch (error) {+ if (error instanceof CoworkerUnavailableError) return null;+ throw error;+ }};/*@@ -2317,31 +2156,7 @@ export function mountCopilotRuntime(a2ui: { enabled: config.generativeUi },// `identifyUser` is the Intelligence projection of the same person `identifyActor` returns:// one resolver decides both whose threads these are and whose coworkers exist.- agents: createRequestAgents(- identifyActor,- loadAgents,- model,- resolveModelApiKey,- stallGuard,- loadToolsForActor,- signRunForActor,- /*- * Only when a computer exists. The tools themselves are registered by the surface, so a Bot is- * offered them without this and the guidance is what tells it how they go together: snapshot- * before acting, and ask a person to take the wheel at a sign-in rather than reporting the task- * as impossible. Absent computer, absent guidance: a Bot is not told about hands it has not got.- */- config.computer ? COMPUTER_GUIDANCE : undefined,- loadVendors,- selectionForActor,- agentFetch,- handoffForActor,- loadInstructionsForActor,- loadAttachmentForActor,- markAttachmentsSentForActor,- learning?.acquire,- loadPersonalMemoryForActor,- ) as never,+ agents: createRequestAgents(identifyActor, resolver) as never,});return {diff --git a/server/src/index.ts b/server/src/index.tsindex 972f672f..1857e5fe 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -1,5 +1,6 @@import { createHash, randomUUID } from "node:crypto";import { isDeepStrictEqual } from "node:util";+import type { AbstractAgent } from "@ag-ui/client";import {CopilotKitIntelligence,IntelligenceAgentRunner,@@ -20,6 +21,10 @@ import {headlessTurnRefusal,installEnterpriseControls,} from "./admin/controls";+import {+ CoworkerUnavailableError,+ createActorAgentResolver,+} from "./agents/agent-resolver";import {mintRunAssertion,type RunAssertion,@@ -73,7 +78,6 @@ import {parseApprovalContinuation,parseApprovalResult,} from "./approvals/types";-import { streamPathBotId } from "./computer/stream-path";import {type AuditInitiator,createAuditReader,@@ -133,13 +137,13 @@ import {describeComputerIsolation,} from "./computer/provider";import { createSnapshotStore } from "./computer/snapshot-store";+import { streamPathBotId } from "./computer/stream-path";import { loadConfig } from "./config";import {type IdentifyActor,type IdentifyUser,mountCopilotRuntime,normalizeModelBaseUrls,- resolveRuntimeAgents,runtimeModelForEnvironment,type ToolSelection,} from "./copilot";@@ -176,7 +180,6 @@ import {createIntelligenceClient,observeIntelligenceAuthentication,} from "./intelligence-client";-import { createSelfHostBanner } from "./self-host-banner";import { clearLearningRevisionFallback } from "./learning/runtime";import { createLearningSettingsStore } from "./learning/settings";import { createMemoryIngestion } from "./memory/ingestion";@@ -240,6 +243,7 @@ import { createRoutineRunner } from "./routines/runner";import { createRoutineStore } from "./routines/store";import { createIntentRouter } from "./routing/classify";import { createModelCompleter } from "./routing/model";+import { createSelfHostBanner } from "./self-host-banner";import { createTeamBots } from "./team-bots/team-bots";import {createPackageStatusReader,@@ -1002,16 +1006,7 @@ const chooseSkills = createModelCompleter({}),});-/*- * WHY THESE ARE NAMED CONSTANTS RATHER THAN ARGUMENTS WRITTEN INLINE.- *- * Two callers now build a Bot: a person's chat request, through `mountCopilotRuntime` below, and a- * routine's headless turn, through `buildAgentFor` further down. They have to build the SAME Bot. A- * routine that resolved its tools, its run assertion or its endpoint dialling through a second,- * slightly different set of collaborators would be a Bot that behaves one way when a person asks and- * another way at three in the morning, with nothing to point at. So each of these is written once and- * passed to both.- */+// Named collaborators are bound once in actorAgentResolver for chat, hops, and headless turns./** The deployment's model key, resolved per call so a credential rotated a moment ago is used next. */const resolveRuntimeModelApiKey = () =>@@ -1596,44 +1591,15 @@ const buildAgentFor = async ({depth?: number;}) => {const actor = await actorFor(ownerUserId);- const agents = await resolveRuntimeAgents(- () => loadAgentsForActor(actor),- runtimeModel,- resolveRuntimeModelApiKey,- stallGuard,- restrictToolsForRun(- initiator,- loadToolsForActor(actor.id, initiator),- proactiveReadOnlyRefs,- ),- signRunForActor(actor.id, initiator, depth),- config.computer ? COMPUTER_GUIDANCE : undefined,- loadVendors,- selectionForActor(actor.id),- agentFetch,- restrictCoordinationForRun(+ let agent: AbstractAgent | undefined;+ try {+ agent = await actorAgentResolver.resolveAgentForActor(actor, agentId, {initiator,- coordinationForActor(actor.id, initiator, depth),- ),- // Only the Bot this routine names. Same reason as the hop delivery: the roster is still read in- // full so a Bot this owner cannot see is still absent, but the other Bots are neither built nor- // asked what they hold.- agentId,- // The owner's own standing instructions. A routine is their work done while they are asleep, so- // it is written the way they asked for it to be written, exactly as their chat turn would be.- loadInstructionsForActor(actor.id),- initiator,- // The same reader the request path gets, bound to the owner the routine runs as, so a file- // attached in a channel reads the same way on a routine's turn as it does on the person's own —- // and is refused the same way when the owner is not in that channel.- loadAttachmentForActor(actor.id),- // And the same recorder, so the files on a routine's own message stop counting as staged the- // moment it sends them, exactly as a person's do.- markAttachmentsSentForActor(actor.id),- copilotRuntime.learning?.acquire,- loadPersonalMemoryForActor(actor.id),- );- const agent = agents[agentId];+ depth,+ });+ } catch (error) {+ if (!(error instanceof CoworkerUnavailableError)) throw error;+ }if (!agent) {/** Named, and raised rather than swallowed. The routine's Bot was deleted, or made private by@@ -1716,45 +1682,48 @@ const routineRunner = createRoutineRunner({* invisible: it runs, and quietly holds different tools or a different role from the one the person* is talking to.*/-const copilotRuntime = mountCopilotRuntime(- config,- runtimeModel,- loadAgentsForActor,- resolveRuntimeModelApiKey,- identifyUser,- identifyActor,+const actorAgentResolver = createActorAgentResolver({+ loadAgents: loadAgentsForActor,+ model: runtimeModel,+ resolveModelApiKey: resolveRuntimeModelApiKey,stallGuard,- loadToolsForActor,+ loadToolsForActor: (actorId, initiator) =>+ restrictToolsForRun(+ initiator,+ loadToolsForActor(actorId, initiator),+ proactiveReadOnlyRefs,+ ),signRunForActor,- undefined,+ computerGuidance: config.computer ? COMPUTER_GUIDANCE : undefined,loadVendors,selectionForActor,agentFetch,- /*- * What a Bot may reach past itself for: another Bot, and a person. Made per run and per person.- *- * Per person because which Bots may be reached is decided against the roster that person can- * see: a Bot must never be able to address one they cannot, or this becomes a way around agent- * visibility. Per run because the caps need to know how deep the chain already is and where an- * answer belongs, and both of those are the deployment's own statement about the run rather than- * anything the model can edit.- */- coordinationForActor,- // A run started or ended on a thread; light the channel it belongs to. Fire-and-forget, keyed by- // thread, and a scratch thread maps to no channel and signals nowhere.- (input) => {- void channelStore.signalBusy(input.threadId, input.busy).catch(() => {});- },- // What this person has told every coworker of theirs, in every channel. See user-instructions.ts.+ handoffForActor: (actorId, initiator, depth) =>+ restrictCoordinationForRun(+ initiator,+ coordinationForActor(actorId, initiator, depth),+ ),loadInstructionsForActor,- // The files on a message, put in front of the model rather than left as links it cannot follow —- // and only the ones the person whose run this is could open themselves.loadAttachmentForActor,- // And that those files went out in a send, written by the person who sent them and only for rows- // they uploaded. See markAttachmentsSentForActor.markAttachmentsSentForActor,- learningSettings,+ // The runtime owns Learning. Resolve its reader only when a turn is built, after boot wiring.+ get acquireLearnedSkills() {+ return copilotRuntime.learning?.acquire;+ },loadPersonalMemoryForActor,+});++const copilotRuntime = mountCopilotRuntime(+ config,+ actorAgentResolver,+ identifyUser,+ identifyActor,+ {+ onRunBusy: (input) => {+ void channelStore.signalBusy(input.threadId, input.busy).catch(() => {});+ },+ learningSettings,+ },);const responsibilityQueue = createWorkQueue(database);diff --git a/server/src/routing/routes.ts b/server/src/routing/routes.tsindex 1948f61d..c25b0bd8 100644--- a/server/src/routing/routes.ts+++ b/server/src/routing/routes.ts@@ -1,109 +1,26 @@import type { MiddlewareHandler } from "hono";import { Hono } from "hono";-import type { AgentProfileStore } from "../agents/profile-store";-import type { AgentProfile } from "../agents/profile-types";-import type { AuditStore } from "../audit";-import { recordAuditEvent } from "../audit";import type { AppVariables } from "../auth/guards";-import type {- IntentRouter,- RoutingCandidate,- RoutingUndecided,-} from "./classify";+import {+ type HttpCoworkerRoutingService,+ MAX_ROUTING_TEXT_LENGTH,+} from "./service";-const PICKED_HARNESS_AGENT_ID = "picked-harness";--export function defaultRoutingProfile(- roster: readonly AgentProfile[],-): AgentProfile | undefined {- return (- roster.find((agent) => agent.id === PICKED_HARNESS_AGENT_ID) ??- roster.find((agent) => agent.visibility === "public") ??- roster[0]- );-}--const DEV_ACTOR_EMAIL = "[email protected]";+export { defaultRoutingProfile } from "./service";/**- * Who to record the routing against, or nobody.+ * Translate the shared coworker-routing result into the established HTTP contract.*- * The single-user development actor is not a real person and has no row to point at, so it is left- * off rather than written as a user id that resolves to nothing.- */-function actorId(- actor:- | {- id?: string;- email?: string;- }- | null- | undefined,-): string | undefined {- return actor?.id && actor.email !== DEV_ACTOR_EMAIL ? actor.id : undefined;-}--/**- * Decide which coworker a message is for, before a channel is pinned to one.- *- * The roster is read for the person asking, so this can only ever land on a coworker they are- * already allowed to reach. The decision is recorded like every other one in the product: a- * `channel.routed` row names where it went and why, and carries the candidate ids but never the- * message itself, which the audit payload redaction would drop anyway.- *- * A person who named a coworker with `@` has already decided, so nothing is inferred and no model- * is called. It is still recorded, with `viaMention` true and the person as the reason. Without- * that the trail answered "why did this go to Risk Analyst" for routed conversations and said- * nothing at all for chosen ones, which reads exactly like a row that failed to write.+ * Choosing a coworker, applying visibility, invoking the intent model, and recording the canonical+ * audit row are deliberately owned by CoworkerRoutingService. This layer only validates HTTP input+ * and turns its outcome into status codes and JSON.*/export function createRoutingRoutes(- store: AgentProfileStore,- router: IntentRouter,+ routing: HttpCoworkerRoutingService,requireUser: MiddlewareHandler<{ Variables: AppVariables }>,- auditStore?: AuditStore,- /**- * Which systems a coworker can reach, for the router to weigh alongside what it is for.- *- * Optional, and absent leaves routing exactly as it was: a deployment with no connectors has- * nothing to add here, and one that cannot answer the question should not have routing fail over- * it. Asked per request rather than held, because a grant added a minute ago has to count.- */- reachableSystems?: (agentId: string) => Promise<readonly string[]>,) {const routes = new Hono<{ Variables: AppVariables }>();- /*- * The one place a `channel.routed` row is written, for both ways a message finds a coworker.- *- * Two call sites writing the same event is two payloads that drift, and a trail whose rows mean- * slightly different things depending on which branch produced them cannot be read at all.- */- async function record(- actorUserId: string | undefined,- chosen: string,- reason: string,- fallback: boolean,- viaMention: boolean,- candidates: readonly string[],- /*- * Why the router did not decide, when it did not.- *- * On the row rather than only in the sentence, because this is the field a deployment counts. A- * router that has been unreachable for a week produced rows that read like ordinary- * "no confident match" ones, which is how #178 went unnoticed for as long as it did.- */- undecided: RoutingUndecided | null,- ): Promise<void> {- if (!auditStore) return;- await recordAuditEvent(auditStore, {- eventType: "channel.routed",- targetType: "agent",- targetId: chosen,- ...(actorUserId ? { actorUserId } : {}),- payload: { chosen, reason, fallback, viaMention, candidates, undecided },- });- }-routes.post("/", requireUser, async (context) => {const body = (await context.req.json().catch(() => null)) as {text?: unknown;@@ -111,111 +28,56 @@ export function createRoutingRoutes(} | null;const text = typeof body?.text === "string" ? body.text.trim() : "";if (!text) return context.json({ error: "A message is required." }, 400);- // Unbounded text becomes the model prompt. Cap it so a multi-megabyte body cannot be used- // to force a timeout or OOM in the router.- if (text.length > 10000) {+ if (text.length > MAX_ROUTING_TEXT_LENGTH) {return context.json(- { error: "A message of at most 10000 characters is required." },+ {+ error: `A message of at most ${MAX_ROUTING_TEXT_LENGTH} characters is required.`,+ },400,);}- const named =+ const agentId =typeof body?.agentId === "string" && body.agentId.trim()? body.agentId.trim(): null;- const actor = context.var.actor;- const roster = await store.list(actor, false);- // The same default the composer shows: the package-picked harness, then the first public coworker.- const preferred = defaultRoutingProfile(roster);- if (!preferred) {- return context.json({ error: "No coworker is available." }, 409);+ const detail = await routing.routeDetailed({+ actor: context.var.actor,+ text,+ agentId,+ });+ const { result } = detail;+ if (result.kind === "none") {+ return context.json(+ {+ error: agentId+ ? "That coworker is not on your roster."+ : "No coworker is available.",+ },+ agentId ? 404 : 409,+ );}-- /*- * A named coworker is an instruction, not a question, so it is honoured as given.- *- * Checked against the same roster the router picks from, so `@` cannot reach further than- * routing can: a name that is not on it is refused rather than quietly turned into somebody- * else, because silently redirecting a message the person addressed by hand is the worst- * available answer.- */- if (named) {- const chosen = roster.find((a) => a.id === named);- if (!chosen) {- return context.json(- { error: "That coworker is not on your roster." },- 404,- );- }- /*- * Third person, because the audit page is not read by the person who chose.- *- * This said "you chose them yourself", which is true in the conversation and false on an- * administrator's screen, where every row is somebody else's. The person is already on the- * row as `actorUserId`; the reason only has to say what kind of decision it was.- *- * @zopeVaibhav had this right in #134.- */- const reason = "named by the person asking";- // The person chose. Nothing was left to the router, so nothing about it was undecided.- await record(- actorId(actor),- chosen.id,- reason,- false,- true,- [chosen.id],- null,+ if (result.kind === "ambiguous") {+ return context.json(+ {+ error: "More than one coworker matches that name.",+ names: result.names,+ },+ 409,);- return context.json({- agentId: chosen.id,- name: chosen.name,- reason,- fallback: false,- viaMention: true,- });}- const candidates: RoutingCandidate[] = await Promise.all(- roster.map(async (a) => ({- id: a.id,- name: a.name,- roleDescription: a.roleDescription,- /*- * Never allowed to break routing. A connector store that is slow or unhappy must not turn- * "who is this for" into an error, so a failure here is the same as holding nothing: the- * router falls back to matching on purpose alone, which is what it did before.- */- ...(reachableSystems- ? {- reaches: await reachableSystems(a.id).catch(- () => [] as readonly string[],- ),- }- : {}),- })),+ const response = {+ agentId: result.agentId,+ name: result.name,+ reason: result.reason,+ fallback: result.fallback,+ viaMention: result.viaMention,+ };+ // The composer chose this coworker directly, and the legacy response did not expose a model+ // fallback cause for that path. Keep the model-routed response shape unchanged below.+ return context.json(+ agentId ? response : { ...response, undecided: detail.undecided },);-- const decision = await router.route(text, candidates, preferred.id);-- await record(- actorId(actor),- decision.agentId,- decision.reason,- decision.fallback,- false,- candidates.map((c) => c.id),- decision.undecided,- );-- return context.json({- agentId: decision.agentId,- name: decision.name,- reason: decision.reason,- fallback: decision.fallback,- undecided: decision.undecided,- viaMention: false,- });});return routes;diff --git a/server/src/routing/service.ts b/server/src/routing/service.tsnew file mode 100644index 00000000..21a8ab7a--- /dev/null+++ b/server/src/routing/service.ts@@ -0,0 +1,486 @@+import { canAccessAgent } from "../agents/profile-policy";+import type { AgentProfileStore } from "../agents/profile-store";+import type { AgentActor, AgentProfile } from "../agents/profile-types";+import type { AuditStore } from "../audit";+import { recordAuditEvent } from "../audit";+import type {+ IntentRouter,+ RoutingCandidate,+ RoutingUndecided,+} from "./classify";++const PICKED_HARNESS_AGENT_ID = "picked-harness";++export function defaultRoutingProfile(+ roster: readonly AgentProfile[],+): AgentProfile | undefined {+ return (+ roster.find((agent) => agent.id === PICKED_HARNESS_AGENT_ID) ??+ roster.find((agent) => agent.visibility === "public") ??+ roster[0]+ );+}++export const MAX_ROUTING_TEXT_LENGTH = 10000;++export class CoworkerRoutingInputError extends Error {+ constructor(+ message = `A message of at most ${MAX_ROUTING_TEXT_LENGTH} characters is required.`,+ ) {+ super(message);+ this.name = "CoworkerRoutingInputError";+ }+}++const DEV_ACTOR_EMAIL = "[email protected]";+const WORD_CHARACTER = /[\p{L}\p{N}\p{M}_]/u;++export type CoworkerRouteResult =+ | {+ kind: "selected";+ agentId: string;+ name: string;+ reason: string;+ fallback: boolean;+ viaMention: boolean;+ viaNameMatch?: true;+ }+ | { kind: "ambiguous"; names: string[] }+ | { kind: "none" };++type RoutingActor = AgentActor & { email?: string };++export type CoworkerRoutingInput = {+ actor: RoutingActor;+ text: string;+ /** An explicit picker selection from a surface such as the web composer. */+ agentId?: string | null;+};++export type CoworkerRouteDetail = {+ result: CoworkerRouteResult;+ /** Kept for surfaces that have historically returned the model's fallback cause. */+ undecided: RoutingUndecided | null;+};++export type CoworkerRoutingService = {+ route(input: CoworkerRoutingInput): Promise<CoworkerRouteResult>;+};++export type HttpCoworkerRoutingService = CoworkerRoutingService & {+ routeDetailed(input: CoworkerRoutingInput): Promise<CoworkerRouteDetail>;+};++export type CreateCoworkerRoutingServiceOptions = {+ store: AgentProfileStore;+ router: IntentRouter;+ auditStore?: AuditStore;+ reachableSystems?: (agentId: string) => Promise<readonly string[]>;+};++/** Normalize people-facing names before matching, without making matching fuzzy. */+export function normalizeCoworkerName(value: string): string {+ return value.normalize("NFKC").toLowerCase().trim().replace(/\s+/gu, " ");+}++function hasTokenBoundaries(text: string, start: number, end: number): boolean {+ const before = [...text.slice(0, start)].at(-1);+ const after = [...text.slice(end)][0];+ return !before || !WORD_CHARACTER.test(before)+ ? !after || !WORD_CHARACTER.test(after)+ : false;+}++type AliasOccurrence = {+ start: number;+ end: number;+ profiles: ReadonlyMap<string, AgentProfile>;+};++function occurrencesOf(+ text: string,+ alias: string,+ profiles: ReadonlyMap<string, AgentProfile>,+): AliasOccurrence[] {+ const occurrences: AliasOccurrence[] = [];+ let start = text.indexOf(alias);+ while (start >= 0) {+ const end = start + alias.length;+ if (hasTokenBoundaries(text, start, end)) {+ occurrences.push({ start, end, profiles });+ }+ start = text.indexOf(alias, start + alias.length);+ }+ return occurrences;+}++function actorId(actor: RoutingActor): string | undefined {+ return actor.id && actor.email !== DEV_ACTOR_EMAIL ? actor.id : undefined;+}++function displayName(name: string): string {+ return name.normalize("NFKC").trim().replace(/\s+/gu, " ");+}++function utf8Hex(value: string): string {+ return [...new TextEncoder().encode(value)]+ .map((byte) => byte.toString(16).padStart(2, "0"))+ .join("");+}++function codePointCompare(left: string, right: string): number {+ const leftPoints = [...left];+ const rightPoints = [...right];+ for (let index = 0; index < leftPoints.length; index += 1) {+ const leftPoint = leftPoints[index]?.codePointAt(0);+ const rightPoint = rightPoints[index]?.codePointAt(0);+ if (leftPoint === undefined) return -1;+ if (rightPoint === undefined) return 1;+ if (leftPoint !== rightPoint) return leftPoint - rightPoint;+ }+ return leftPoints.length - rightPoints.length;+}++type AliasIndex = {+ aliases: Map<string, Map<string, AgentProfile>>;+ labels: Map<string, string>;+};++function addAlias(+ aliases: AliasIndex["aliases"],+ alias: string,+ profile: AgentProfile,+): void {+ if (!alias) return;+ const profiles = aliases.get(alias) ?? new Map<string, AgentProfile>();+ profiles.set(profile.id, profile);+ aliases.set(alias, profiles);+}++function buildAliasIndex(roster: readonly AgentProfile[]): AliasIndex {+ const aliases = new Map<string, Map<string, AgentProfile>>();+ const labels = new Map<string, string>();+ for (const profile of roster) {+ // Full names only. A trailing word of a name ("review", "notes", "analyst") is an ordinary word+ // in a request, and matching it sent "review this contract" to whichever coworker ends in Review.+ addAlias(aliases, normalizeCoworkerName(profile.name), profile);+ }+ // Keep encoded id aliases even when a later roster collision changes the displayed label.+ // A previously offered label must become ambiguous rather than silently address another Bot.+ for (const profile of roster) {+ addAlias(+ aliases,+ normalizeCoworkerName(+ `${displayName(profile.name)} (id ${utf8Hex(profile.id)})`,+ ),+ profile,+ );+ }+ // A generated numeric discriminator is also part of an encoded id label. If a natural alias+ // reuses an old discriminator, merge the original id at the same span so containment cannot+ // discard it and quietly route to the newly named coworker.+ for (const profile of roster) {+ const base = normalizeCoworkerName(+ `${displayName(profile.name)} (id ${utf8Hex(profile.id)})`,+ );+ for (const alias of aliases.keys()) {+ if (+ alias.startsWith(base) &&+ /^ \((?:[2-9]|[1-9]\d+)\)$/u.test(alias.slice(base.length))+ ) {+ addAlias(aliases, alias, profile);+ }+ }+ }+ const reservedLabels = new Set(aliases.keys());+ for (const profile of roster) {+ const normalized = normalizeCoworkerName(profile.name);+ const duplicates = aliases.get(normalized)?.size ?? 0;+ let label = profile.name;+ if (duplicates > 1) {+ const base = `${displayName(profile.name)} (id ${utf8Hex(profile.id)})`;+ label = base;+ let discriminator = 2;+ while (+ reservedLabels.has(normalizeCoworkerName(label)) &&+ !(+ label === base && aliases.get(normalizeCoworkerName(base))?.size === 1+ )+ ) {+ label = `${base} (${discriminator++})`;+ }+ reservedLabels.add(normalizeCoworkerName(label));+ }+ labels.set(profile.id, label);+ addAlias(aliases, normalized, profile);+ if (duplicates > 1) {+ addAlias(aliases, normalizeCoworkerName(label), profile);+ }+ }+ return { aliases, labels };+}++type ExplicitOccurrence = {+ start: number;+ end: number;+ profiles: Map<string, AgentProfile>;+};++/**+ * Discard only aliases that a strictly longer explicit occurrence fully contains.+ *+ * Intervals are ordered by start, then widest first. A running maximum end therefore proves that a+ * prior interval starts no later and reaches at least as far as the current one, which is exactly+ * containment. Partial overlaps extend the maximum only for later contained intervals; they never+ * suppress each other.+ */+function withoutContainedOccurrences(+ occurrences: readonly AliasOccurrence[],+): ExplicitOccurrence[] {+ const bySpan = new Map<string, ExplicitOccurrence>();+ for (const occurrence of occurrences) {+ const key = `${occurrence.start}:${occurrence.end}`;+ const merged =+ bySpan.get(key) ??+ ({+ start: occurrence.start,+ end: occurrence.end,+ profiles: new Map<string, AgentProfile>(),+ } satisfies ExplicitOccurrence);+ for (const profile of occurrence.profiles.values()) {+ merged.profiles.set(profile.id, profile);+ }+ bySpan.set(key, merged);+ }++ const sorted = [...bySpan.values()].sort(+ (left, right) => left.start - right.start || right.end - left.end,+ );+ let maximumEnd = -1;+ return sorted.filter((occurrence) => {+ const contained = maximumEnd >= occurrence.end;+ maximumEnd = Math.max(maximumEnd, occurrence.end);+ return !contained;+ });+}++function labelsFor(+ profiles: Iterable<AgentProfile>,+ labels: ReadonlyMap<string, string>,+): string[] {+ return [...profiles]+ .map((profile) => labels.get(profile.id) ?? profile.name)+ .sort(codePointCompare);+}++/** "hey", "hi" or "hello" opening a message, then an optional `@`, before the name addressed. */+const OPENING_ADDRESS = /^(?:(?:hey|hi|hello)(?![\p{L}\p{N}\p{M}_])[\s,]*)?@?/u;+/** "ask" as a whole word, then an optional `@`, before the name addressed. */+const ASK_ADDRESS = /(?<![\p{L}\p{N}\p{M}_])ask\s+@?/gu;+/** A list of names addressed together: "ask Risk Analyst and Knowledge", "@Ann, @Bob". */+const LIST_CONTINUATION = /^(?:\s*,\s*|\s*&\s*|\s+(?:and|or)\s+)@?/u;++/**+ * Keep only the names a message ADDRESSES, so a coworker is chosen without the model only when the+ * person spoke to it: the message opens with its full name ("Risk Analyst, please…", after an+ * optional greeting), names it with `@`, or asks it ("ask Risk Analyst to…"). A name mentioned in+ * passing ("don't send this to Risk Analyst") is left to the model. Names listed straight after an+ * addressed one are addressed too, so "ask Risk Analyst and Knowledge" is still a choice to make.+ */+function addressedOccurrences(+ text: string,+ occurrences: readonly AliasOccurrence[],+): AliasOccurrence[] {+ const starts = new Set<number>();+ starts.add(OPENING_ADDRESS.exec(text)?.[0].length ?? 0);+ for (let at = text.indexOf("@"); at >= 0; at = text.indexOf("@", at + 1)) {+ starts.add(at + 1);+ }+ for (const match of text.matchAll(ASK_ADDRESS)) {+ starts.add((match.index ?? 0) + match[0].length);+ }+ const addressed: AliasOccurrence[] = [];+ const sorted = [...occurrences].sort(+ (left, right) => left.start - right.start || right.end - left.end,+ );+ for (const occurrence of sorted) {+ // A name that starts inside an addressed one and runs past it ("ask Ann Marie Curie" with Ann+ // Marie and Marie Curie) is addressed too, so overlapping names stay a choice, not a guess.+ const overlapsAddressed = addressed.some(+ (prior) =>+ occurrence.start > prior.start &&+ occurrence.start < prior.end &&+ occurrence.end > prior.end,+ );+ if (!starts.has(occurrence.start) && !overlapsAddressed) continue;+ addressed.push(occurrence);+ const continuation = LIST_CONTINUATION.exec(text.slice(occurrence.end));+ if (continuation) starts.add(occurrence.end + continuation[0].length);+ }+ return addressed;+}++function explicitNameRoute(+ text: string,+ roster: readonly AgentProfile[],+): CoworkerRouteResult | null {+ const normalizedText = normalizeCoworkerName(text);+ const { aliases, labels } = buildAliasIndex(roster);+ const occurrences = [...aliases.entries()].flatMap(([alias, profiles]) =>+ occurrencesOf(normalizedText, alias, profiles),+ );+ const explicitOccurrences = withoutContainedOccurrences(+ addressedOccurrences(normalizedText, occurrences),+ );+ const profiles = new Map<string, AgentProfile>();+ for (const occurrence of explicitOccurrences) {+ for (const profile of occurrence.profiles.values()) {+ profiles.set(profile.id, profile);+ }+ }+ if (profiles.size === 1) {+ const chosen = profiles.values().next().value as AgentProfile;+ return {+ kind: "selected",+ agentId: chosen.id,+ name: chosen.name,+ reason: "matched a coworker’s name in the message",+ fallback: false,+ viaMention: false,+ viaNameMatch: true,+ };+ }+ if (profiles.size > 1) {+ return { kind: "ambiguous", names: labelsFor(profiles.values(), labels) };+ }+ return null;+}++function auditReason(+ selected: Extract<CoworkerRouteResult, { kind: "selected" }>,+ undecided: RoutingUndecided | null,+): string {+ if (selected.viaNameMatch) return selected.reason;+ if (selected.viaMention) return "named by the person asking";+ if (selected.fallback)+ return undecided ? `fallback: ${undecided}` : "fallback";+ return "intent match";+}++export function createCoworkerRoutingService(+ options: CreateCoworkerRoutingServiceOptions,+): HttpCoworkerRoutingService {+ async function record(+ actor: RoutingActor,+ selected: Extract<CoworkerRouteResult, { kind: "selected" }>,+ candidates: readonly string[],+ undecided: RoutingUndecided | null,+ ): Promise<void> {+ if (!options.auditStore) return;+ await recordAuditEvent(options.auditStore, {+ eventType: "channel.routed",+ targetType: "agent",+ targetId: selected.agentId,+ ...(actorId(actor) ? { actorUserId: actorId(actor) } : {}),+ payload: {+ chosen: selected.agentId,+ reason: auditReason(selected, undecided),+ fallback: selected.fallback,+ viaMention: selected.viaMention,+ viaNameMatch: selected.viaNameMatch === true,+ candidates,+ undecided,+ },+ });+ }++ async function routeDetailed(+ input: CoworkerRoutingInput,+ ): Promise<CoworkerRouteDetail> {+ if (!input.text.trim())+ throw new CoworkerRoutingInputError("A message is required.");+ if (input.text.length > MAX_ROUTING_TEXT_LENGTH) {+ throw new CoworkerRoutingInputError();+ }+ // The store applies this same policy in SQL; keep this canonical policy check at the service+ // boundary so a broader store implementation cannot leak a coworker into routing.+ const roster = (await options.store.list(input.actor, false)).filter(+ (profile) => canAccessAgent(input.actor, profile),+ );+ const namedId = input.agentId?.trim() || null;+ if (namedId) {+ const chosen = roster.find(({ id }) => id === namedId);+ if (!chosen) return { result: { kind: "none" }, undecided: null };+ const result: Extract<CoworkerRouteResult, { kind: "selected" }> = {+ kind: "selected",+ agentId: chosen.id,+ name: chosen.name,+ reason: "named by the person asking",+ fallback: false,+ viaMention: true,+ };+ await record(input.actor, result, [chosen.id], null);+ return { result, undecided: null };+ }++ if (roster.length === 0)+ return { result: { kind: "none" }, undecided: null };++ const explicit = explicitNameRoute(input.text, roster);+ if (explicit) {+ if (explicit.kind === "selected") {+ await record(input.actor, explicit, [explicit.agentId], null);+ }+ return { result: explicit, undecided: null };+ }++ const preferred = defaultRoutingProfile(roster);+ if (!preferred) return { result: { kind: "none" }, undecided: null };+ const candidates: RoutingCandidate[] = await Promise.all(+ roster.map(async (profile) => ({+ id: profile.id,+ name: profile.name,+ roleDescription: profile.roleDescription,+ /*+ * Never allowed to break routing. A connector store that is slow or unhappy must not turn+ * "who is this for" into an error, so a failure here is the same as holding nothing: the+ * router falls back to matching on purpose alone, which is what it did before.+ */+ ...(options.reachableSystems+ ? {+ reaches: await options+ .reachableSystems(profile.id)+ .catch(() => [] as readonly string[]),+ }+ : {}),+ })),+ );+ const decision = await options.router.route(+ input.text,+ candidates,+ preferred.id,+ );+ const result: Extract<CoworkerRouteResult, { kind: "selected" }> = {+ kind: "selected",+ agentId: decision.agentId,+ name: decision.name,+ reason: decision.reason,+ fallback: decision.fallback,+ viaMention: false,+ };+ await record(+ input.actor,+ result,+ candidates.map(({ id }) => id),+ decision.undecided,+ );+ return { result, undecided: decision.undecided };+ }++ return {+ async route(input) {+ return (await routeDetailed(input)).result;+ },+ routeDetailed,+ };+}diff --git a/server/tests/agent-resolver.test.ts b/server/tests/agent-resolver.test.tsnew file mode 100644index 00000000..79c112ea--- /dev/null+++ b/server/tests/agent-resolver.test.ts@@ -0,0 +1,176 @@+import { describe, expect, test } from "bun:test";+import { BuiltInAgent } from "@copilotkit/runtime/v2";+import { createActorAgentResolver } from "../src/agents/agent-resolver";+import type { AuditInitiator } from "../src/audit";++describe("actor-scoped agent resolver", () => {+ test("builds only the addressed coworker and carries the headless initiator and depth", async () => {+ const built: string[] = [];+ const contexts: unknown[] = [];+ const actor = { id: "u1", role: "admin" as const };+ const initiator: AuditInitiator = { kind: "routine", id: "routine-1" };+ const resolver = createActorAgentResolver({+ loadAgents: async (seenActor) => {+ expect(seenActor).toEqual(actor);+ return ["risk", "other"].map((id) => ({+ id,+ name: id,+ type: "built_in" as const,+ systemPrompt: "Work.",+ }));+ },+ model: { provider: "openai", defaultModel: "unused" },+ resolveModelApiKey: async () => "synthetic-key",+ loadToolsForActor: (id, cause) => {+ contexts.push(["tools", id, cause]);+ return async (botId) => {+ built.push(botId);+ return [];+ };+ },+ signRunForActor: (id, cause, depth) => {+ contexts.push(["sign", id, cause, depth]);+ return () => "synthetic-assertion";+ },+ handoffForActor: (id, cause, depth) => {+ contexts.push(["handoff", id, cause, depth]);+ return async () => [];+ },+ loadInstructionsForActor: (id) => async () => {+ contexts.push(["instructions", id]);+ return "Be precise.";+ },+ });+ await resolver.resolveAgentForActor(actor, "risk", { initiator, depth: 3 });+ expect(built).toEqual(["risk"]);+ expect(contexts).toEqual([+ ["tools", "u1", initiator],+ ["sign", "u1", initiator, 3],+ ["handoff", "u1", initiator, 3],+ ["instructions", "u1"],+ ]);+ });++ test("propagates construction failures instead of reporting an unavailable coworker", async () => {+ const failure = new Error("key store unavailable");+ const resolver = createActorAgentResolver({+ loadAgents: async () => [+ { id: "risk", name: "Risk", type: "built_in", systemPrompt: "Work." },+ ],+ model: { provider: "openai", defaultModel: "unused" },+ resolveModelApiKey: async () => {+ throw failure;+ },+ });+ await expect(+ resolver.resolveAgentForActor({ id: "u1", role: "user" }, "risk"),+ ).rejects.toBe(failure);+ });++ test("uses the same actor for web maps and individual agent resolution", async () => {+ const seenActorIds: string[] = [];+ const resolver = createActorAgentResolver({+ loadAgents: async (actor) => {+ seenActorIds.push(actor.id);+ return [+ {+ id: "risk",+ name: "Risk Analyst",+ type: "built_in" as const,+ systemPrompt: "Assess operational risk.",+ },+ ];+ },+ model: { provider: "openai", defaultModel: "gpt-5.6-terra" },+ resolveModelApiKey: async () => "openai-secret",+ });+ const actor = { id: "u1", role: "user" as const };++ const visibleAgents = await resolver.resolveAgentsForActor(actor);+ const risk = await resolver.resolveAgentForActor(actor, "risk");++ expect(seenActorIds).toEqual(["u1", "u1"]);+ expect(visibleAgents.risk).toBeInstanceOf(BuiltInAgent);+ expect(risk).toBeInstanceOf(BuiltInAgent);+ });++ test("rejects an agent absent from the actor's visible map", async () => {+ const resolver = createActorAgentResolver({+ loadAgents: async () => [+ {+ id: "risk",+ name: "Risk Analyst",+ type: "built_in" as const,+ systemPrompt: "Assess operational risk.",+ },+ ],+ model: { provider: "openai", defaultModel: "gpt-5.6-terra" },+ resolveModelApiKey: async () => "openai-secret",+ });++ let rejection: unknown;+ try {+ await resolver.resolveAgentForActor(+ { id: "u1", role: "user" },+ "private-risk",+ );+ } catch (error) {+ rejection = error;+ }++ expect(rejection).toBeInstanceOf(Error);+ expect((rejection as Error).message).toBe(+ "Coworker private-risk is unavailable to this user.",+ );+ });++ test("rejects an agent when the actor has no visible coworkers", async () => {+ const resolver = createActorAgentResolver({+ loadAgents: async () => [],+ model: { provider: "openai", defaultModel: "gpt-5.6-terra" },+ resolveModelApiKey: async () => "openai-secret",+ });++ expect(+ await rejectionMessage(() =>+ resolver.resolveAgentForActor(+ { id: "u1", role: "user" },+ "private-risk",+ ),+ ),+ ).toBe("Coworker private-risk is unavailable to this user.");+ });++ test("rejects inherited object keys as unavailable coworkers", async () => {+ const resolver = createActorAgentResolver({+ loadAgents: async () => [+ {+ id: "risk",+ name: "Risk Analyst",+ type: "built_in" as const,+ systemPrompt: "Assess operational risk.",+ },+ ],+ model: { provider: "openai", defaultModel: "gpt-5.6-terra" },+ resolveModelApiKey: async () => "openai-secret",+ });++ for (const agentId of ["constructor", "toString", "__proto__"]) {+ expect(+ await rejectionMessage(() =>+ resolver.resolveAgentForActor({ id: "u1", role: "user" }, agentId),+ ),+ ).toBe(`Coworker ${agentId} is unavailable to this user.`);+ }+ });+});++async function rejectionMessage(run: () => Promise<unknown>) {+ try {+ await run();+ } catch (error) {+ if (error instanceof Error) return error.message;+ throw error;+ }+ throw new Error("Expected the run to reject.");+}diff --git a/server/tests/copilot.test.ts b/server/tests/copilot.test.tsindex 7b19aaf8..3fa5168e 100644--- a/server/tests/copilot.test.ts+++ b/server/tests/copilot.test.ts@@ -8,6 +8,7 @@ import { BuiltInAgent } from "@copilotkit/runtime/v2";import { EMPTY, lastValueFrom } from "rxjs";import { z } from "zod";import { PROVENANCE_GUIDANCE } from "../../shared/bot-prompt";+import { createActorAgentResolver } from "../src/agents/agent-resolver";import { MAX_INLINED_BYTES_PER_RUN } from "../src/channels/attachment-parts";import { loadConfig } from "../src/config";import type { LoadAttachment } from "../src/copilot";@@ -756,12 +757,14 @@ describe("standing agent roles", () => {seen.request = request;return { id: "user-7", role: "user" as const };},- async (actor) => {- seen.actors.push(actor);- return [remoteAgent("http://coworker.internal/ag-ui")];- },- { provider: "openai", defaultModel: "gpt-5.6-terra" },- async () => null,+ createActorAgentResolver({+ loadAgents: async (actor) => {+ seen.actors.push(actor);+ return [remoteAgent("http://coworker.internal/ag-ui")];+ },+ model: { provider: "openai", defaultModel: "gpt-5.6-terra" },+ resolveModelApiKey: async () => null,+ }),);const request = new Request("http://openbot.test/api/copilotkit");@@ -790,9 +793,13 @@ describe("standing agent roles", () => {let roleDescription = "Review receipts.";const factory = createRequestAgents(async () => ({ id: "user-7", role: "user" as const }),- async () => [remoteAgent(endpoint.url, { roleDescription })],- { provider: "openai", defaultModel: "gpt-5.6-terra" },- async () => null,+ createActorAgentResolver({+ loadAgents: async () => [+ remoteAgent(endpoint.url, { roleDescription }),+ ],+ model: { provider: "openai", defaultModel: "gpt-5.6-terra" },+ resolveModelApiKey: async () => null,+ }),);const request = new Request("http://openbot.test/api/copilotkit");@@ -1443,21 +1450,15 @@ describe("a person's standing instructions", () => {const asked: string[] = [];const factory = createRequestAgents(async () => ({ id: "user-7", role: "user" as const }),- async () => [assistant],- model,- async () => "openai-secret",- undefined,- undefined,- undefined,- undefined,- undefined,- undefined,- undefined,- undefined,- (actorId) => async () => {- asked.push(actorId);- return "Write in British English.";- },+ createActorAgentResolver({+ loadAgents: async () => [assistant],+ model,+ resolveModelApiKey: async () => "openai-secret",+ loadInstructionsForActor: (actorId) => async () => {+ asked.push(actorId);+ return "Write in British English.";+ },+ }),);await factory({diff --git a/server/tests/learning-handoff.test.ts b/server/tests/learning-handoff.test.tsindex b0048be0..b58da7b9 100644--- a/server/tests/learning-handoff.test.ts+++ b/server/tests/learning-handoff.test.ts@@ -1,5 +1,6 @@import { expect, spyOn, test } from "bun:test";import { CopilotKitIntelligence } from "@copilotkit/runtime/v2";+import { createActorAgentResolver } from "../src/agents/agent-resolver";import { createStallGuard } from "../src/channels/stall-guard";import { loadConfig } from "../src/config";import { mountCopilotRuntime } from "../src/copilot";@@ -48,24 +49,15 @@ test("delegation creates its scratch Thread with the addressed Bot's Learning as});const runtime = mountCopilotRuntime(loadConfig(testEnvironment()),- { provider: "openai", defaultModel: "unused" },- async () => [],- async () => null,+ createActorAgentResolver({+ model: { provider: "openai", defaultModel: "unused" },+ loadAgents: async () => [],+ resolveModelApiKey: async () => null,+ stallGuard: guard,+ }),async () => ({ id: "person", name: "Person" }),async () => ({ id: "person", role: "user" }),- guard,- undefined,- undefined,- undefined,- undefined,- undefined,- undefined,- undefined,- undefined,- undefined,- undefined,- undefined,- settings,+ { learningSettings: settings },);expect(await runtime.threadLock.acquire({diff --git a/server/tests/routing-limits-validation.test.ts b/server/tests/routing-limits-validation.test.tsindex 0fd8e6bc..bf63e52b 100644--- a/server/tests/routing-limits-validation.test.ts+++ b/server/tests/routing-limits-validation.test.ts@@ -1,12 +1,15 @@import { describe, expect, test } from "bun:test";import type { MiddlewareHandler } from "hono";import { Hono } from "hono";-import type { AppVariables } from "../src/auth/guards";+import type { AgentProfileStore } from "../src/agents/profile-store";import { createApp } from "../src/app";-import { loadConfig } from "../src/config";-import { createRoutingRoutes } from "../src/routing/routes";+import type { AppVariables } from "../src/auth/guards";import { createComputerRoutes } from "../src/computer/routes";+import { loadConfig } from "../src/config";import type { RoutineRunner } from "../src/routines/runner";+import type { IntentRouter } from "../src/routing/classify";+import { createRoutingRoutes } from "../src/routing/routes";+import { createCoworkerRoutingService } from "../src/routing/service";import { testEnvironment } from "./support/environment";const requireUser: MiddlewareHandler<{ Variables: AppVariables }> = async (@@ -38,7 +41,13 @@ describe("POST /api/route text cap", () => {const app = new Hono<{ Variables: AppVariables }>();app.route("/",- createRoutingRoutes(store as never, router as never, requireUser),+ createRoutingRoutes(+ createCoworkerRoutingService({+ store: store as unknown as AgentProfileStore,+ router: router as unknown as IntentRouter,+ }),+ requireUser,+ ),);return app;}diff --git a/server/tests/routing-routes.test.ts b/server/tests/routing-routes.test.tsindex 05e70331..b4c442d3 100644--- a/server/tests/routing-routes.test.ts+++ b/server/tests/routing-routes.test.ts@@ -10,6 +10,7 @@ import {createRoutingRoutes,defaultRoutingProfile,} from "../src/routing/routes";+import { createCoworkerRoutingService } from "../src/routing/service";/*** Why a conversation went where it went, for every conversation.@@ -70,6 +71,7 @@ function profile(input: {hasAuth: false,hasCallbackToken: false,hidden: false,+ pinned: false,id: input.id,name: input.name,ownerUserId: ACTOR.id,@@ -101,7 +103,7 @@ function app(options: { routed?: string; undecided?: RoutingUndecided } = {}) {};const store = {- list: async () => ROSTER,+ list: async () => ROSTER.map(profile),} as unknown as AgentProfileStore;const router = {@@ -128,7 +130,10 @@ function app(options: { routed?: string; undecided?: RoutingUndecided } = {}) {const server = new Hono<{ Variables: AppVariables }>();server.route("/api/route",- createRoutingRoutes(store, router, asActor, auditStore),+ createRoutingRoutes(+ createCoworkerRoutingService({ store, router, auditStore }),+ asActor,+ ),);return { server, written, asked, defaults };}@@ -319,3 +324,14 @@ describe("recording why a message was not routed", () => {});});});++test("the HTTP adapter refuses oversized routing input with 400", async () => {+ const { server, asked, written } = app();+ const response = await post(server, { text: "x".repeat(10001) });+ expect(response.status).toBe(400);+ expect(await response.json()).toEqual({+ error: "A message of at most 10000 characters is required.",+ });+ expect(asked).toEqual([]);+ expect(written).toEqual([]);+});diff --git a/server/tests/routing-service.test.ts b/server/tests/routing-service.test.tsnew file mode 100644index 00000000..0a8a6bdb--- /dev/null+++ b/server/tests/routing-service.test.ts@@ -0,0 +1,785 @@+import { describe, expect, test } from "bun:test";+import type { AgentProfileStore } from "../src/agents/profile-store";+import type { AgentProfile } from "../src/agents/profile-types";+import type { AuditStore } from "../src/audit";+import type {+ IntentRouter,+ RoutingCandidate,+ RoutingUndecided,+} from "../src/routing/classify";+import {+ createCoworkerRoutingService,+ normalizeCoworkerName,+} from "../src/routing/service";++const ACTOR = { id: "u1", role: "user" } as const;++function profile(+ id: string,+ name: string,+ visibility: "public" | "private" = "public",+ ownerUserId: string | null = null,+): AgentProfile {+ return {+ id,+ name,+ title: name,+ roleDescription: `${name} work`,+ avatarSeed: id,+ visibility,+ ownerUserId,+ systemOwned: false,+ hidden: false,+ pinned: false,+ deletedAt: null,+ endpoint: null,+ hasAuth: false,+ hasCallbackToken: false,+ };+}++function makeService(+ options: {+ roster?: AgentProfile[];+ decision?: {+ agentId: string;+ reason: string;+ fallback: boolean;+ undecided: RoutingUndecided | null;+ };+ reachableSystems?: (agentId: string) => Promise<readonly string[]>;+ } = {},+) {+ const roster = options.roster ?? [+ profile("risk", "Risk Analyst"),+ profile("knowledge", "Knowledge"),+ ];+ const modelCalls: Array<{+ text: string;+ candidates: readonly RoutingCandidate[];+ defaultId: string;+ }> = [];+ const audits: Array<{+ payload: Record<string, unknown>;+ targetId: string | null;+ }> = [];+ const store = { list: async () => roster } as unknown as AgentProfileStore;+ const router = {+ route: async (+ text: string,+ candidates: readonly RoutingCandidate[],+ defaultId: string,+ ) => {+ modelCalls.push({ text, candidates, defaultId });+ const selected = options.decision ?? {+ agentId: "knowledge",+ reason: "matches what it is for",+ fallback: false,+ undecided: null,+ };+ const candidate = candidates.find(({ id }) => id === selected.agentId);+ return { ...selected, name: candidate?.name ?? selected.agentId };+ },+ } as unknown as IntentRouter;+ const auditStore = {+ insert: async (event: {+ payload: Record<string, unknown>;+ targetId: string | null;+ }) => {+ audits.push(event);+ },+ } as unknown as AuditStore;++ return {+ service: createCoworkerRoutingService({+ store,+ router,+ auditStore,+ reachableSystems: options.reachableSystems,+ }),+ modelCalls,+ audits,+ };+}++describe("CoworkerRoutingService", () => {+ test("refuses empty service input before asking the model", async () => {+ const { service, modelCalls, audits } = makeService();+ for (const text of ["", " "]) {+ await expect(service.route({ actor: ACTOR, text })).rejects.toThrow(+ "A message is required.",+ );+ }+ expect(modelCalls).toEqual([]);+ expect(audits).toEqual([]);+ });++ test("refuses oversized text before any routing, including picker selections", async () => {+ const { service, modelCalls, audits } = makeService();+ for (const agentId of [undefined, "risk"]) {+ await expect(+ service.route({ actor: ACTOR, text: "x".repeat(10001), agentId }),+ ).rejects.toThrow("A message of at most 10000 characters is required.");+ }+ expect(modelCalls).toEqual([]);+ expect(audits).toEqual([]);+ });++ test("accepts text at the routing limit", async () => {+ const { service, modelCalls } = makeService();+ await service.route({ actor: ACTOR, text: "x".repeat(10000) });+ expect(modelCalls[0]?.text).toHaveLength(10000);+ });++ test("distinguishes name inference from picker selection in the audit", async () => {+ const { service, audits, modelCalls } = makeService();+ await service.route({+ actor: ACTOR,+ text: "ask Risk Analyst to review this",+ });+ await service.route({ actor: ACTOR, text: "review this", agentId: "risk" });+ expect(audits[0]?.payload).toMatchObject({+ reason: "matched a coworker’s name in the message",+ viaMention: false,+ viaNameMatch: true,+ });+ expect(audits[1]?.payload).toMatchObject({+ reason: "named by the person asking",+ viaMention: true,+ viaNameMatch: false,+ });+ expect(modelCalls).toEqual([]);+ });++ test("a name that ends another coworker's name addresses only its own coworker", async () => {+ const { service, modelCalls } = makeService({+ roster: [profile("analyst", "Analyst"), profile("risk", "Risk Analyst")],+ });+ expect(+ await service.route({ actor: ACTOR, text: "ask analyst" }),+ ).toMatchObject({+ kind: "selected",+ agentId: "analyst",+ viaNameMatch: true,+ });+ expect(+ await service.route({ actor: ACTOR, text: "ask risk analyst" }),+ ).toMatchObject({ kind: "selected", agentId: "risk", viaNameMatch: true });+ expect(modelCalls).toEqual([]);+ });+ test("an issued discriminator label refuses a later coworker given that exact name", async () => {+ const roster = [+ profile("a", "Risk Analyst"),+ profile("b", "Risk Analyst"),+ profile("c", "Risk Analyst (id 61)"),+ ];+ const { service } = makeService({ roster });+ const label = "Risk Analyst (id 61) (2)";+ expect(+ await service.route({ actor: ACTOR, text: `ask ${label}` }),+ ).toMatchObject({ kind: "selected", agentId: "a" });+ roster.push(profile("d", label));+ const result = await service.route({ actor: ACTOR, text: `ask ${label}` });+ expect(result.kind).toBe("ambiguous");+ if (result.kind !== "ambiguous") throw new Error("Expected ambiguity");+ for (const choice of result.names) {+ expect(+ await service.route({ actor: ACTOR, text: `ask ${choice}` }),+ ).toMatchObject({ kind: "selected" });+ }+ });+ test("an issued id label cannot silently change recipient after a roster collision", async () => {+ const roster = [profile("a", "Risk Analyst"), profile("b", "Risk Analyst")];+ const { service } = makeService({ roster });+ const label = "Risk Analyst (id 61)";+ expect(+ await service.route({ actor: ACTOR, text: `ask ${label}` }),+ ).toMatchObject({ kind: "selected", agentId: "a" });+ // A coworker whose name merely ends with the label is a different name and changes nothing.+ roster.push(profile("c", "Senior Risk Analyst (id 61)"));+ expect(+ await service.route({ actor: ACTOR, text: `ask ${label}` }),+ ).toMatchObject({ kind: "selected", agentId: "a" });+ // One given the label as its exact name makes the label ambiguous rather than switch recipient.+ roster.splice(2, 1, profile("c", label));+ const result = await service.route({ actor: ACTOR, text: `ask ${label}` });+ expect(result.kind).toBe("ambiguous");+ if (result.kind !== "ambiguous") throw new Error("Expected ambiguity");+ for (const choice of result.names) {+ expect(+ await service.route({ actor: ACTOR, text: `ask ${choice}` }),+ ).toMatchObject({ kind: "selected" });+ }+ });+ test("duplicate labels remain unique beside a coworker whose literal name resembles a label", async () => {+ const { service } = makeService({+ roster: [+ profile("a", "Risk Analyst"),+ profile("b", "Risk Analyst"),+ profile("c", "Risk Analyst (id 61)"),+ ],+ });+ const result = await service.route({+ actor: ACTOR,+ text: "ask Risk Analyst",+ });+ expect(result.kind).toBe("ambiguous");+ if (result.kind !== "ambiguous") throw new Error("Expected ambiguity");+ expect(new Set(result.names).size).toBe(result.names.length);+ for (const name of result.names) {+ expect(+ await service.route({ actor: ACTOR, text: `ask ${name}` }),+ ).toMatchObject({ kind: "selected" });+ }+ });++ test("duplicate labels remain unique beside a coworker whose suffix alias resembles a label", async () => {+ const { service } = makeService({+ roster: [+ profile("a", "Risk Analyst"),+ profile("b", "Risk Analyst"),+ profile("c", "Senior Risk Analyst (id 61)"),+ ],+ });+ const result = await service.route({+ actor: ACTOR,+ text: "ask Risk Analyst",+ });+ expect(result.kind).toBe("ambiguous");+ if (result.kind !== "ambiguous") throw new Error("Expected ambiguity");+ expect(new Set(result.names).size).toBe(result.names.length);+ for (const name of result.names) {+ expect(+ await service.route({ actor: ACTOR, text: `ask ${name}` }),+ ).toMatchObject({ kind: "selected" });+ }+ });++ test("routes a unique explicit coworker name without invoking the model", async () => {+ const { service, modelCalls } = makeService();++ const result = await service.route({+ actor: ACTOR,+ text: "ask risk analyst to review this",+ });++ expect(result).toMatchObject({+ kind: "selected",+ agentId: "risk",+ viaMention: false,+ viaNameMatch: true,+ });+ expect(modelCalls).toEqual([]);+ });++ test("normalizes explicit names with NFKC, case, and whitespace", async () => {+ const { service, modelCalls } = makeService({+ roster: [profile("risk", "Risk Analyst")],+ });++ expect(+ await service.route({ actor: ACTOR, text: "Ask risk\tanalyst please" }),+ ).toMatchObject({+ kind: "selected",+ agentId: "risk",+ viaMention: false,+ viaNameMatch: true,+ });+ expect(modelCalls).toEqual([]);+ });++ test("does not match a coworker name inside a larger word", async () => {+ const { service, modelCalls } = makeService({+ roster: [profile("risk", "Risk")],+ });++ await service.route({ actor: ACTOR, text: "de-risking the portfolio" });++ expect(modelCalls).toHaveLength(1);+ });++ test("uses Unicode token boundaries instead of ASCII word boundaries", async () => {+ const { service, modelCalls } = makeService({+ roster: [profile("risk", "Risk")],+ });++ await service.route({ actor: ACTOR, text: "Risk\u{10400} review" });++ expect(modelCalls).toHaveLength(1);+ });++ test("leaves a word two coworkers' names end with to the model", async () => {+ const { service, modelCalls } = makeService({+ roster: [+ profile("risk", "Risk Analyst"),+ profile("data", "Data Analyst"),+ ],+ });++ expect(+ await service.route({ actor: ACTOR, text: "ask analyst to review this" }),+ ).toMatchObject({ kind: "selected", viaMention: false });+ expect(modelCalls).toHaveLength(1);+ });+ test("returns visible choices when two coworkers share the addressed full name", async () => {+ const { service, modelCalls } = makeService({+ roster: [profile("a", "Risk Analyst"), profile("b", "Risk Analyst")],+ });++ const result = await service.route({+ actor: ACTOR,+ text: "Risk Analyst, review this",+ });+ expect(result.kind).toBe("ambiguous");+ if (result.kind !== "ambiguous") throw new Error("Expected ambiguity");+ expect(result.names).toHaveLength(2);+ expect(modelCalls).toEqual([]);+ });+ test("prefers a unique longer explicit alias over a shared suffix", async () => {+ const { service, modelCalls } = makeService({+ roster: [profile("analyst", "Analyst"), profile("risk", "Risk Analyst")],+ });++ expect(+ await service.route({+ actor: ACTOR,+ text: "ask risk analyst to review this",+ }),+ ).toMatchObject({+ kind: "selected",+ agentId: "risk",+ viaMention: false,+ viaNameMatch: true,+ });+ expect(modelCalls).toEqual([]);+ });++ test("returns choices when two independent explicit names appear in long-to-short order", async () => {+ const { service, modelCalls } = makeService();++ expect(+ await service.route({+ actor: ACTOR,+ text: "ask Risk Analyst and Knowledge to review this",+ }),+ ).toEqual({+ kind: "ambiguous",+ names: ["Knowledge", "Risk Analyst"],+ });+ expect(modelCalls).toEqual([]);+ });++ test("returns choices when two independent explicit names appear in short-to-long order", async () => {+ const { service, modelCalls } = makeService();++ expect(+ await service.route({+ actor: ACTOR,+ text: "ask Knowledge and Risk Analyst to review this",+ }),+ ).toEqual({+ kind: "ambiguous",+ names: ["Knowledge", "Risk Analyst"],+ });+ expect(modelCalls).toEqual([]);+ });++ test("selects a profile when all explicit mentions refer to that same profile", async () => {+ const { service, modelCalls } = makeService();++ expect(+ await service.route({+ actor: ACTOR,+ text: "ask Risk Analyst and Risk Analyst to review this",+ }),+ ).toMatchObject({+ kind: "selected",+ agentId: "risk",+ viaMention: false,+ viaNameMatch: true,+ });+ expect(modelCalls).toEqual([]);+ });++ test("keeps partially overlapping full names as independent explicit choices", async () => {+ const { service, modelCalls } = makeService({+ roster: [profile("ann", "Ann Marie"), profile("curie", "Marie Curie")],+ });++ expect(+ await service.route({ actor: ACTOR, text: "ask Ann Marie Curie" }),+ ).toEqual({+ kind: "ambiguous",+ names: ["Ann Marie", "Marie Curie"],+ });+ expect(modelCalls).toEqual([]);+ });++ test("suppresses contained prefix aliases but retains a partially overlapping suffix name", async () => {+ const { service, modelCalls } = makeService({+ roster: [+ profile("ann", "Ann"),+ profile("ann-marie", "Ann Marie"),+ profile("curie", "Marie Curie"),+ ],+ });++ expect(+ await service.route({ actor: ACTOR, text: "ask Ann Marie Curie" }),+ ).toEqual({+ kind: "ambiguous",+ names: ["Ann Marie", "Marie Curie"],+ });+ expect(modelCalls).toEqual([]);+ });++ test("handles many repeated explicit mentions without changing their selection", async () => {+ const { service, modelCalls } = makeService();+ const text = Array.from({ length: 500 }, () => "Risk Analyst").join(+ " and ",+ );++ expect(await service.route({ actor: ACTOR, text })).toMatchObject({+ kind: "selected",+ agentId: "risk",+ viaMention: false,+ viaNameMatch: true,+ });+ expect(modelCalls).toEqual([]);+ });++ test("labels duplicate normalized names distinctly and resolves a chosen label", async () => {+ const { service, modelCalls } = makeService({+ roster: [+ profile("risk-id", "Risk Analyst"),+ profile("risk-copy", "Risk Analyst"),+ ],+ });++ expect(+ await service.route({+ actor: ACTOR,+ text: "ask risk analyst to review this",+ }),+ ).toEqual({+ kind: "ambiguous",+ names: [+ "Risk Analyst (id 7269736b2d636f7079)",+ "Risk Analyst (id 7269736b2d6964)",+ ],+ });+ expect(+ await service.route({+ actor: ACTOR,+ text: "ask Risk Analyst (id 7269736b2d636f7079) to review this",+ }),+ ).toMatchObject({+ kind: "selected",+ agentId: "risk-copy",+ viaMention: false,+ viaNameMatch: true,+ });+ expect(modelCalls).toEqual([]);+ });++ test("uses stable id labels when duplicate ids differ only by case", async () => {+ const roster = [+ profile("risk", "Risk Analyst"),+ profile("Risk", "Risk Analyst"),+ ];+ const { service, modelCalls } = makeService({ roster });++ const result = await service.route({+ actor: ACTOR,+ text: "ask risk analyst to review this",+ });+ expect(result).toEqual({+ kind: "ambiguous",+ names: ["Risk Analyst (id 5269736b)", "Risk Analyst (id 7269736b)"],+ });+ expect(new Set(result.names.map(normalizeCoworkerName)).size).toBe(+ result.names.length,+ );+ expect(+ await service.route({+ actor: ACTOR,+ text: "ask Risk Analyst (id 5269736b) to review this",+ }),+ ).toMatchObject({ kind: "selected", agentId: "Risk" });+ expect(modelCalls).toEqual([]);+ });++ test("uses NFKC-distinct id labels with an order-independent mapping", async () => {+ const optionA = profile("A", "Risk Analyst");+ const optionFullWidthA = profile("A", "Risk Analyst");+ const forward = makeService({ roster: [optionFullWidthA, optionA] });+ const reverse = makeService({ roster: [optionA, optionFullWidthA] });++ const forwardResult = await forward.service.route({+ actor: ACTOR,+ text: "ask risk analyst to review this",+ });+ const reverseResult = await reverse.service.route({+ actor: ACTOR,+ text: "ask risk analyst to review this",+ });++ expect(forwardResult).toEqual({+ kind: "ambiguous",+ names: ["Risk Analyst (id 41)", "Risk Analyst (id efbca1)"],+ });+ expect(reverseResult).toEqual(forwardResult);+ expect(+ await forward.service.route({+ actor: ACTOR,+ text: "ask Risk Analyst (id 41) to review this",+ }),+ ).toMatchObject({ kind: "selected", agentId: "A" });+ expect(+ await forward.service.route({+ actor: ACTOR,+ text: "ask Risk Analyst (id efbca1) to review this",+ }),+ ).toMatchObject({ kind: "selected", agentId: "A" });+ });++ test("keeps a duplicate label bound to its id when new duplicates are added or reordered", async () => {+ const idA = profile("a", "Risk Analyst");+ const idB = profile("b", "Risk Analyst");+ const addedEarlier = profile("A", "Risk Analyst");+ const original = makeService({ roster: [idB, idA] });+ const expanded = makeService({ roster: [idB, addedEarlier, idA] });+ const stableLabel = "Risk Analyst (id 62)";++ expect(+ await original.service.route({+ actor: ACTOR,+ text: "ask risk analyst to review this",+ }),+ ).toEqual({+ kind: "ambiguous",+ names: ["Risk Analyst (id 61)", stableLabel],+ });+ expect(+ await expanded.service.route({+ actor: ACTOR,+ text: "ask risk analyst to review this",+ }),+ ).toEqual({+ kind: "ambiguous",+ names: ["Risk Analyst (id 41)", "Risk Analyst (id 61)", stableLabel],+ });+ expect(+ await expanded.service.route({+ actor: ACTOR,+ text: `ask ${stableLabel}`,+ }),+ ).toMatchObject({ kind: "selected", agentId: "b" });+ });++ test("uses normalization-safe labels for base64url case collisions", async () => {+ const first = profile("\u0800", "Risk Analyst");+ const second = profile("\u081A", "Risk Analyst");+ const { service } = makeService({ roster: [second, first] });++ const result = await service.route({+ actor: ACTOR,+ text: "ask risk analyst to review this",+ });++ expect(result).toEqual({+ kind: "ambiguous",+ names: ["Risk Analyst (id e0a080)", "Risk Analyst (id e0a09a)"],+ });+ expect(new Set(result.names.map(normalizeCoworkerName)).size).toBe(+ result.names.length,+ );+ expect(+ await service.route({+ actor: ACTOR,+ text: "ask Risk Analyst (id e0a080) to review this",+ }),+ ).toMatchObject({ kind: "selected", agentId: "\u0800" });+ expect(+ await service.route({+ actor: ACTOR,+ text: "ask Risk Analyst (id e0a09a) to review this",+ }),+ ).toMatchObject({ kind: "selected", agentId: "\u081A" });+ });++ test("returns none for an absent or empty visible roster", async () => {+ const { service } = makeService({ roster: [] });++ expect(await service.route({ actor: ACTOR, text: "anything" })).toEqual({+ kind: "none",+ });+ });++ test("returns none when an explicit composer id is inaccessible", async () => {+ const { service, modelCalls } = makeService({+ roster: [+ profile("risk", "Risk Analyst"),+ profile("private", "Private Analyst", "private", "u2"),+ ],+ });++ expect(+ await service.route({+ actor: ACTOR,+ text: "anything",+ agentId: "private",+ }),+ ).toEqual({ kind: "none" });+ expect(modelCalls).toEqual([]);+ });++ test("falls back to intent routing when no explicit name appears", async () => {+ const { service, modelCalls } = makeService();++ expect(+ await service.route({ actor: ACTOR, text: "what is our PTO policy" }),+ ).toMatchObject({+ kind: "selected",+ agentId: "knowledge",+ viaMention: false,+ });+ expect(modelCalls).toHaveLength(1);+ });++ test("routes on purpose alone when coworker reachability cannot be loaded", async () => {+ const { service, modelCalls } = makeService({+ reachableSystems: async () => {+ throw new Error("private reachability detail");+ },+ });++ expect(+ await service.route({ actor: ACTOR, text: "help me" }),+ ).toMatchObject({ kind: "selected", agentId: "knowledge" });+ expect(modelCalls).toHaveLength(1);+ expect(modelCalls[0]?.candidates.map((c) => c.reaches)).toEqual([[], []]);+ });+ test("passes only the actor-visible roster to intent routing", async () => {+ const visible = profile("mine", "My Private", "private", ACTOR.id);+ const inaccessible = profile("other", "Other Private", "private", "u2");+ const deleted = {+ ...profile("deleted", "Deleted", "public"),+ deletedAt: new Date(),+ };+ const { service, modelCalls } = makeService({+ roster: [profile("public", "Public"), visible, inaccessible, deleted],+ });++ await service.route({ actor: ACTOR, text: "anything" });++ expect(modelCalls[0]?.candidates.map(({ id }) => id)).toEqual([+ "public",+ "mine",+ ]);+ });++ test("writes selected audit fields exactly once without message text", async () => {+ const { service, audits } = makeService();++ await service.route({ actor: ACTOR, text: "private payroll details" });++ expect(audits).toHaveLength(1);+ expect(audits[0]).toMatchObject({ targetId: "knowledge" });+ expect(audits[0]?.payload).toEqual({+ chosen: "knowledge",+ reason: "intent match",+ fallback: false,+ viaMention: false,+ viaNameMatch: false,+ candidates: ["risk", "knowledge"],+ undecided: null,+ });+ expect(JSON.stringify(audits[0])).not.toContain("private payroll details");+ });++ test("preserves a model fallback audit cause", async () => {+ const { service, audits } = makeService({+ decision: {+ agentId: "knowledge",+ reason: "sent to your default while the router was unreachable",+ fallback: true,+ undecided: "unreachable",+ },+ });++ await service.route({ actor: ACTOR, text: "anything" });++ expect(audits[0]?.payload).toMatchObject({+ fallback: true,+ undecided: "unreachable",+ });+ });++ test("does not persist a model reason that echoes the message", async () => {+ const text = "private payroll details for Sam";+ const { service, audits } = makeService({+ decision: {+ agentId: "knowledge",+ reason: text,+ fallback: false,+ undecided: null,+ },+ });++ const result = await service.route({ actor: ACTOR, text });++ expect(result).toMatchObject({ kind: "selected", reason: text });+ expect(audits[0]?.payload.reason).toBe("intent match");+ expect(JSON.stringify(audits[0])).not.toContain(text);+ });+ test("does not route on words in the shipped coworker names, or on a name mentioned in passing", async () => {+ const roster = [+ profile("general", "General Assistant"),+ profile("knowledge", "Knowledge"),+ profile("risk", "Risk Analyst"),+ profile("expense", "Expense Review"),+ profile("vendor", "Vendor Review"),+ profile("interview", "Interview Notes"),+ profile("release", "Release Notes"),+ profile("followups", "Meeting Follow-ups"),+ ];+ for (const text of [+ "Please review this contract for compliance risks",+ "Summarize my meeting notes",+ "I need an assistant to book travel",+ "What does our knowledge base say about refunds?",+ "Don't send this to Risk Analyst, it's about expenses",+ ]) {+ const { service, modelCalls } = makeService({ roster });+ const result = await service.route({ actor: ACTOR, text });+ expect({ text, kind: result.kind }).toEqual({ text, kind: "selected" });+ expect({ text, model: modelCalls.length }).toEqual({ text, model: 1 });+ }+ });++ test("routes a message that addresses a shipped coworker by its full name", async () => {+ const roster = [+ profile("risk", "Risk Analyst"),+ profile("expense", "Expense Review"),+ profile("knowledge", "Knowledge"),+ profile("followups", "Meeting Follow-ups"),+ ];+ for (const [text, agentId] of [+ ["Risk Analyst, please check this vendor", "risk"],+ ["hey Expense Review: is this claim within policy?", "expense"],+ ["Hi @Knowledge what is our refund policy", "knowledge"],+ ["can you ask Meeting Follow-ups to pull the actions", "followups"],+ ["send this to @Risk Analyst please", "risk"],+ ["Knowledge", "knowledge"],+ ] as const) {+ const { service, modelCalls } = makeService({ roster });+ expect(await service.route({ actor: ACTOR, text })).toMatchObject({+ kind: "selected",+ agentId,+ viaNameMatch: true,+ });+ expect({ text, model: modelCalls.length }).toEqual({ text, model: 0 });+ }+ });+});