OPSOpen Post-Training System

A research engineering field guide

From a model to a multi-agent systemPart 2

One agent decision moves around the system A connected clockwise flow from a World observation to an agent's identity and context, through the shared model, into an Action proposal, then through trusted Checks to a stored Result. The Result becomes available on a later scheduled turn. The episode orchestrator in the center controls turn order. observation prompt text proposal checked next turn EPISODE ordered schedule one turn at a time WORLDobservation AGENTidentity + context MODELshared Qwen3 weights ACTIONparsed proposal CHECKSmessage / tool gate RESULTmessage / tool result

Part 1 showed how I built Qwen3-0.6B and made it generate text. Part 2 follows what happens after that: how separate agents get their own instructions and information, communicate, use tools, and act in a sandboxed environment.

↗Read Part 1 on SubstackQwen3-0.6B, JAX, tokenizer, generation and KV cache
Source-groundedInteractive diagramsReadable without JavaScript

01 / The handoff

Part 1 ends at the model boundary

In Part 1, we built Qwen3-0.6B and followed how it loads its weights, processes text and generates tokens. We ended with a key idea: a model that can generate text is only one half of an RL system. Part 2 picks up at that point. It follows one decision through the other half: an agent receives its own instructions and view, the model turns that input into an action proposal, and trusted code routes the proposal to a message board or a tool in the environment.

This codebase now contains the foundations for agent identities, communication, tools, sandboxed environments and episode orchestration. A connected durable trajectory recorder, a complete evaluation framework and the RL training loop are still future work. We will start at the boundary between the model and an agent decision, then follow that decision through the components that receive and check it.

Our route through the codeAgentSpec gives an agent its stable identity. AgentSession tracks one episode. Observation describes what it may see. Action records what it proposes. Registries, a message board, context manager, tools, environment, and orchestrator connect those records.

Why this is the handoff point

In Part 1 the central object was the model: parameters are loaded, tokens are encoded, and a decoder predicts the next token. Here the central object becomes a decision. A decision has an owner, a view of the world, a time in an episode, and a result that must be checked. We keep this story anchored to the committed repository snapshot named above so readers can compare each claim with the source at the linked path.

The practical question that guides every section is: which trusted component owns this piece of information? The registry owns identity, the environment owns authoritative state, the board owns message records, and the orchestrator owns order. A model response is only an input to those components. It does not become truth because it is fluent.

02 / The contracts

Start with AgentSpec

A useful first distinction is between the agent’s durable definition and its temporary state. The prompt and permissions belong to the definition. Turn count and message cursor belong to the episode session.

ContractWhat it recordsLifetime
AgentSpecID, name, kind, system prompt, communication and tool permissionsScenario / registry
AgentSessionAgent ID, episode ID, status, turn count, consumed-message cursorOne agent in one episode
MessageSender, recipient, content, episode, step and timestampEpisode conversation
ObservationAgent-scoped visible state plus addressed messagesOne decision step
ActionTyped proposal tied to its agent, episode and observationOne decision step

AgentSpec, Message, Observation, and Action are frozen dataclasses. JSON-shaped payloads are copied into immutable mappings/tuples and can be converted with to_dict()/from_dict(). AgentSession is mutable lifecycle state; it does not hold the conversation transcript or tool outputs.

These contracts validate identity fields, nonnegative step counts, timestamps and cross-record references. For example, Action.validate_against(observation) rejects an action tied to a different agent, episode, step, or observation ID. It does not decide whether an action is authorized or execute it.

Read the records by lifetime

Start with AgentSpec: scenario setup creates it, and an episode may use the same immutable definition for every turn. Then read AgentSession: the orchestrator creates one per agent for that episode and reuses it when the schedule names that agent again. The Observation is short-lived and specific to one decision. The Action points back to that Observation, so a downstream component can reject a response that belongs to an earlier or different decision.

This is deliberately a small contract set. We do not put every record in a universal base class or create a generic event hierarchy. Each type exists because more than one package needs to agree on its fields. A type that has one consumer and no meaningful boundary may stay local to that consumer. That keeps the shared core from becoming a dumping ground for application-specific state.

Core records: what feeds the next record?

Scenario definitionAgentSpecstatic ID, prompt, kind, communication rules and tool grants
+ episode starts
Episode bookkeepingAgentSessionmutable status, successful turn count and consumed-message cursor
+ agent-visible messages
Communication recordMessageepisode, sender, recipient, content, step, timestamp
↓ environment combines scoped state
Decision inputObservationagent + episode + step + visible state + addressed messages
↓ model proposes
Decision outputActionsource Observation ID + agent + episode + step + structured payload
Explore the architecture

Choose a component

Each card links a real contract or module in the committed source.

SOURCE ATLAS / HOW THE MODULES FIT

Read the system as connected layers

These drawings name the real source files and the job each one performs. They are maps of the committed implementation, not just a package tree. Follow the arrows to see which component prepares data, which component checks it, and which component owns the final effect.

Start with the system map: one hub, its working modules, and their children

The episode orchestrator sits at the center because it decides when a component is called. The colored rectangles form the orbit: each arrow names the information passed to the next module. Dotted spokes show which modules the orchestrator coordinates. The vertical diagrams later in the article open each module and show which submodules own its work.

The communication and action loopFollow the solid arrows clockwise. A scheduled agent receives a scoped view, builds a prompt, asks the shared model, and proposes an action. Trusted checks either store a message or run a tool. The resulting record reaches an agent through a later Observation.
The connected Open Post-Training System module orbit At the center, EpisodeOrchestrator controls the schedule. Around it, seven connected rectangular modules form a clockwise loop: World, Agent, Runtime, Model, Action, Checks, and Result. Result data returns to the World on a later scheduled turn. Observation identity + context prompt text proposal authorized next scheduled turn EPISODE EpisodeOrchestrator run_episode() ordered schedule · cleanup one step at a time WORLDbuild_observation()scoped view · unread · results AGENTAgentSpec + AgentSessionregistry · context manager RUNTIMEAgentRuntime.run_turn()validate · prompt · parse MODELQwen3Backend.generate()shared weights · fresh cache ACTIONaction_parser.pystrict proposal · no side effect CHECKSMessageBoard · Dispatcherpermission · schema · execution RESULTMessage · SendResultToolResult · sequence record

How agents talk: for a message action, the checks call MessageBoard.send() with the trusted sender. The board stores a sequenced Message for the recipient; it does not wake that recipient. When the schedule later runs the recipient, the board returns the unread message and the World places it in that agent’s Observation. For a tool action, the dispatcher returns a private ToolResult, which is supplied to that same agent’s later Observation.

solid arrow = data passed to the next moduledotted spoke = module coordinated by EpisodeOrchestrator

The orbit above shows the main modules talking to one another. Vertical call maps are placed beside their explanations: agent identity and context, runtime and model generation, message/tool checks, environment services, and episode orchestration.

03 / Independent identities

Ten agents can share one model without becoming one agent

The scenario file is the canonical roster. AgentRegistry.from_scenario() reads its definitions, resolves each prompt relative to the scenario directory, and constructs one AgentSpec per entry.

The Kashmir scenario distinguishes five main agents from five people agents. Each has an independent prompt and permission declaration. Ubaid may message Insha, and may message Sahil only when the technical_demonstration_requested condition is true. These are declarative permissions; the MessageBoard evaluates them at send time using the supplied conditions.

The prompt loader reads UTF-8 text without normalizing it and rejects missing, out-of-directory, or empty prompt files. The site intentionally does not republish full role prompts. Runtime identity comes from the trusted AgentSpec and AgentSession supplied by the orchestrator, not from a model-generated claim.

Follow the identity load in code

The normal call is AgentRegistry.from_scenario("tasks/scenarios/kashmir/scenario.json"). Use registry.get("agent_1") for a single definition or registry.list_main_agents() and registry.list_people_agents() when the caller needs a group. IDs are exact string identifiers; agent_3 and people_3 are separate keys even though both end in the digit 3.

The scenario grants are authoritative for the board and dispatcher. Prompt prose can tell an agent what is appropriate, but that prose is not a permissions engine. This lets an evaluator vary the prompt or test a malicious output while leaving access control in trusted code. The tradeoff is that a permission change must be made in the scenario and checked through the policy-enforcing component; editing only the prompt will not change the actual grant.

Agent identity: scenario file to episode session

1 · Scenario assetsscenario.json + agent prompt filesone ID, kind, prompt path, communication rules and tool grants per agent
↓ PromptLoader resolves a safe scenario-relative file
2 · PromptLoader.load()agents/prompt_loader.pyreads the original UTF-8 text; rejects missing, empty or out-of-directory paths
↓ AgentRegistry validates and registers unique IDs
3 · AgentRegistry.from_scenario()agents/registry.pyconstructs one immutable AgentSpec per entry
↓ the episode starts
4 · AgentSessionagents/orchestrator.pyone mutable session per agent per episode; reused for every scheduled appearance
↓ history is stored separately
5 · AgentContextManager(episode_id, agent_id)keeps prompt-ready context isolated from other agents and episodes
scenario.json→PromptLoader→AgentRegistry→AgentSpec × 10

04 / Communication

A message is stored, authorized, and read as an observation

The MessageBoard is a synchronous, in-memory episode store. It does not wake agents. The orchestrator chooses the next scheduled agent; the board provides that agent’s unread inbox when it runs.

Interactive visualization A

Send a permitted message

local example
No messages in this example inbox yet.
Board sequence: 0Recipient cursor: 0Ready

The committed board stores messages by episode with a global sequence number for ordering. Retrieval is scoped to the authenticated session’s agent and episode; consumption advances that session’s cursor. The orchestrator passes unread messages into Environment.build_observation(), then advances the cursor once the action has been validated.

A message record is not a wake-up signal

The API separates storage from scheduling. A call to MessageBoard.send(...) checks sender permissions and appends a sequenced message. Later, when the orchestrator reaches that recipient, get_unread(session) returns messages beyond its cursor. mark_consumed(session, through_sequence) advances the cursor after the message has actually been presented in a valid turn. The board does not start a thread, send a push event, or run an agent in the background.

This design makes message timing explicit in the schedule and keeps tests deterministic. It also means “sent” and “read” are separate facts: a message may be stored while the recipient is never scheduled again. The board returns a rejection for a denied send, so the caller can record the policy outcome without pretending the recipient received anything.

Communication submodules: how Agent A reaches Agent B

1 · Agent A proposessend_message(recipient_id, content)the model supplies recipient and content; trusted orchestrator supplies sender identity
↓
2 · Board checks the sender ruleMessageBoard._permission_decision()blocked, allowed, or conditional recipient rule; missing condition means deny
↓ accepted only
3 · MessageBoard stores a Messageepisode sequence + sender + recipient + timestampreturns SendResult; a stored record does not wake the recipient
↓ when the schedule later selects Agent B
4 · Recipient inbox is readget_unread(session)filters by Agent B’s session, episode, recipient ID, and consumed cursor
↓
5 · World includes the inboxObservationBuilder.build()the message appears in Agent B’s Observation and then B’s prompt
↓ after B returns a valid Action
6 · Cursor advancesmark_consumed(session, through_sequence)B will not receive the same message as unread again

05 / Inference

One set of weights, separate requests

The Qwen3 backend is shared, while the request is assembled for the current agent. Each call carries that agent’s system prompt, rendered context, current Observation, and only the tool specifications authorized for that agent.

AgentSpec promptStored contextCurrent ObservationAuthorized ToolSpecs
→
Qwen3Backendshared weights
one generation request
→
generated textJSON Actionvalidated proposal

load_shared_backend() protects a process-wide singleton with a lock. Qwen3Backend.from_config() resolves the checkpoint and tokenizer paths and loads them once. Each generation call gets a fresh KV cache through the existing generation function; the cache accelerates token decoding within that request and is not cross-agent memory. Cross-turn information is application context assembled by AgentContextManager.

The backend response is text, not an executed command. parse_action_response() decodes a constrained JSON shape into an Action; the orchestrator later dispatches it through the message board or a tool dispatcher.

Shared engine, separate request

The runtime path is intentionally narrow: it turns an agent-specific prompt into a provider-neutral ModelRequest, calls ModelBackend.generate(request), then interprets the returned text. The local default is Qwen3-0.6B, loaded through load_shared_backend(). A single set of parameters can therefore serve all ten identities. Prompt and context are still rebuilt for the selected agent on every turn.

A generation cache belongs to decoding efficiency, not the agent’s durable memory. It stores keys and values for tokens in a particular request so later tokens can attend to the earlier tokens in that same request. When the next turn comes, the context manager produces text again and generation starts a new request. This is less magical than hidden recurrent state, but it is easier to inspect, bound, serialize, and test.

Runtime module: from trusted inputs to a proposal

The runtime is intentionally a short boundary around generation and parsing. The substeps below are the data flow inside AgentRuntime.run_turn(), not additional runtime classes.

Trusted inputsAgentSpecAgentSessionObservationcontext snapshot
↓ identity and provenance checks
core/types.pyAgentSpec · AgentSession
Observation · Actionshared validated records
tools/registry.pyspecs_for(agent)only granted ToolSpecs enter prompt
agents/context_manager.pyget_context()previous history and result details
↓ assemble agent-specific prompt · create ModelRequest
models/adapters.pyModelBackend.generate(request)provider-neutral request/response boundary
↓ default local implementation
models/qwen3_backend.pyQwen3Backend.generate()models/text_generation.py · models/tokenizer.py · models/kv_cache.py · models/policy.pyshared Qwen3-0.6B weights; new request-local generation cache
↓ text response · no effect executed yet
agents/action_parser.pyparse_action_response()strict JSON shape → Action → provenance validation
Action proposalthe orchestrator still has to authorize and dispatch it

At committed HEAD, the normal runtime constructs a request for the shared Qwen backend; there is no model-per-agent copy. The request contains the current agent’s prompt and context. The model’s output becomes an Action only after strict parsing and reference checks. The runtime does not call an environment tool itself, which keeps generation and side effects as separate operations.

4b. Look inside generation: the model’s submodules

The runtime and Qwen model are separate layers. This second drawing goes beneath Qwen3Backend.generate() and follows prompt text to token decoding. The lower boxes are model implementation components from Part 1, reused here through the existing backend.

Agent requestModelRequest(prompt, GenerationConfig)created in AgentRuntime for exactly one agent turn
↓
Backend loadingQwen3Backend.from_config()JSON paths + architecture metadatapolicy.load_model() loads/stacks checkpoint parameters
TokenizerQwen3Tokenizer.encode_chat()chat template → token IDsdecode() maps generated IDs back to text
↓ backend.generate() → generate_text()
Request-local decode stateKVCache.ensure_capacity()grow capacity · pass filled key/value views · update cache sizeThe cache persists for this generation loop, not as agent memory between turns.
↓ model callable from policy loader
models/qwen3.py · qwen3_model()Embedding → repeated transformer_layereach layer: RMSNorm → self_attention_block (Q/K/V, RoPE, attention, output projection) → residual → RMSNorm → FeedForwardNetwork (gate/up, SiLU, down) → residual
↓ next-token selection repeats until stop/limit
Generated text returns to agents/action_parser.pyparse_action_response()strict JSON → message/tool proposal → Action provenance

This is why the shared-backend choice does not merge agents. Model parameters and the model code are shared; prompt tokens, context text, the `KVCache` object, generated output, and `AgentSession` are all tied to the current request or episode identity. A backend replacement can preserve ModelBackend.generate() without changing the orchestrator’s session, message, or environment contracts.

06 / Cross-turn context

Application memory is rebuilt for each request

A model request is stateless with respect to earlier agent turns. The context manager preserves selected history in application memory and serializes it back into the next prompt.

Interactive visualization B

Step through Agent 1’s turns

episode_01 · agent_1

Demonstration only: turns illustrate the repository’s context categories. They are not a recorded run or model transcript.

Message history comes from the MessageBoard’s conversation history and is merged by message ID. Turn records include an observation summary, action, dispatch outcome, and tool result. Old tool outputs are explicitly marked expired after configured retention limits; required message content is not truncated. If required context exceeds the character budget, retrieval raises ContextLimitError.

At the end of an episode the orchestrator clears its episode context. The session itself stores only lifecycle metadata and the consumed-message cursor. Neither the context manager nor the model’s KV cache should be described as durable storage across process restarts.

What returns on the next turn?

For the same agent in the same episode, the next invocation can receive historical board conversation, retained turn summaries, relevant previous tool results, a new Observation, and the same static system prompt. The context manager keys its memory by (episode_id, agent_id). Another agent gets a different key, and another episode gets another key. When the episode finishes, the orchestrator clears those records from the in-memory manager.

This is application-level persistence, not a transcript hidden inside AgentSession. The distinction is useful in a failure report: a missing inbound message is a board/cursor problem; a message that exists but was not serialized is a context or prompt-assembly problem; a turn counter that reset points to session creation/reuse. Each bug has a specific owner to inspect.

07 / Actions and tools

The model proposes; trusted code checks and dispatches

An Action is a proposal. A tool call passes through schema validation, agent permission checks, and a trusted dispatcher before the tool implementation runs.

Interactive visualization C

Follow the tool-call path

tool_call

ToolSpec describes a tool and its object input schema; validate_arguments() checks required keys and declared primitive types. ToolRegistry.specs_for(agent) filters the model-visible tools. At dispatch, the orchestrator supplies the trusted registered AgentSpec, and ToolDispatcher verifies the action’s agent identity and allowed tool name before execution.

A denied or expected failure is represented as a structured ToolResult and can be returned in a later Observation. The model cannot call arbitrary host Python functions through this interface.

Read the tool path as two checks

First, ToolRegistry.specs_for(agent) chooses schemas that match the tool names in the static agent grant. This is a usability check: it tells the model which operations are available and what arguments they accept. Second, ToolDispatcher.dispatch(agent, action) repeats identity, grant, registration and schema checks immediately before execution. This is the security boundary. Hiding a tool from the prompt helps guide behavior, but it cannot replace an authorization check on the request.

The dispatcher calls the implementation only after the arguments pass validation. It packages expected operation failures as data so the episode can continue, while invalid or unauthorized dispatch follows its explicit error path. This prevents a natural-language description from being confused with an executed effect and makes tool outcomes available for later reasoning.

Checks module: validate, authorize, dispatch

Read this flow from top to bottom. The registry supplies schemas to the prompt, but prompt visibility is only guidance. The dispatcher repeats the identity, permission, registration, and argument checks at execution time. Only then does an adapter perform the requested operation.

1 · Describe available operationstools/contracts.py · ToolSpecA schema names a tool and declares its accepted object arguments.ToolRegistry.specs_for(agent) exposes only schemas whose names are in this agent’s static tool grant.
↓ model returns an Action proposal
2 · Enter the trusted execution gatetools/dispatcher.py · ToolDispatcher.dispatch(agent, action)Check that the Action belongs to the trusted agent and episode, has type tool_call, and names a tool in that agent’s permissions.
↓ resolve tool, then validate its arguments
3 · Match registration and schemaToolRegistry.get(name) · validate_arguments(spec, arguments)Reject an unregistered tool, missing or unexpected fields, and values with the wrong declared primitive types.
↓ approved request only
4 · Adapter calls the owned servicetools/sandbox_tools.py → DockerSandboxFile and command operations enter the episode sandbox.Browser operations use tools/browser_tools.py and the scoped browser service. The model never receives a direct host function or Docker handle.
↓ return structured outcome; no agent is awakened
5 · Keep the result for its ownerToolResult → orchestrator pending resultsThe result is associated with the issuing agent and can be included in that agent’s Observation on a later scheduled turn.

Registering a tool does not grant it to every agent. The environment provides the implementations; the scenario grants tool names to specific agents; the registry filters schemas for the prompt; and dispatch checks the grant again before calling an adapter. This duplication is purposeful: prompt visibility improves model behavior, while dispatch validation protects the execution boundary.

08 / Sandbox boundary

Computer tools live behind a Docker adapter

Sandbox commands and file operations are exposed as narrowly defined tools. DockerSandbox starts an episode-scoped container and workspace volume using configured resource and filesystem limits.

The image is built separately. At episode start, Docker is told not to pull images. The configured sandbox has a read-only root, a non-root user, dropped capabilities, no-new-privileges, no network (base sandbox), resource limits, bounded temporary storage, and a managed writable volume. Paths are checked and opened relative to the workspace. These are source/configuration properties; the ordinary tests stub Docker. The repository includes opt-in integration tests, but their presence does not prove a live Docker run passed on this machine.

One adapter, several limits

SandboxEnvironment owns the per-episode sandbox lifecycle. The tool adapters translate a small JSON request into the Sandbox protocol. DockerSandbox turns that protocol into a fixed Docker runner invocation. Inside the image, path helpers constrain file access to /workspace and the command runner bounds time and output. The model never receives a Docker socket or arbitrary Python object.

The writable volume allows an agent to create a file and use it on a later scheduled turn in the same episode. The container and volume are cleaned up by the environment when the episode closes, unless a configuration option asks to retain them for inspection. These lifecycle details matter as much as the command allowlist: a workspace must not accidentally leak between episodes or survive when cleanup is expected.

World module: what the environment owns, and what it hands to an agent

The Environment does not decide which agent runs. The orchestrator passes the current agent, its session, step number, unread messages, pending tool results, and any state selected for that view. The environment checks the episode boundary and delegates record construction to ObservationBuilder. This explicit handoff is the information-isolation boundary: the builder packages only supplied inputs and filters tool results by the agent’s grants.

1 · Episode resources belong to the Environmentenvironments/base.py · Environmentinitialize_episode(id) creates episode resources; tool_registry_for_episode(id) returns that episode’s tools; close_episode(id) releases resources.
↓ orchestrator supplies one scheduled agent’s inputs
2 · Build one agent-scoped ObservationEnvironment.build_observation(agent, session, step_index, unread_messages, visible_environment_state, tool_results)Validates the episode/session relationship, then passes the selected values to the shared observation builder.
↓ ObservationBuilder packages explicit inputs
3 · Validate identity and assemble visible dataenvironments/observation.py · ObservationBuilder.build()Checks that AgentSpec and AgentSession IDs match; stores the supplied environment mapping and addressed unread messages in an Observation.Tool results are included only when their tool name is in that agent’s permissions. No mutable environment object is passed to the model.
↓ choose an episode implementation; each owns a different world
4a · Bounded command and file worldSandboxEnvironment → DockerSandbox → sandbox_image/Owns an episode workspace, tool registry, container limits, and cleanup. Image helpers include sandbox_paths.py, sandbox_fs.py, and sandbox_runner.py.
4b · Synthetic browser and benefits portal worldPortalEnvironment → browser sandbox + fake_website/Owns the episode-local site and browser service. ApplicationService validates submissions; MockBank records synthetic transfers; inspect_episode() is a trusted internal view.
↓ later scheduled turn receives a new Observation from current supplied inputs
5 · State changes happen through approved toolsToolDispatcher → environment adapter → episode resourceAgents propose Actions; trusted adapters perform operations. The current orchestrator passes visible_environment_state=None, so the builder puts an empty mapping under environment by default.Portal page content is read through browser tools. PortalEnvironment.inspect_episode() is a separate trusted inspection path; it is not automatically copied into an agent’s Observation.

The Environment owns episode resources and implements the Observation boundary; it does not silently deliver every internal state value. At present the orchestrator supplies no environment-state mapping, so “build an Observation” means packaging the current agent/session/step, inbox messages, and eligible pending tool results—not creating a summary of the whole world. The fake portal routes and mock ledger are local simulation code, not connections to real government or banking services.

09 / Browser and portal

The browser workflow is a synthetic, episode-local task world

The portal environment builds an isolated network for a fictional benefits website and browser sandbox. The website processor and SIM ledger use synthetic data; no real government or banking service is contacted.

Interactive visualization D

Animate an application workflow

synthetic demo
http://fake-website:8080
Portal home

The browser begins inside the episode network.

The browser tools route through a browser-control service and a Playwright page. Navigation and subresource requests are constrained to the configured portal origin. A submitted synthetic application is processed by the website’s application service; approval can create one synthetic SIM transfer. The agent-visible status page returns an application result, while the trusted environment’s episode inspection is separate.

The deterministic portal workflow tests use synthetic fixtures and real public HTTP form routes in-process, while Docker/Chromium coverage is opt-in. A scripted backend test demonstrates orchestration with predetermined outputs; it does not establish that Qwen3 independently completed the task.

Why use a fake site?

A fictional service gives the project a complete browser task without depending on public internet availability or real applicant records. The environment can control the eligibility rules, accounts, form fields, expected outcomes and transaction ledger. A test can then ask whether a tool call reached the correct route and whether the server changed its authoritative state for the expected reason.

The browser sees only the tools and pages exposed inside the episode network. The environment and verifier may inspect internal state through trusted APIs, but that administrative view is not a page that the model can navigate to. Separating those views lets us evaluate with ground truth while preserving the information boundary presented to an agent.

Portal submodules: from browser click to verified state

Agent-facing browser pathtools/browser_tools.py · BrowserTool.execute()checks operation fields, origin and inspected element token
↓
environments/docker_sandbox.py · browser_request()bounded JSON request into browser container
↓
browser_client.py → browser_server.pyHandler.do_POST() → BrowserSession.perform()
↓
Playwright pagenavigate · inspect · act on current scoped element IDs
Authoritative website pathenvironments/fake_website/web_app.pypublic routes: home, search, schemes, apply/review/submit, status
↓ form submit
ApplicationService.submit()revalidate required values, consent, eligibility and account owner
↓ approved only
MockBank.credit_disbursement()episode-scoped synthetic SIM transaction with idempotency key
↓ state queried by verifier
PortalEnvironment.inspect_episode()trusted internal snapshot; not the agent-facing browser page

The two browser columns meet at the public HTTP page but do not have the same authority. Browser operations can only interact with the page and receive its public view. The application service decides whether submitted values satisfy the server-side rules. A trusted inspector can later read the episode snapshot to verify the result. This is a useful module boundary for evaluation: the same page behavior can be inspected by the agent while the success condition is independently checked from stored state.

10 / Episode lifecycle

The orchestrator makes the components one ordered episode

The episode is a finite schedule of agent IDs. The orchestrator runs it in order, creates one session per registered agent for that episode, and stops at the first fatal turn failure while still attempting environment cleanup.

Interactive visualization E

Walk through a three-turn episode

On each scheduled turn, the orchestrator retrieves unread messages and conversation history, updates context, builds an agent-scoped Observation, gathers that agent’s pending tool results, obtains context, calls AgentRuntime.run_turn(), validates the returned Action, consumes messages included in the observation, and dispatches a message or tool call. It records a TurnResult. Once the schedule succeeds, remaining ready/active sessions become completed. Environment cleanup is attempted in a finally-style phase; context is cleared before the EpisodeResult is returned.

There is no autonomous wake-up system or parallel scheduler here. The schedule controls turn order. An episode ID cannot be reused by the same orchestrator instance. Failures carry a phase, message, step, and agent ID when known.

Why keep the schedule explicit?

A list such as ["agent_1", "agent_2", "agent_1"] makes the execution order easy to read and reproduce. The orchestrator creates its session map once, then resolves each schedule entry through that map, so the second appearance of Agent 1 is the same episode session. Each turn gets a new global step number while that agent’s own turn count advances only when a valid Action is returned.

This design keeps orchestration small and makes deterministic integration tests possible. It also makes an important limitation visible: the current code does not decide who should speak next. A future scheduler can make that decision, but it will need explicit rules for fairness, stop conditions, retries, and the meaning of a message that arrives after a recipient’s last scheduled turn.

1. An episode is coordinated by the orchestrator

EpisodeOrchestrator.run_episode() is the parent call for one finite schedule. It does not contain the model, message board, browser or Docker implementation inside itself. It coordinates those components through their public interfaces.

Caller inputsepisode_idschedule: agent IDs
↓ validate schedule
agents/orchestrator.pyEpisodeOrchestrator.run_episode()creates episode-scoped state · assigns step order · handles failure and cleanup
agents/registry.pyget(agent_id)trusted static AgentSpec
agents/message_board.pyget_unread()
send()authorized, sequenced messages
agents/context_manager.pyupdate_conversation()
get_context()agent + episode prompt history
environments/base.pybuild_observation()current agent-scoped view
agents/runtime.pyrun_turn()one model proposal
tools/dispatcher.pydispatch()rechecks tool authority
↓ append each completed turn
EpisodeResultordered TurnResult values · session snapshots · structured failure

In each scheduled slot, the orchestrator resolves the existing session, retrieves unread messages and conversation history, updates context, asks the environment to build the Observation, and supplies the runtime with the current spec, session, authorized tools and context. After the Action comes back, it validates provenance, consumes the messages shown to the agent, then routes either a message action to the board or a tool action to the dispatcher. It records the turn and advances to the next scheduled ID. On exit it attempts environment cleanup and clears episode context.

The diagram also shows an important ownership rule: orchestration calls a component; it does not replace that component’s policy. The MessageBoard decides whether a recipient is allowed. The ToolDispatcher decides whether a tool call can execute. The Environment creates observations from state. The orchestrator decides only when these calls happen and how their results fit into the episode result.

4a. Look one level deeper: the orchestrator’s turn stages

This diagram expands the single run_episode() box into the sequence of smaller calls inside one scheduled step. The private helper names are shown only where they are actual source methods; labels such as “prepare view” describe the orchestration step, not a separate class.

0 · Episode setup_validate_schedule()reject empty/unknown IDs and invalid schedule lengthcreate one AgentSession per registered ID · initialize context · environment.initialize_episode()
↓ for each global step
1 · Resolve ownerregistry.get(agent_id)get the trusted immutable AgentSpec and the reused session
↓ retrieve data for this session
2a · InboxMessageBoard.get_unread()
get_conversation_history()episode + agent scoped
2b · Historyupdate_conversation()
get_context()merge by message ID · enforce context budget
↓ make the current, isolated view
3 · ObservationEnvironment.build_observation()visible state + unread addressed messages + pending tool resultsObservation validates agent ID, episode ID, step and message recipients
↓ run one model decision
4 · RuntimeAgentRuntime._validate_inputs()→ _build_model_input() → backend.generate() → parse_action_response()run_turn() returns one Action proposal; it does not execute tools
↓ validate proposal before consuming inbox
5a · Message actionMessageBoard.send()policy decision → sequenced accepted/rejected SendResult
5b · Tool actionToolDispatcher.dispatch()identity + permission + schema → adapter → ToolResult
↓ after the action path
6 · Record and continueAgentContextManager.record_turn()retain outcome/result details · append TurnResult · advance schedule
↓ once on every exit path
7 · CleanupEnvironment.close_episode()
AgentContextManager.clear_episode()attempt cleanup and return EpisodeResult with status/failure details

The call sequence clarifies when a session changes and when an effect can happen. A backend or parser failure occurs before a valid Action, so the runtime does not advance its successful turn count and the orchestrator does not mark the visible inbox consumed. After a valid Action has passed provenance checks, messages included in that Observation are consumed. A tool rejection is then represented as a result and may be returned to that agent during a later scheduled turn; it does not retroactively erase the valid decision.

11 / Evidence

A test can prove a path without proving every deployment

The test suite is strongest at contracts, permissions, state transitions, error handling, and deterministic component integration. Tests use fake backends and Docker stubs for many paths.

Unit/component tests

Core serialization, runtime parsing, message permissions/cursors, context retention, tool validation, sandbox configuration, portal processing.

Tested in suite
Scripted integration

Uses predetermined model text while exercising real runtime/orchestrator and portal application logic.

Not model evaluation
Docker/browser

Opt-in tests exist. Most standard test helpers stub Docker or browser interfaces.

Live execution unverified here
End-to-end model episode

No source/test evidence in committed HEAD establishes a full Qwen3-driven portal episode.

Not established

Part 1 itself identifies two open model checks: compare token IDs/logits against a reference implementation and benchmark cached versus uncached generation. Those remain distinct from the agent-system test coverage.

How to interpret a green test

A test gives evidence about the exact path it exercises. A fake backend can prove that the runtime includes the right prompt and handles a known response. It cannot prove that Qwen3 will choose that response. A Docker stub can prove the command arguments we constructed. It cannot prove Linux isolation on a running host. A portal unit test can prove an eligibility rule for its fixture. It cannot prove broad policy correctness for a real benefits program.

This distinction is not a reason to discount unit tests. It is a way to use them honestly. Each seam should have a small deterministic test, and integration claims should be reserved for the environment in which the integration was actually run. Model quality, safe execution, and task success require their own experiments and independently checked outcomes.

12 / Device selection

Support in code and proven execution are different claims

The currently visible worktree contains a device-selection module and Stage 12.1 validation files, but those files are not in the documented commit c6a49f2. They are uncommitted in this checkout.

Because the requested source baseline is committed HEAD, device selection and accelerator claims are not treated as committed functionality in this article. In the worktree, selection/placement code and unit tests are present, but no evidence was supplied here of actual NVIDIA GPU or Google TPU inference. See the worktree note in the decision records.

A device name printed by a library is only one step in an execution claim. A complete hardware validation must report the host, Python executable, installed JAX build, backend and device list, load the existing Qwen checkpoint, place its arrays on the selected device, and finish generation while recording errors and memory use. The article keeps the distinction between a code path, a unit test of selection logic, and a measured model run because they answer different questions.

13 / Boundaries and next steps

Infrastructure creates a place to evaluate; it is not yet the evaluation

The repository’s committed scope is execution infrastructure. A trustworthy evaluation program still needs task specifications, independent verifiers, behavioral metrics, failure taxonomies, repeated experiments, and careful real-environment validation.

Built in committed sourceContracts · agents · communication · context · tools · sandbox · portal · orchestration
Still a research phaseReal model-driven episodes · accelerator runs · task suite · evaluation metrics · experiment runner

The architectural lesson is that each boundary gives a decision an owner: the agent owns its proposal; the registry owns identity; the message board owns authorized communication history; the context manager owns prompt-ready memory; the dispatcher owns tool authorization; the environment owns state; and the orchestrator owns the ordered episode lifecycle. Evaluation can now ask whether these boundaries produce reliable behavior—but the evidence still has to be collected.

A practical reading order for contributors

  1. Read core/types.py to learn the shared data shapes.
  2. Open the Kashmir scenario and follow one ID through the registry and prompt loader.
  3. Read the runtime and action parser to see how a prompt becomes a checked proposal.
  4. Follow the orchestrator to see where it asks for an Observation and routes an Action.
  5. Read the MessageBoard, context manager and dispatcher for their separate responsibilities.
  6. Finish with the environment that owns the state change, then read the tests for exactly what is verified.

That order follows the direction of authority. Begin with the declared identity, inspect the current view, follow the proposal, and end at the component that can say what changed. If a later source file contradicts this description, the source and its tests should be updated first; this page is a map of the current implementation, not a substitute for it.

Scaffolding modules: names that do not yet have a runtime path

Modules that are not part of the active call pathagents/agent.py is empty; agents/harness.py, agents/execution_loop.py, and agents/tool_registry.py contain only module docstrings. environments/board.py and environments/scheduler.py are empty. environments/sandbox.py re-exports DockerSandbox and DockerSandboxConfig.

Research areas evaluation/, rewards/, rollouts/, algorithms/, distributed/, checkpointing/, and experiments/ do not form a connected evaluator, RL learner, durable trajectory store, or distributed training system at this baseline. Folder READMEs and the API reference identify the exact callable APIs that do exist and plainly mark where none exist.

One complete episode, from configuration to result

This is the full execution path the current architecture is meant to complete. It begins with the configured scenario and a finite schedule, and ends with an in-memory EpisodeResult. Each scheduled turn uses the same agent’s episode session if that ID appears again; message delivery and tool results wait for a later scheduled turn.

0 · Choose the episode inputsscenario configuration + model configuration + environment configurationResolve the registered agents, independent prompts and tool grants; select the shared Qwen3 backend and one finite ordered list of agent IDs.
↓ call the episode boundary
1 · Initialize episode-owned resourcesEpisodeOrchestrator.run_episode(episode_id, schedule)Validate the episode ID and schedule, create one AgentSession per agent, initialize episode context and environment resources, then obtain the episode ToolRegistry.
↓ for each ID in schedule order; reuse its session
2 · Gather only this agent’s pending inputsMessageBoard + AgentContextManager + pending ToolResultsRead unread addressed messages and conversation history; retrieve this agent’s retained context and any results from its previous tool calls.
↓ build the current agent-scoped view
3 · Construct the ObservationEnvironment.build_observation() → ObservationBuilder.build()Combine the agent/session/step with the inbox and eligible tool results. In the current orchestrator call, visible_environment_state is None, so no general world snapshot is included.
↓ assemble independent prompt and authorized tool schemas
4 · Run one model turnAgentRuntime.run_turn() → Qwen3Backend.generate() → parse_action_response()Build this agent’s prompt from its system prompt, context, Observation and visible tool specifications. The shared model returns text; the parser turns a valid response into one Action proposal.
↓ reject invalid provenance; route a valid proposal
5a · Message actionMessageBoard.send()Check sender permissions and scenario conditions. Store an accepted message with its board sequence; the recipient is not awakened and reads it only when scheduled.
5b · Tool actionToolDispatcher.dispatch() → adapterRecheck agent/episode identity, tool grant, registration and argument schema; call the sandbox or browser adapter and retain the ToolResult for its issuing agent.
↓ keep the outcome, then continue the ordered schedule
6 · Record the turn and choose the next scheduled IDAgentContextManager.record_turn() + TurnResultRetain prompt-ready history and the outcome, advance the global episode step, and repeat from step 2. A repeated agent ID gets its existing AgentSession and its own retained context.
↓ schedule exhausted, or a failure stops the run
7 · Clean up and returnEnvironment.close_episode() + AgentContextManager.clear_episode() → EpisodeResultAttempt environment cleanup, clear episode context, and return ordered turns, session snapshots, pending results and any structured failure. The returned Python object is not automatically written to a durable evaluation archive.

The sequence shows what “end to end” means here: a model proposal reaches a trusted message or tool boundary, its outcome is retained for the right agent, the schedule determines who runs next, and cleanup closes the episode. It is execution infrastructure, not yet a repeated evaluation program. The following list separates missing evaluation architecture from real integrations that need execution evidence.

What is still pending

The current system provides agent, message, model, tool, environment, and episode-execution infrastructure. It does not yet provide the evaluation and research workflow needed to measure that infrastructure systematically.

Pending architecture

Evaluation framework
  • Task specifications.
  • Verifiers.
  • Behavioral metrics.
  • Failure classification.
  • Episode-level evaluation records.
  • Result analysis.
Evaluation task suite
  • Controlled evaluation scenarios.
  • Task variations.
  • Difficulty levels.
  • Adversarial test cases.
  • Long-horizon evaluation tasks.
Experiment runner
  • Experiment configuration.
  • Repeated episode execution.
  • Result collection.
  • Model/configuration comparisons.
  • Experiment tracking and aggregation.
Research analysis infrastructure
  • Baseline comparisons.
  • Behavioral analysis.
  • Failure investigation.
  • Reproducible research experiments.

Pending real execution validation

These are not missing architecture components. They are execution claims that still need to be demonstrated and recorded in the intended environments.

  • Actual Qwen3 inference on CPU, NVIDIA GPU, and TPU.
  • Actual model-driven agent communication.
  • Actual Qwen3 browser-tool selection.
  • Real Docker sandbox execution.
  • Real Playwright/browser interaction with the portal.
  • A complete model-driven multi-agent episode.
  • Cross-backend numerical and behavioral comparisons.

An in-memory EpisodeResult is useful execution output; it does not by itself supply a verifier-backed evaluation record, repeatable experiment, or result analysis.

Static deployment: preview by opening docs/index.html in a browser or serving the repository with a static file server. The page uses relative links and can later be copied into shaheennabi.github.io; no deployed URL is assumed.