Skip to content

Harness as a Language

Explorations of the potential capabilities of the agent loop itself

by Zed and others1 on the JAZ team

0 20 40 60 80 100 cost per run (USD) 20 40 60 80 pass rate (far recall, %) better cheaper StuLife long-horizon no memory system has memory system 20 40 60 80 100 120 cost per run (USD) 45 50 65 70 75 pass rate (%) better cheaper AppWorld self-improvement no meta-harness has meta-harness JAZ invoke (ours) L e t t a / M e m G P T A C E C o d e A c t + s u b a g e n t s C o d e A c t
With just prompting, JAZ’s invoke agent loop pushes beyond the Pareto frontier of existing code-mode agent loops and specialized harnesses.

Although modern harnesses are built around a simple core — the agent loop — they still need harness components beyond the loop itself. For example, every harness needs tools and context management, and many capabilities (e.g., memory and self-improvement) involve particular setups beyond just running a bare agent loop. The bitter lesson then begs the question: what’s the simplest LLM-based primitive that supports these capabilities?

More precisely, we’re looking for the simplest primitive that is expressive enough to let the LLM perform what we call “in-loop self-engineering”: implementing behavior that emulates any harness logic, but inside the agent loop itself, without external tools or systems. By engineering and adapting itself while it works through tasks, it should in theory achieve higher performance much more efficiently than current methods of recursive self-improvement.

We believe a code-mode agent loop is already surprisingly close to being that primitive. We just need a change of perspective:

Integrate the LLM into a programming language.

Traditionally, the LLM has been thought of as a map from text to text, and an agent as a system built around the LLM to let it act in an environment. We argue that the better mental model for both LLMs and agents is an LLM-like primitive invoke that’s truly “integrated” into a programming language. The input and output are both generalized: instead of strings or message lists, they are now arbitrary objects in the base language. To implement this generalized primitive invoke in terms of an actual LLM, the LLM writes code to construct the output object from the input objects. In other words, invoke is thought of as a function whose body is dynamically filled in by an LLM each time it’s called.

Our vision is that this is all that’s needed for fully general “in-loop self-engineering”. In the first step of our journey, we show how, by giving invoke an environment, it becomes an agent that can manage its own context and memory and optimize prompts and tools — all inside the loop without any external harness mechanisms or systems.

An LLM integrated into a programming language

Section titled “An LLM integrated into a programming language”

The traditional LLM primitive takes text (or a message list) and outputs text. Thus, for the LLM to be actually useful in a program we’re writing and interact with the other objects in the program, we’ll have to write parsing and unparsing boilerplate to convert between raw strings and structured objects.

Traditional LLM primitive

field_notes = pd.read_csv("notes.csv")  # one free-text note per penguinprompt = (    "Extract species, sex and weight in g as a CSV table. "    "Put the table between <table> and </table>.\n\n")↑ output format specificationprompt += "\n".join(← serialize Python object into LLM's prompt    f"Note {i}: {note}" for i, note in enumerate(field_notes["note"]))response = client.responses.create(model="gpt-5.4-nano", input=prompt)text = response.output_text← parse LLM's response into Python objecttable = text.split("<table>", 1)[1].split("</table>", 1)[0]df = pd.read_csv(io.StringIO(table.strip()))output format specificationserialize Python object into LLM's promptparse LLM's response into Python object
The traditional LLM primitive is a function from text (message list) to text, requiring conversion between objects in the language (Python) and text. Even LLM APIs that support structured output require serialization and parsing, as “structured output” is restricted to JSON or Pydantic models.

Is there a way to make an LLM more integrated into a programming language, say, Python? Suppose we extend the Python language with an “LLM” that can directly take in Python objects of any type and return a Python object of any type, so that we don’t have to deal with parsing and unparsing. Then the code above becomes just one function call:

df = invoke(← LLM directly outputs Python object    task="Extract data from my notes to a DataFrame table.",    field_notes=pd.read_csv("notes.csv"),)↑ directly give LLM the Python object# `df` is already a DataFrame objectLLM directly outputs Python objectdirectly give LLM the Python object
We hope to have an “LLM” that directly takes Python objects as inputs and outputs.

To implement this “generalized” LLM primitive invoke, we need to let the actual LLM construct an arbitrary Python object out of arbitrary input Python objects. Leveraging LLMs’ coding abilities, they can just write code that constructs that output object from the input objects. The resulting implementation of invoke, which we call “functional invoke”, can be thought of as a function whose body is dynamically generated by the language model on every invocation.

Our first observation about invoke is that no extra mechanism is needed for giving it tools to turn it into an agent — since invoke takes arbitrary objects, we can just give it the Python functions implementing the tools.

The second observation is that this agent automatically has access to invoke subagents. Since invoke is a primitive extending the language and the code the model writes is in the same language, this code is automatically allowed to contain recursive calls to invoke.

The third observation is that, despite not having an agent loop, functional invoke can emulate one. Similar to how tail recursion gives rise to while loops, tail-recursive invoke gives rise to an agent loop, which we call the invoke agent loop. More specifically, if we automatically append a recursive invoke call to the end of its LLM-generated body, you create the effect of handing control back to the LLM to issue its next action. This recursive call must explicitly pass the agent’s history (input programs and their outputs) so that the next LLM call actually has the full history in context.

Functional invoke, tail-recursive

The invoke agent loop

Both start from the same call to invoke.

The call expands into a frame, def invoke, whose inputs are what the LLM sees. On the right, the whole agent loop runs inside this one frame.

The LLM writes code. Left, the body of the function, ending in a tail call to invoke that passes the code and its output on as history. Right, its first turn in the REPL.

The code runs. Left, the tail call expands into a new frame, whose inputs, now including the history, are what the LLM sees. Right, the output appears in the frame, and the LLM sees the whole frame so far.

The LLM writes again, and ends with return: left, the new frame's body; right, the second turn.

The value comes back to the caller: on the left through every frame, on the right out of the loop. Each turn of the loop was one frame of the recursion.

Tail-recursive invoke in functional invoke gives rise to the invoke agent loop.

In practice, JAZ’s serializer for invoke inputs would truncate the history’s serialization and break caching. So instead of literally appending a tail-recursive invoke to every LLM-generated body for invoke, JAZ implements the invoke agent loop as an actual code-mode agent loop (REPL agent) with an append-only message list containing its history. But the LLM can still write its own tail-recursive invoke as a form of context management, as we will soon see.

The invoke agent loop preserves the two key properties of functional invoke that are essential to in-loop self-engineering:

  1. The LLM writes arbitrary code that can call subagents (invoke) as functions; this makes it code-mode with subagents available by default.2
  2. Everything the LLM sees can be accessed through variables in code, because everything the LLM sees is just an input to the function the LLM is writing a body for. This is what distinguishes the invoke agent loop from existing agents of the code-mode-with-subagents paradigm like smolagents, agex, RLMs, and Agentica. Although these agents do often allow you to pass in an object that becomes a variable the LLM’s code can reference, the user prompt and REPL history are not available as variables. invoke instead makes the rule apply equally to everyone, and that is essential to general in-loop self-engineering, including in the two examples that we now demonstrate.
penguin_field_study.pyinvoke frame

LLM writes invoke's body; JAZ runs it

You write"""Data extraction from text in a penguin field study""" def search_field_journal(query: str) -> str:    """Search the field team's season journal."""    url = "https://journal.example.org/api/search"    return requests.get(url, params={"q": query}).text extracted_data = def invoke(LLM sees    task="Extract data from my notes to a DataFrame table.",        Extract data from my notes to a DataFrame table.    field_notes=pd.read_csv("notes.csv"),                                                note        0    Chinstrap, Dream. Male. Mass 3900 g....        1    Female Adelie on Torgersen, 3.8 kg. ...        2    Torgersen — Adélie hen, 7.2 lb. Flip...        [344 rows x 1 columns]    search_field_journal=search_field_journal,        `search_field_journal(query: str) -> str`:        Search the field team's season journal.): LLM writesprint(search_field_journal(task))LLM sees- The scale that reads in lb was never zeroed:  subtract 0.2 lb from every weight in lb. LLM writesimport pandas as pd    parts = []    for i in range(0, len(field_notes), 50):Subagents        part = invoke(            task=task,            field_notes=field_notes[i:i + 50],            instructions=__history__[0].repl_output,        )        parts.append(part)     return pd.concat(parts, ignore_index=True)print(extracted_data)
You get

Minimal interface

All inputs — prompt, data, tools — are the same thing: keyword arguments with names you choose.

Maximally expressive

All inputs are available as variables.

Recursive subagents are available by default.

The REPL history itself is available as a variable in the REPL.

Return any Python object created in the REPL.

You write one call. The task, the notes and a tool are all the same thing: keyword arguments.

invoke's frame opens, and the LLM sees each input rendered for it: the task as text, the DataFrame as pandas prints it, the tool as its signature and docstring.

The LLM writes code against the inputs as variables: it calls the tool you passed, searching the field journal with the task itself.

JAZ runs it, and the LLM sees the output: the scale that reads in lb was off, so every weight in lb needs correcting.

It writes the rest against the same variables: it splits field_notes into parts of fifty, and returns them as one DataFrame.

Each part is invoke again: a subagent with fifty notes and the task, handed the journal's answer through __history__, the REPL's own record of what ran.

The frame closes, and extracted_data is an actual DataFrame: the object the LLM's code returned, not text describing it.

The two key properties of invoke: 1. arbitrary code allowing recursive invoke; 2. everything the LLM sees is variables in the REPL.

Case studies of in-loop self-engineering with invoke

Section titled “Case studies of in-loop self-engineering with invoke”

Unbounded horizon by emulating compaction and memory

Section titled “Unbounded horizon by emulating compaction and memory”

Current agent harnesses all have some form of compaction to avoid context rot: a loop-external LLM call summarizes the conversation history and the context is replaced with the summary. Since this loses details of the history, a substantial line of research has emerged that focuses on developing memory systems that enable long-range recall.

In fact, neither compaction nor an external memory system is needed for the effect of compaction and memory. The bare invoke agent loop is expressive enough to emulate compaction and memory in-loop.

To do so, the model delegates to a subagent to finish its work. To emulate compaction, the parent agent can give the subagent a summary of the history. To emulate memory, the parent agent passes in its __history__ so that the subagent has full programmatic access to it:

return invoke(
..., # parent's inputs, including user prompt
prev_history=__history__, # parent's history
prev_history_summary=..., # summary of history
...
)

The simplest form of in-loop compaction and memory.

The pattern above can be generalized to more sophisticated context and memory management mechanisms. For example, automated context management (e.g., Chroma Context-1 and Context Language Models) is equivalent to passing in a filtered version of __history__ with certain entries summarized or removed. Automated memory management is accomplished by maintaining programmatic state as an alternative to __history__ to pass to the subagent. More generally, invoke’s expressiveness enables the parent agent to build the subagent’s context (compaction) and state (memory) from its own context and state. This form of compaction and memory is, in principle, more flexible than any fixed harness that implements them.

To validate the basic feasibility of in-loop compaction and memory, we prompted the invoke agent loop with GPT-5.4 nano to perform a simple form of in-loop compaction and memory similar to that shown in the listing above. The agent successfully handles the StuLife extra-long-horizon benchmark, exceeding the context window by over 50x while being able to recall precise information from many context windows in the past.

0 20 40 60 80 100 cost per run (USD) 20 40 60 80 pass rate (far recall, %) better cheaper StuLife long-horizon no memory system has memory system JAZ invoke (ours) Letta/MemGPTmore search Letta/MemGPTless search CodeAct+subagentsJAZ CodeAct+subagentssmolagents CodeActJAZ
JAZ invoke uses subagents to emulate compaction and memory on the long-horizon StuLife benchmark. See the paper for the meanings of the subscripts on the methods.

As expected, CodeAct+subagents3 is ineffective as it’s unable to reliably pass its own history and inputs without modification to the subagent — it doesn’t have programmatic access to them. A system with a special memory system — Letta with the MemGPT memory architecture — also underperforms, due to the limited memory interface it exposes compared to full programmatic access to history that JAZ invoke exposes.

The invoke primitive lets the agent implement its own compaction and memory mechanism “in-loop”. Indeed, compaction and memory are just a special case of harness logic that builds the next LLM call’s context and state via some modification of the current context and state. And JAZ invoke gives the agent the means to implement that itself:

When an LLM agent’s full context and state are available in programmatic variables (invoke property 2), the LLM can efficiently build the next LLM call’s context and state from these programmatic variables and pass them to a call to invoke (invoke property 1).

Agent (depth 36)

context
LLM sees instructions=..., guidance=...,         prev_history=[...], state=..., ...⋮  5 turns, Tasks 851–852>>> task = get_next_task()Task 853/1284 (type=INFO)... Week 13, Monday 08:00 ... we introduce the'Social Interaction Alchemy Protocol', asupplemental rule that states: ...>>> res = complete_task()>>> >>> ⋮  55 more turns, Tasks 854–881>>> >>> LLM sees Your context window is close to full.         You must finish ... by delegating ...         Follow this template exactly: ... >>> # timeout: 86400    return invoke(        instructions=instructions,        guidance=guidance,        prev_history=globals().get(            "prev_history", []) + __history__,        state=state,        prev_progress_summary="So far, I            completed tasks through Task 880 ...",        next_steps="Your next step is to call            get_next_task() ...",    )
memory: full history so farcompaction: summary and next steps

Subagent (depth 37)Subsub...subagent (depth 53)

context
LLM sees instructions=..., guidance=...,  prev_history=[REPLHistoryEntry(llm_response=    "# <brief plan...", repl_output="Task 1/    1284 ...", ...), ...[...41887727 characters    omitted...]...],  prev_progress_summary="So far, I completed    tasks through Task 880 ...", ... ⋮  Tasks 882–1252, and 16 more hand-offs>>> task = get_next_task()Task 1253/1284 (type=quiz_question)... Mental Health ... final exam ...D: ... After applying the 'Social InteractionAlchemy Protocol', ...>>> term = "Social Interaction Alchemy Protocol"    for i, entry in enumerate(prev_history):        pos = entry.repl_output.find(term)        if pos >= 0: print(i, ...)2567 ... we introduce the 'Social InteractionAlchemy Protocol', a supplemental rule thatstates: ...>>> res = complete_task(answer="D")

From a real StuLife run: an agent, itself 35 hand-offs into the year, works one REPL turn at a time. At Task 853 a lecture defines a rule. Every turn stays in its context.

Fifty-nine turns later its context window is 70% full, and a hook tells it so, with a template for the hand-off.

No external compaction step: the agent itself hands the rest of the work to a subagent, filling in the template with its state and a summary and next steps in its own words.

The subagent starts with a fresh context. Among its inputs: the history, shown truncated (some 42 million characters omitted), and the summary.

It carries on, and so do its own subagents. Sixteen hand-offs and 400 tasks later, the final exam asks about that lecture: the agent reads the rule out of prev_history exactly, and answers correctly.

Example trajectory from a real StuLife run showing in-loop compaction and memory.

Continual self-improvement by emulating harness optimization

Section titled “Continual self-improvement by emulating harness optimization”

Since fixed systems don’t learn from their mistakes, people have developed self-improving agent systems that can learn over time. Those systems have varied in their optimization target (e.g., prompt vs. skills vs. full harness code) and the amount of optimization-specific logic (e.g., single LLM call vs. evolutionary algorithms vs. general-purpose coding agents). But one thing that is common to all existing self-improving systems is that there’s some mechanism external to the task-solving agent that enables the self-improvement, such as an optimization algorithm, a meta-agent, external memory (e.g., file system), or logging.

On the other hand, the invoke primitive can self-improve in-loop by using the top-level agent as a meta-agent and subagents as task-solving agents. Opposite to compaction and memory, subagents now pass their own REPL histories up to their parent to let the meta-agent analyze and improve its inputs to solver subagents.

At first, optimizing inputs to an invoke subagent may appear limiting compared to self-improving systems that optimize the entire harness code. However, if we’re right about invoke supporting fully general in-loop self-engineering, then any harness logic can be realized by prompting invoke to emulate it. As such, optimizing inputs to invoke should be no less expressive than optimizing harness code itself.

To validate the feasibility of optimizing task-solving subagents in-loop, we prompted invoke to create and improve the prompt and tools to task-solving subagents across a sequence of tasks. Over the full sequence of AppWorld tasks, we obtained on average a 7% improvement over the non-self-improving baseline at just 2x its cost.

20 40 60 80 100 120 cost per run (USD) 45 50 65 70 75 pass rate (%) better cheaper AppWorld self-improvement no meta-harness has meta-harness JAZ invoke (ours) ACEbatch; train all ACEtrain 10% CodeAct+subagentsJAZ CodeActJAZ CodeActAppWorld
JAZ invoke uses subagents to perform continual self-improvement on the AppWorld benchmark. See the paper for the meanings of the subscripts on the methods.

CodeAct+subagents3 is less effective as subagents struggle to give the top-level agent their own trajectories. Agentic context engineering (ACE), a specialized system for self-improvement, costs 11x as much to reach the same amount of improvement, and when restricted to 3x the cost the improvement is reduced to just 2% (n.s.). The high cost is caused by ACE’s rigid self-improvement workflow, which JAZ invoke avoids by giving the agent the flexibility to batch tasks as appropriate and selectively read the most relevant parts of trajectories.

The invoke primitive makes it possible for an agent to effectively optimize its subagents. Indeed, self-improvement is just a special case of harness logic where agents communicate their own state and context with each other: the subagent gives its parent agent its context, which allows the parent agent to update its state, which is inputs to subagents. And JAZ invoke provides the agent the means to implement such communication itself:

When an LLM agent’s full context and state are available in programmatic variables (invoke property 2), agents can efficiently build “messages” from their own context and state and communicate those messages with each other by providing inputs and receiving output from invoke (invoke property 1).

Top-level agent (acts as meta-agent)

LLM sees single_task_instructions=..., guidance=...,         get_next_task=..., complete_task=..., ...>>> prompt = f"""{single_task_instructions}    Return a Python dict with exactly these keys:    - 'answer': the single number, single string, or None    - 'history': your __history__ ..."""    for i in range(5):        task = get_next_task()        result = invoke(task=task,            instructions_for_subagent=prompt)        grade = complete_task(result['answer'])            pprint(summary)[..., {'invoke_ok': True, 'num_failed': 5, 'num_passed': 1,  ..., 'success': False, 'task_index': 3}, ...]AssertionError: {'AMZA2B70', ...} == {'AMZa2b70', ...}>>> for r in failed:        for i, h in enumerate(r['history']):            print(i, h.llm_response[:1400])            print(h.repl_output[:1400], h.repl_exception)12 # <brief plan for next step># Inspect a first batch of candidate Gmail threads, ...def normalize_code(c: str) -> str:    c = c.strip().upper()>>> prompt = f"""{single_task_instructions} ...    - Preserve exact strings copied from source data:      codes, IDs, names, ... casing, and punctuation.      Do not uppercase/lowercase/normalize unless ...    - For tasks asking for "all", "every", or exhaustive      lists, paginate until results are exhausted. ..."""    def login_app(app_name: str) -> dict:        """Log the current supervisor into an app ..."""        ...    for i in range(8):        task = get_next_task()        result = invoke(task=task, login_app=login_app,            instructions_for_subagent=prompt, ...)            print({'batch_num': ..., 'successes': successes, ...}){'batch_num': 2, 'batch_size': 8, 'successes': 7, ...}>>> 

3rd subagent (acts as solver agent)

LLM sees task="... Find all Amazon promo codes from my           Gmail account, including spam and archived           emails, and give it to me in a comma-separated           list.", instructions_for_subagent="...">>> print(apis.supervisor.show_account_passwords())>>> access = apis.gmail.login(username=..., password=...)>>> >>>     def normalize_code(c: str) -> str:        c = c.strip().upper()⋮  24 turns in all, 1 error>>> answer = ",".join(amazon_codes)    return {"answer": answer, "history": __history__}

6th subagent (acts as solver agent)

LLM sees task="... Place an order for all staplers in           my amazon cart.",         instructions_for_subagent="... Preserve exact           strings copied from source data ...",         login_app(app_name: str) -> dict: Log the           current supervisor into an app ...>>> >>> amazon_login = login_app("amazon")    access_token = amazon_login["access_token"]⋮  9 turns in all, 3 errors>>> return {"answer": None, "history": __history__}

From a real AppWorld run: the top-level agent, a meta-agent, writes a seed prompt that asks each subagent for its own __history__ back, and runs a first batch of five tasks, one subagent each, grading every answer.

The 3rd subagent must list every Amazon promo code in the user's Gmail. On the way it uppercases each code, then returns its answer and its whole history.

The 3rd subagent has returned, and is gone. Three of five tasks pass: task 3 fails five of its six checks, its codes in the wrong case and three missing.

The meta-agent reads the failed subagents' histories as data, turn by turn, including the line where subagent 3 uppercased every code.

It writes the general lesson into the prompt, exact strings and exhaustive searches, adds a login tool, and launches a batch of eight.

The 6th subagent logs in to Amazon with the new tool in one call, and passes all seven checks.

Seven of eight pass. The meta-agent keeps reading, revising, rolling back and validating, on batches of up to 64.

Example trajectory from a real AppWorld run showing in-loop continual self-improvement.

While we’ve shown two examples of how invoke can be prompted to emulate external harness logic, we believe more generally that any kind of harness we’d ever want to write is expressible within the invoke agent loop. The reason is simple. Every existing harness is logic that determines what each LLM call’s context and state are, based on context, state, and outputs from previous LLM calls. And the definition of invoke is exactly what allows the LLM to perform “in-loop self-engineering”: writing code that constructs what future LLM calls can see and access from previous state, context, and LLM outputs.

While we don’t claim models can already perform fully general “in-loop self-engineering”, we believe that an agent loop that gives the LLM that potential is the first step. We give the LLM wings so that we can eventually teach it to fly.

Giving the LLM a ton of flexibility also comes with risks — even the most basic ReAct-style tool-calling agent runs the risk of unbounded API spend, requiring iteration and cost limits to prevent during evals. As a result, we built a full agent framework, JAZ, where the core agent primitive, invoke, is this minimalist primitive with maximal expressivity, and an expressive hook system lets users monitor, constrain, validate, and even modify the agent. Feel free to reach out to us if you’re interested in becoming a core contributor to JAZ!

On the research side, we’ve been running more experiments with more baselines and benchmarks, and we will be putting out more blog posts analyzing them in depth — stay tuned! We’re also exploring more expressive forms of in-loop self-engineering that give the agent more freedom (less handholding via prompts), and other things we can do with the invoke primitive. If you’re excited about this direction of research, don’t hesitate to reach out to us for a collaboration!

Paper: arxiv.org/abs/2609.26891 (NeurIPS 2026 Meta-Agents Workshop oral)

GitHub: github.com/jaz-lang/jaz

Discord: discord.gg/dBrJmSPW5x

X (Twitter): @jaz_lang_ai

Email: jazlang.team@gmail.com

  1. Joshua, Mateja, Nicole, Supriya, Amitayush, Alex, Omar, Jonathan, Armando ↩

  2. This is the default paradigm of dspy.RLM v3.4.1+ and agex. Agentica and smolagents don’t have subagents by default, but support them. ↩

  3. Our reimplementation in JAZ as a controlled ablation of invoke, intended to encompass existing code-mode agent loops such as smolagents and RLMs. ↩ ↩2