Unifying Execution and Business States
Introduction: The Problem with Scattered State
In the previous two lessons, you built a stateless reducer agent that externalizes prompts and serializes context. Up to now, the agent has reported its results through the RunResult interface you defined back in Unit 1 — a small object bundling context, status, and finalAnswer. That worked, but it only captured part of the picture.
Consider everything the agent actually needs to track as it runs: the current context array, the processing status, any error messages, the tool calls waiting to be executed, and the final_answer. With only RunResult, several of these live as loose local variables inside run() — scattered state that makes the system harder to maintain, more difficult to debug, and fragile to pause and resume, because no single object captures everything about the agent's situation.
The solution is to evolve RunResult into a richer, unified State interface that implements Factor 5 of the 12-Factor Agents methodology: unify execution state and business state. By introducing this interface, the agent's run() method gains a clean async run(inputState: State): Promise<State> signature — a reducer-like state transition interface that takes one version of the world and returns another. The agent is stateless from the caller's perspective, but it is not side-effect-free: it still calls the LLM and executes tools while producing the next state.
Distinguishing Execution State from Business State
Before evolving our types into the unified State interface, it helps to clarify what execution state and business state mean and why they both belong in the same object.
- Execution state refers to the metadata about where the agent is in its processing lifecycle, including how many
stepshave been taken, what the currentstatusis, what work is pending, and whether any fatal errors have occurred. - Business state refers to the domain-specific information the agent is working with, including the conversation
context, thefinal_answeronce the agent completes its work, and any domain-specific data structures you might add later.
Notice that RunResult already mixed a little of both: status is execution state, while context and finalAnswer are business state. The next step is to make that union complete and explicit. By merging execution state and business state into a single State object, you create a unified representation that is easier to reason about, persist, and pass between systems — enabling capabilities such as pausing an agent mid-execution and resuming it later.
Adding the PendingToolCall Type
The home for our state types already exists. Back in Unit 1 we created src/core/models/state.ts to hold AgentStatus, ContextItem, and RunResult, and Unit 2 left it untouched. In this lesson we stay in that same file — no new directories, no new modules — keeping state.ts as a pure data container while the Agent class handles processing logic. We keep AgentStatus and ContextItem exactly as they are, retire RunResult, and add two new types in their place. The first is PendingToolCall, a new interface for tool calls the model has requested but the agent has not yet executed:
Unlike the serialized form stored in ContextItem (where arguments is a JSON string), the arguments here are a parsed Record<string, unknown>, making them easy to pass directly to tool functions. This gives queued work a first-class home in the state instead of leaving it as a transient local variable.
Adding the Unified State Type
The second new type is State, the unified container that replaces RunResult. Where RunResult held only context, status, and finalAnswer, State captures the mutable execution and business data used by this example in seven fields. Resuming on another agent instance also requires compatible external configuration: the model, reasoning setting, prompt and tool schemas must match the original run:
id— A unique identifier for this state instance, enabling tracking across systems and persistence layers.steps— Counts how many processing cycles the agent has completed, used for debugging and enforcing maximum step limits.status— Tracks the agent's lifecycle stage using the existingAgentStatusunion.context— Holds the complete conversation history as aContextItem[]array (the same role it played inRunResult).pending_tool_calls— Stores tool calls requested by theLLMbut not yet executed, representing queued work.error— Astring | nullthat captures any fatal exception message (populated whenstatus === "failed").final_answer— Astring | nullthat stores the agent's final response once processing completes successfully (the role previously played byRunResult.finalAnswer, now snake-cased to match the rest of theStatefields).
Using string | null instead of optional properties (?) makes it explicit that these fields always exist on the object — they simply start as null and are populated during execution. With these types defined, you can refactor the agent to use State everywhere RunResult previously appeared, starting with the nextStep method where most state mutations happen.
Incrementing Steps and Processing Pending Tool Calls
The nextStep method is where most state mutations happen, so this is the most significant part of the implementation. The method receives a State object, mutates it in place, and returns the same object — implementing the reducer pattern at the state level. It begins by incrementing the steps counter directly on the state object, then iterates through pending_tool_calls and persists each tool call into the unified context history, using JSON.stringify to serialize the arguments back into the string format that ContextItem expects:
The spread [...state.pending_tool_calls] creates a snapshot of the array before the loop begins, so mutations to pending_tool_calls during the loop — like removing processed calls — do not affect the iteration. This makes it clear how execution progresses step by step, with all mutations flowing through the same State object. Now you need to handle the actual tool execution and update the state accordingly.
Executing Tools and Updating State
After appending the function call to context, a switch block handles tool execution. The final_answer case is handled separately with an if check before the switch — when it fires, the method clears pending_tool_calls, sets status to "complete", assigns state.final_answer using a typeof guard to ensure only string values are stored, and returns immediately. For math tools, the method executes the function inside a try/catch block using the numberArg helper to extract validated numeric arguments, formats the result as JSON, removes the processed call from pending_tool_calls using .filter(), and appends the output to context:
By flowing all results back into the State object, you maintain an application-visible execution trace that can be inspected or persisted. Reproducing a model decision also requires the recorded response. The two helpers used here — numberArg and compactToolError — keep this logic clean, and we look at each next.
Validating Numeric Arguments
numberArg validates and extracts a numeric argument from the parsed arguments object, throwing a descriptive error if the value is missing or non-finite. This is what lets the switch cases call tool functions confidently, knowing the values they receive are real, finite numbers:
When this function throws, the surrounding try/catch in the switch catches it and routes the message through compactToolError.
Normalizing Tool Errors
compactToolError normalizes any caught exception into a JSON string that the model can read and recover from, safely handling both Error instances and any other thrown value — important because anything can be thrown in JavaScript, not just Error objects:
After processing all pending tool calls and appending their outputs to context, you need to call the LLM to get the next set of actions.
Calling the LLM for the Next Step
With every pending tool call executed, the method calls this.client.responses.create(...) with the serialized context. The serializeContextToText utility from the previous lesson converts the ContextItem[] array into a formatted string accepted by the input field. The tool_choice: "required" parameter forces the model to always respond with a tool call, and the optional reasoning field is passed only when using gpt-5:
With a response in hand, the method's final job is to translate the model's output into queued work on the State object.
Queueing New Tool Calls into State
Once the model responds, the method appends any function calls it requested to pending_tool_calls and returns the updated state. This explicit queueing makes the agent's control flow transparent and debuggable — the work that used to live in a transient loop variable now has a durable home in the state:
Two helpers drive that one line: isFunctionCall filters the raw output down to function calls, and toPendingToolCall converts each one into the shape the state expects. We look at each next.
Narrowing Output with isFunctionCall
The isFunctionCall type guard — the same one used in earlier units — narrows each item in response.output to the specific shape that carries a function_call, so TypeScript knows exactly what properties are available when toPendingToolCall receives it:
Once an item is narrowed to this shape, it is safe to hand off for conversion.
Converting Output with toPendingToolCall
toPendingToolCall is new in this lesson. It converts the raw API output item into a PendingToolCall, parsing the JSON argument string back into a typed Record<string, unknown> so downstream tool functions can access arguments directly by name:
Now you need to update the run() method to orchestrate these steps using the unified State and handle unexpected crashes.
Updating the Run Method to Work with State
The run() method changes shape with unified state: instead of juggling separate local variables for step, status, and finalAnswer and bundling them into a RunResult at the end, it now tracks a single State object. The method is async and returns a Promise<State>, reflecting that LLM calls are asynchronous. To adhere to the stateless principle, it creates a deep copy of the incoming inputState using the built-in structuredClone — a standard runtime function that performs a full structural copy of any serializable object without requiring a third-party library. We also wrap the execution loop in a try/catch: if a fatal error occurs (such as an API outage), we catch it, set state.status to "failed", and record the message using error instanceof Error ? error.message : String(error) — an idiomatic pattern for handling unknown thrown values safely:
This control flow returns an existing terminal state unchanged and clears an old answer before resuming an incomplete one. Success, timeout, and failure are captured within the returned State object. Because every outcome travels through the same structure — rather than the slimmer RunResult plus the occasional thrown exception — the caller never needs to handle multiple return types or wrap calls in their own try/catch.
Running the Agent with the New State-Based API
The main.ts script demonstrates how to use the agent with the unified state pattern. Where earlier lessons started from a bare ContextItem[], you now construct a plain State object literal — no class instantiation required — with a unique id generated by Node's built-in randomUUID() from the node:crypto module. All fields must be provided explicitly because the State interface has no defaults; the caller is responsible for supplying valid initial values. You then await agent.run(state) and read results directly from the returned State object, which prints Status: complete and the solved equation when the run succeeds:
Running this script produces the following output, showing that the agent successfully solved the quadratic equation:
The unified state pattern makes the API cleaner than the old RunResult plus loose variables, and all execution information is now available in one object. With this structure, the caller never needs to handle multiple return types.
Summary and What's Next
You have implemented Factor 5 by evolving the RunResult you defined in Unit 1 into a single source of truth — one State object that captures its mutable execution and business data. Compatible agent configuration remains an external requirement for resumption. By using structuredClone(inputState) at the start of run(), you have ensured that your agent keeps a state-in/state-out interface — taking one version and returning another without mutating the input object.
TypeScript's type system reinforces this design: the carried-over AgentStatus union still makes every lifecycle transition explicit and compiler-checked, the ContextItem discriminated union still lets you safely narrow context entries by their type or role property, and the new string | null fields make the presence or absence of an error or answer unmistakably clear.
This design not only simplifies the code but also enables powerful capabilities you will explore in future lessons: serializing state to JSON for persistence, inspecting saved executions for debugging, and scaling horizontally by having different processes resume work from a serialized state. In the upcoming practice exercises, you will extend the State interface to handle more complex scenarios and explore how unified state simplifies error handling and recovery.
