What happens on a chat turn
Follow one staff message from the Hub through the worker graph, a remote procedure call to the server, and the streamed reply.
A staff member types a sentence and hits send. This page is that turn, in order, so when something is missing (wrong campus, a tool the model never reaches, a permission error in the reply) you know which hop to open.
You do not need this page to add a tool. You need it the first time a tool "doesn't fire" and you are staring at four processes.
This diagram is the whole turn. When the worker asks the server to run a tool, it sends a remote procedure call (RPC) over RabbitMQ. The sections below take each step in order.
The server starts reading before it hands the turn over (afterReadStarted in NaalyaAiService), so no early event is missed. Because the reply lives in a Redis stream, a Hub that reconnects can replay it from the last chunk it saw.
1. The Hub opens a stream
The Education Hub does not call api.op for chat. It streams. useChat (and the Rover stream hook) posts to the naalya-ai chat endpoint with the bearer token every other request already uses. The server authenticates the staff member, mints the runtime context, and hands the turn to the worker with a RabbitMQ emit on naalya-agent. The worker writes what it produces to a Redis stream for that caller. The server reads that stream and sends it to the Hub as server-sent events, which the Hub renders as they arrive.
The context is the whole security story for the turn. It is built on the server from the JWT and live database rows, then passed to LangGraph as runtimeContext. The model never supplies it.
What goes in:
- Who,
userDetails: name, email, user id, profile id, user type, school, optional campus. - Where,
runMode:schoolorcampus(campus mode always carries a campus id and name; a campus mode with no campus is a type error). - What they may do:
userPermissions, a flattened CASL snapshot. Advisory only. It stops Rover offering work that will fail. It is never the authorization decision: that is rebuilt on every RPC call. - Which specialists exist this turn,
capabilities: class teacher, subject teacher, director of studies. - The calendar: current academic year and terms, so "this term" does not need a lookup.
- The teaching map: class/subject assignments, omitted for non-teachers rather than sent empty.
- This message's attachments, not the whole thread.
Run mode is not an authorization boundary
A client that lies about school vs campus only changes what Rover offers. Every RPC result is still filtered by a freshly rebuilt CASL ability. The server validates mode anyway, because a wrong mode makes Rover confidently misdescribe its own answers.
2. The worker builds the graph
createRoverGraph runs per turn. Nothing about the caller's tools or prompt is cached across messages: if their roles changed five seconds ago, the next turn already reflects it.
The graph is createDeepAgent with:
- Rover's tools:
buildAgentTools, RPC proxies for this run mode, plus local tools, plus backend-bound tools (save_artifact, ...) when a sandbox is mounted. - Skills from
skillSourcesForWireId('rover'):/skills/general/then/skills/rover/. - Role subagents from
selectSubagentsonly whencapabilitiessays they exist. Each subagent is its own compiled graph, with its own tools (buildRoleTools) and skills. They do not inherit Rover's.
The system prompt is assembled, not hand-maintained as a tool list: supervisor copy + a tool inventory derived from the same array the graph receives + a delegate roster derived from the same subagents array. If a tool is missing from the inventory, it is missing from the graph: they cannot drift.
3. The model calls a tool
Rover (or a subagent) picks a tool by name: create_department, get_current_date. What happens next depends on which kind it is.
Local. The handler runs in the worker. No RabbitMQ. Used for a clock, asking the staffer a question, listing the agent map, sandbox files. See Adding a local tool.
RPC. The generic proxy in build-agent-tools.ts does the same three things for every tool. The helpers it calls: resolveIdentity, resolveCallScope, toRpcProxy, AgentToolService.call: are the RPC hop, in that order.
- Take identity and call scope from the runtime context: never from model arguments.
toolCaller.call(definition.event, { identity, scope, args })over the agent-tool queue.- Stringify
{ data, scopeContext }or{ error }back to the model.
The event (create.department) is the RabbitMQ message pattern. The name (create_department) is what the model and the Hub label registry see. They are allowed to differ; keep the event verb.subject and the name verb_subject. How those fields are declared: Defining a tool.
4. The server executes
AgentToolsController listens with @MessagePattern(tool.event). Every handler funnels through execute(). The numbered list below is the outline; every helper on this hop, payload shape, both postures, audit, is The RPC hop.
- Reject a payload with no identity.
- Parse
argsagainst the shared Zod schema. - Fail closed if the identity has no tenant (
NO_TENANT_SCOPE_ERROR). - Rebuild the CASL ability inside tenant scope: no HTTP middleware ran on this path.
- Run the posture:
caslgoes throughrunInToolScope(permission gate + tenant frame);relationshipgoes throughrunInRelationshipToolScope(the domain service asserts ownership itself). - On a successful write, emit exactly one audit row. HTTP
@Auditinterceptors do not run on RPC.
The service method is the same one the REST controller calls. The tool does not reimplement the domain.
5. The model reads the envelope
Both kinds of tool return the same shape, so the model has one contract:
type AgentToolResult<T> =
| { data: T; scopeContext: string }
| { error: string };scopeContext is a sentence about how filtered the data is: school-wide vs this campus. The prompt tells the model to qualify its language from that field, so a campus-scoped user hears "across your campus" rather than a fake whole-school number.
A denied permission is { error: 'Permission denied...' }, not an HTTP 403. The model can explain it; the Hub hides failed tool rows from the activity timeline and lets Rover's reply carry the news.
6. The Hub narrates
As tool calls stream, the Hub looks up the tool name in src/components/rover/activity/tool-labels.ts and draws a line ("Creating a department..."). No label means fallback copy derived from the verb: awkward for verbs like upsert or recompute. Treat the label as part of shipping the tool. The RPC how-to includes that step.
7. Stopping a turn
While a reply is running, the Hub's Send button becomes Stop. It calls POST /api/v1/naalya-ai/staff/chat/stop (naalyaAiStaffChatStop), which needs a staff user and the staff AI chat feature, and answers 204 whether or not a turn is running. Guest chat has no stop route.
The flag lives on the caller's chat stream, so a stop reaches whichever worker runs their turn (ChatStreamService.requestStop). When the next turn claims the stream, it deletes any flag left over, so a late stop cannot end the wrong turn. The worker polls the flag twice a second (watchStop in apps/worker/src/naalya-agent/core/turn-stop.ts), so a stop can take up to half a second to land.
Stopping undoes nothing. closeStoppedThread answers every tool call the abort left open with Stopped by the teacher before this finished., because the model API rejects a call with no result. Then it adds a note for Rover's next turn, which tool calls finished and what they returned, which were cut off part-way and may or may not have gone through, and how much of the reply Rover had written. The note tells Rover not to carry on unless asked. The turn is saved and marked stopped, and the Hub shows You stopped this reply in the transcript.
A model that refuses a request now ends the turn with I can't help with that one. Try asking another way. instead of the general failure message, because a refusal comes back the same on a retry.
Read at API a30a8858 and Hub b4655217. No turn was stopped in a running app.
File reads, plans, and one preview
These three are on main a888ae352ca2d6ece9d22bf3c0ac90fcb01a425f, which shares a tree with staging b0a3d7eb. No file was read through a running agent, and no preview was rendered.
LeanReadMiddleware is mounted on Rover and on the three role subagents. When read_file returns a string, a data: base64 run of 2,000 characters or more is replaced with a note that the data was left out and is still in the file. Shorter embedded data is left as it is. Other tools are unchanged. The unit test was read and not run.
createPlanMiddleware passes a two-sentence description for write_todos: write or update the full list, each step pending, in progress, or completed, and send the whole list every time. The comment says the library description is about 4,000 characters. That length was not measured.
preview_document allows one preview per document. A later call for the same path returns an error that tells the model to hand over its best version. A call with fromPage does not spend that preview. The prompt in files.prompt.ts and the print-html skill say to list every fault from that one preview and fix them in one pass.
If something looks wrong
| Symptom | First place to look |
|---|---|
| Model never calls your tool | Description, scope vs run mode, roles vs who is chatting: placement on the contract |
Tool called, { error: Permission denied } | Handler gate vs the caller's CASL rules |
| Tool called, empty list | Tenant / campus / year filters on the service, not the tool wrapper |
| Wrong campus's data | Envelope pin: payload.scope.campusId must win over model campusId |
| Chat line missing in the Hub | Tool label map: name must match create_department, not create.department |
| Skill never loads | Folder name = frontmatter name, persona folder, webpack copy in prod |
Where to go next
Choosing RPC or local
Does this tool touch school data? That decides which how-to you follow.
The shared contract
Runtime context, identity, and the request/result envelope.
The RPC hop
Every worker and server helper, in the order this turn just ran.
Queues & Messaging
The RabbitMQ request/response channel the RPC hop uses.
How the AI system works
Rover and the role subagents, where they run, how they reach school data, and the difference between a tool and a skill.
The shared contract
What the worker and server agree on, the runtime context minted at dispatch, the identity that rides every call, and the request/result envelope.