Naalya Handbook
AI system

The RPC hop

One agent tool call from model.invoke to the domain service. The worker proxy, the RabbitMQ call, execute(), tenant scope, the two auth postures, and audit.

You declared the tool in Defining a tool. This page follows one call in the order it runs. HTTP guards don't run on RabbitMQ, so execute() is the only thing between the model and your service: skip it and you skip parsing, tenant fail-closed, the ability rebuild, the permission gate and audit.

The worker side

HelperFileJob
resolveIdentity, resolveCallScopecore/tools/tool-context.tsWho is calling and which campus, only from the runtime context the server minted. Never from model arguments. Campus mode pins campusId
resolvePermissionsSameThe caller's CASL snapshot, for shaping what Rover offers. Never for deciding whether a tool may run
CONTEXT_MISSING_ERRORSameReturned when identity or scope is missing. Says "Do not retry", because agents retry errors
toRpcProxycore/tools/build-agent-tools.tsThe one generic wrapper for every RPC tool: read context, send definition.event, stringify the reply. Emits streamOnSuccess only on success. Strips em dashes from the description. Never fork it
AgentToolService.callcore/tools/agent-tool.service.tsSends over RabbitMQ with a 10-second timeout. Logs argument keys and result size, never values. Turns transport failures into "infrastructure, do not retry" errors
buildAgentToolscore/tools/build-agent-tools.tsRover's tools for this turn: RPC tools for the run mode, minus role-only ones, minus tools whose feature is off for the school, plus local tools
buildRoleToolsSameOne specialist's tools (role plus shared), feature-filtered, plus ask_user stamped with the role
selectSubagentscore/subagents/index.tsWhich specialists join this turn, from server-resolved capabilities. The model can't add one

Tools are built per turn, never cached. There's no per-specialist tool array to edit: tag roles on the definition.

Two more rules sit in build-agent-tools.ts at main a888ae352ca2d6ece9d22bf3c0ac90fcb01a425f, which shares a tree with staging b0a3d7eb.

toRpcProxy treats an afterId of 00000000-0000-0000-0000-000000000000 as no cursor, so the call is the first page. The comment says a model fills an optional cursor with that id. The compare has no unit test for that line.

buildRoleTools takes a background flag. RoverJobRunner sets background on the job context, and the three role subagents pass it through. A background co-worker keeps tools whose event is not a mutating verb, plus save.lesson_material, and it does not get propose. Other save events are mutating, so they are dropped. A chat turn leaves the flag unset, so it still gets the mutating tools and propose. The unit test names save_to_week_folder, ask_user, get_scheme_of_work, and list_lesson_plans as kept, and create_scheme_of_work, delete_lesson_plan, and propose as dropped. The test was read and not run. isMutatingEvent classifies by the verb before the dot. That file was not in the compare.

The server side

Every handler is a @MessagePattern(tool.event) on AgentToolsController that must call this.execute(payload, schema, posture, fn). fn gets parsed args and a jwt rebuilt from the identity; use jwt, never args, for who is acting.

Identity. No sub or type: Missing tool-call identity.

Parse. The tool's Zod schema; failure is Invalid tool arguments: ....

Tenant. A non-platform user with no school fails closed (No school context for this user.). inTenantScope runs platform admins unscoped and everyone else inside withSchool.

Ability. A fresh CASL ability is built inside that tenant frame and placed in permissionScopeStore for both postures. Without it, services with a "no ability means a trusted job" carve-out would fail open; a subject teacher once got a whole-class gradebook that way.

Posture. runInToolScope (CASL) or runInRelationshipToolScope (relationship), below.

Audit. On { data } with posture.audit set, auditToolWrite writes exactly one row, taking schoolId from the JWT.

Errors. Any throw becomes { error } via toToolError: an HttpException message passes through; anything else is logged and masked as "That action could not be completed. Do not retry; tell the user what you were trying to do."

The two postures

apps/server/src/app/naalya-ai/agent-tools.controller.ts
type ToolPosture<T> =
  | { auth: 'casl'; gate: { action: Action; resource: Resource }; audit?: ToolAuditDescriptor<T> }
  | { auth: 'relationship'; scopeNote?: string; audit?: ToolAuditDescriptor<T> }
caslrelationship
AsksDoes the user's role allow action on resource?Does the user personally own or teach this?
Gateability.can(...) before fn; denied means fn never runsNone in execute; the service throws if the relationship doesn't hold
scopeContextA sentence derived from the CASL rules (whole school, own records, assigned campuses, or filtered)A fixed note (below)
Use whenThe HTTP twin is @RequirePermissions(X, Y); copy that pairThe service takes jwt.sub and asserts assignment, headship, or "your own school"

Anything else doesn't compile: auth is required, gate is only legal (and required) on casl, scopeNote only on relationship.

Writes need audit; reads must omit it. isMutatingEvent(tool.event) decides which, and the write-audit spec fails a mutating tool without an audit row, or a CASL read that has one.

A handler, line by line

apps/server/src/app/naalya-ai/agent-tools.controller.ts
@MessagePattern(createDepartmentTool.event)
createDepartment(@Payload() payload: AgentToolPayload[typeof createDepartmentTool.event]) {
  const pinned = payload?.scope?.campusId
  return this.execute(
    payload,
    createDepartmentTool.schema,
    {
      auth: 'casl',
      gate: { action: Action.CREATE, resource: Resource.DEPARTMENT },
      audit: {
        action: ActionAuditAction.CREATE,
        resourceType: AuditResourceType.DEPARTMENT,
        resourceId: (result: DepartmentEntity) => result.id,
      },
    },
    ({ campusId: requested, ...dto }, jwt) =>
      this.departmentService.create({ ...dto, campusId: pinned ?? requested }, jwt),
  )
}
  • The event name must match the tool's, or the worker times out.
  • In campus mode the envelope's campus wins over the model's.
  • The gate is the same pair as POST /departments.
  • fn calls the same service the HTTP controller uses, with jwt as the actor.

Choosing a posture

Find the HTTP handler for the same operation.

@RequirePermissions(X, Y) with no "you must teach this" check in the service: casl with that gate.

The service takes jwt.sub and asserts assignment, headship or own school: relationship.

Both? Match what the service actually enforces. deleteDepartment is relationship, because being head is enough.

Where to go next

On this page