% ============================================================================ \section{Execution Substrate, Document Generation, and an Illustrative Walk-Through} \label{sec:capabilities} % ============================================================================ Having described how the agent is orchestrated, we now detail the two subsystems that turn its plans into artifacts---the sandboxed Python substrate that executes model-authored code and the pipeline that renders the resulting report into several document formats---and then walk through one request end to end. The walk-through is a \emph{demonstration} in the design-science sense \citep{peffers2007design}: it shows that the mechanisms compose, and it reports no measurements. \subsection{The Python execution sandbox} \label{subsec:sandbox} When the model invokes the custom-analysis tool, the server does not evaluate the code in process. It spawns a separate Python interpreter---the project's virtual environment if present, otherwise the system interpreter---as a child process and communicates with it over standard streams. The process boundary protects the server from faults in the executed code and bounds their effect (Figure~\ref{fig:sandbox}); it is isolation by process, not by container, and Section~\ref{subsec:threats} returns to what that does and does not guarantee. \input{figures/sandbox} \paragraph{Inter-process protocol.} The server serialises a single JSON object---the model-authored code, an optional context dictionary, and the market-data credential---and writes it to the child's standard input, then closes the stream. The child reads the entire input, executes, and writes exactly one JSON object to standard output: a success flag, captured textual output, a list of base64-encoded figures, a list of generated files, and any error. The child is launched with output buffering disabled and a hard 90-second wall-clock timeout. The parent collects standard output and standard error separately; a non-zero exit code, or error output with no standard output, is treated as failure, and the error text is returned to the model as the tool result so that it can revise its code on the next turn. This single-request, single-response discipline keeps the boundary simple and makes failures explicit. \paragraph{Namespace construction.} Inside the child, execution is performed by building an execution namespace---a dictionary---and calling the interpreter's \texttt{exec} against it. The runtime attempts to import, and injects when available, 29 packages: the core scientific stack (NumPy, pandas, SciPy, Matplotlib, seaborn, Plotly), statistics and econometrics (statsmodels, \texttt{arch}, pmdarima, Prophet, hmmlearn), machine learning (scikit-learn, XGBoost, LightGBM), optimisation and portfolio construction (CVXPY, PyPortfolioOpt, Riskfolio-Lib), market and technical-analysis utilities (yfinance, \texttt{ta}, mplfinance, vectorbt), data engines (DuckDB, Polars), and symbolic and graph libraries (SymPy, NetworkX, Numba), together with the spreadsheet and word-processing writers. Each import is wrapped so that a missing package degrades to an absent name rather than a failed execution; the platform's own documentation advertises ``17 libraries'', which undercounts what the executor attempts to load. The runtime also injects two artifact helpers (\texttt{save\_excel}, \texttt{save\_word}) and a market-data client constructed from the supplied credential; any context variables passed by the model are merged in last, so that the model can parameterise a reusable script without string interpolation. Matplotlib is configured for a non-interactive backend before any plotting occurs. If the executed code defines a callable named \texttt{main}, the runtime invokes it after execution and captures its return value. \paragraph{Output and figure capture.} Standard output and standard error produced by the code are redirected into in-memory buffers for the duration of execution, so that \texttt{print} statements become the textual result rather than corrupting the JSON protocol. Figures are captured after execution by a deterministic sweep: the runtime enumerates all live Matplotlib figure numbers and, for each, renders the figure to an in-memory PNG at 150 dots per inch with a tight bounding box and base64-encodes the bytes. This is why the single-call convention asks the model to emit each chart as a separate figure: the sweep turns each one into an individually addressable image. The encoded figures travel back through the JSON response, are written to a served directory, and are streamed to the client as figure events. Files written by the artifact helpers are returned as download links in the same way. \subsection{Pre-built numerical routines} \label{subsec:numerical} Alongside the open-ended sandbox, the server contains Python implementations of several routine computations---a Monte Carlo path simulator under geometric Brownian motion, a Black--Scholes pricer returning prices and Greeks, a GARCH(1,1) estimator, historical, parametric, and simulated Value-at-Risk with expected shortfall and companion ratios, a mean--variance portfolio optimiser, a risk-metrics module, a plotting module, and a volatility-surface renderer---each exposed through the same child-process contract as the sandbox. Their closed forms are recorded in Appendix~\ref{app:numerical}. At the audited commit, however, only the option pricer is declared in the tool catalogue; the handlers for the Monte Carlo, GARCH, VaR, portfolio-optimisation, risk-metrics, and plotting routines exist in the route module but have no corresponding tool definition, so the model cannot invoke them, even though the system prompt still describes the Monte Carlo and volatility-surface tools. The practical consequence is that, at this commit, such analyses are performed through the custom-Python path of Listing~\ref{lst:onecall}, with the model writing the code, rather than through a fixed implementation. The first version of this paper presented the four routines as model-callable tools; we correct that here and note that restoring the definitions is a small change. \subsection{The document-generation pipeline} \label{subsec:docs} VQuant treats the deliverable as a first-class artifact. From a single Markdown report---the text the agent streams to the user, with embedded figure references---the platform produces several output formats, each through a distinct mechanism (Figure~\ref{fig:docpipeline}). \input{figures/docpipeline} \paragraph{PDF via headless rendering.} Rendering Markdown that contains mathematics is delicate because a Markdown parser will mangle mathematical syntax. The pipeline solves this with a protect--parse--restore step: before parsing, every display and inline mathematics span is extracted and replaced by a unique placeholder; the now mathematics-free Markdown is parsed to HTML (with \texttt{marked}); the placeholders are then restored as spans destined for a client-side renderer (KaTeX). The assembled HTML is loaded into a headless Chromium instance (Puppeteer), which executes the renderer; the server waits until rendered output appears in the document before printing the page to PDF with headers, footers, and pagination. Rendering in a real browser engine is what lets complex notation and styled tables reproduce faithfully; it also makes PDF generation depend on a content-delivery network for the renderer's assets, a deployment constraint noted in Section~\ref{subsec:threats}. \paragraph{Slides via model restructuring and two-pass \LaTeX.} Presentation output is a two-phase mechanism. First, the platform issues a second model call---pinned to \texttt{claude-opus-4-8} irrespective of the model that produced the report---whose sole task is to restructure the report into slide content, one idea per slide, with special characters escaped and key quantities emphasised, returning only body \LaTeX. The server wraps that body in a fixed Beamer preamble and compiles it with two sequential passes of \texttt{pdflatex}, the second being required for cross-references and the table of contents to resolve; a non-zero exit code is tolerated when a PDF was nonetheless produced, since \LaTeX{} returns one on warnings. When the analysis produced figures, the server synthesises one slide per figure without further model involvement. \paragraph{Word via document conversion.} For an editable office format, the same Markdown is written to a temporary file and converted with Pandoc, which preserves tables, lists, and heading structure. \paragraph{Spreadsheets with live formulas.} Within the sandbox, the spreadsheet helper writes multi-sheet workbooks that contain live formulas---column sums, averages, extrema, and counts, together with optional per-column formulas supplied by the model---and conditional formats, rather than pre-computed constants, so that the recipient can audit and modify the calculations. This mirrors, at the spreadsheet level, the platform's commitment to auditable output: the deliverable carries its own derivation. \paragraph{Sharing and persistence.} Any report can be published to a stable URL under an eight-character identifier; the server stores the report content and its figure references and serves them through a public viewer, so an analysis can be revisited or cited without re-running the computation. Figure files themselves live on the server's disk and are lost on redeployment, a limitation the code acknowledges. Sessions, token ledgers, and cost estimates are persisted per user. \subsection{An illustrative walk-through} \label{subsec:walkthrough} To show how the mechanisms compose, we trace the request ``analyse NVDA's fundamentals, technicals, and run a Monte Carlo simulation'' through the system as implemented. No numbers are reported, because none were measured; the trace describes control flow. The route handler appends the query to an empty message list and calls \textsc{ProcessResponse}. \textsc{PrepareContext} finds nothing to truncate or summarise. The streaming call opens with the date-stamped system prompt, the 245 tool schemas, and the single user message; the model's reasoning summary begins to arrive on the thinking channel and is rendered in the collapsible panel. Under the routing policy the request is ``comprehensive'', so the model requests on the order of ten tools in one turn---profile, income statement, balance sheet, cash flow, key metrics, quote, historical prices, RSI, MACD, peers, news---plus one call to the custom-Python tool whose code fetches the price history inside the sandbox, simulates geometric-Brownian paths, and emits a fan chart and a terminal-value histogram as separate figures. The server emits a \texttt{tools} event listing the requests, then executes them in three batches of at most five with 500-millisecond pauses, emitting \texttt{tool\_start}, \texttt{tool\_complete}, and per-batch \texttt{status} events. The Python call spawns the child process, which returns captured output and two base64 figures; the server writes the images to the served directory, emits \texttt{python\_code} and \texttt{custom\_python\_figures} events, and returns the textual output---capped at 15{,}000 characters---as the tool result. All other results are capped at 3{,}000 characters. The assistant message with the tool-use blocks and the user message with the tool-result blocks are appended, and the routine recurses. On the second call the model has every result in context and, in the typical case, requests no further tools: it streams the report section by section, following the template in Appendix~\ref{app:prompt}, with Markdown tables for the financial statements and image references for the two figures. The accumulated text, figures, token totals, and cost are persisted with the session and a \texttt{done} event closes the stream. From the rendered report the user may request a PDF (headless rendering), a DOCX (Pandoc), a Beamer deck (a second model call, pinned to Opus 4.8, then two \texttt{pdflatex} passes, with one synthesised slide per figure), or a share link. Had the model instead decomposed the analysis---fetching prices in one turn and simulating in another---the trace would contain one additional recursion, which is the round trip the single-call convention is designed to remove.