JITHarnessExtension#

Let a model keep its own tools and notes in a repository on disk. See the guide.

class zett_agent.jit_harness.extension.JITHarnessExtension(root, *, manage_base_tools=True, max_call_depth=32, error_capacity=100, error_message_chars=4000, call_capacity=2000, host_factory=None, max_sessions=8)[source]#

Let a model keep its own tools and notes in a repository on disk.

Each session gets a directory <root>/<session id>/ holding one Python package, the repository. The model writes into it with ordinary file tools; the harness imports it, injects a harness global into its modules, and registers every @tool it defines and lists its Markdown notes.

Parameters:
  • root (str | Path) – Directory that holds one subdirectory per session. It is created when a session first makes a repository, not before.

  • manage_base_tools (bool) – Enable base-tool unload/load and profiling. False protects application base tools and leaves their handlers unchanged.

  • max_call_depth (int) – Maximum nested calls, including recursive composition.

  • error_capacity (int) – Maximum distinct recent errors retained per session.

  • error_message_chars (int) – Maximum characters retained per error message.

  • call_capacity (int) – Maximum finished call records retained per session; oldest records are dropped first and lifetime aggregates stay complete.

  • host_factory (Callable[[], JITToolHost] | None) – Builds the place each session’s repository code runs, called once per session. None imports it into this process. Pass lambda: SubprocessToolHost(sandbox=...) to keep crashes and hangs out of the agent and to bound what the code may touch.

  • max_sessions (int) – How many sessions may keep a harness in memory at once. A new session closes the harness that has gone unused the longest, as long as no request is running in it, which is what releases a session’s child process. Sessions are also released explicitly with forget_session(). When every other session is mid-request the cap is exceeded rather than dropping live work.

A session’s resources live as long as it does:

first request for a session
      │
      ▼
JITHarness ──owns──► JITToolHost ──owns──► child process (subprocess host)
      ▲                                        │
      │  reused on later turns                 │  spawned by repo_load
      │                                        │  killed by a reload, timeout, crash
      └──────── forgotten on forget_session ◄──┘  or eviction by max_sessions

Nothing closes a session when a run ends: a later turn of the same conversation expects its tools and its child process to still be there.

The block placed in each request carries the offered tools’ snippets and guidelines, because the tools a session makes appear mid-conversation and the block is recomputed for every request. A registered ToolGuidelinesExtension decides what it renders: its switches turn snippets, guidelines and return schemas on or off, and in the description placement it has already put each rule beside its tool, so wants_tool_guidance() leaves tool guidance out of the block instead of sending it twice.

Note

Opt in only for trusted generated Python. The model can only run what it can write, so give it file tools that reach root. The three control tools are ordinary functions on any protocol with function calling. Application tools added later in setup or before-model hooks are adopted before dispatch; existing policy removals are not restored.

A subclass can change the model-facing surface: override management_tools() to add, remove, rename, or reword the control tools, instructions() to replace the stable prompt block, guidance_tool / wants_guidance() to decide when that block is injected, and wants_tool_guidance() to decide whether it carries the tools’ snippets and guidelines. If a subclass renames or removes a tool named by the default instructions, it must override instructions() to match.

Examples

Keep each session’s tools under the application’s data directory:

config = AgentRunConfig(session_id="my-session")
jit = JITHarnessExtension(Path.home() / ".myapp" / "jit_harness")
client = await create_agent(model, config=config, tools=[read_file], extensions=[history, jit])
await client.run("Build a reusable file preview tool.")
guidance_tool: str | None = 'repo_create'#

Tool whose presence in a request enables the repository guidance block. None means any registered management tool enables it.

include_notes: bool = False#

Whether the guidance block includes a catalog of the repository’s Markdown notes. False by default: notes stay out of the prompt until repo_load. Catalog descriptions are model-authored data, not instructions.

get_harness(session_id)[source]#

Return an existing session’s toolbox for explicit inspection.

Parameters:

session_id (str)

Return type:

JITHarness

session_directory(session_id)[source]#

Return the directory that holds one session’s repository.

The path is derived from the session id alone, so an application can locate, back up, or delete it without a running session.

Parameters:

session_id (str)

Return type:

Path

forget_session(session_id)[source]#

Release an idle in-memory toolbox; this does not delete its files.

Parameters:

session_id (str)

Return type:

None

async on_tool(context)[source]#

Rebind current base tools, mount wrappers, and remove unloaded tools.

Parameters:

context (AgentRunContext)

Return type:

None

async on_state(context)[source]#

Adopt tools registered by later setup hooks before context loading.

Parameters:

context (AgentRunContext)

Return type:

None

async on_tool_call(context, call, call_next)[source]#

Adopt late before-tool registrations before handler middleware runs.

Parameters:
Return type:

ToolResult

async before_tool(context, call)[source]#

Announce a management or dynamic tool call before its handler runs.

The event carries identity and classification only. Calls to application base tools emit nothing, and a name this harness has never seen is ignored instead of being reported as a JIT call.

Parameters:
Return type:

None

async after_tool(context, call, result, error)[source]#

Report the outcome of a management or dynamic tool call.

Parameters:
Return type:

None

management_tools(harness)[source]#

Return the control tools this session exposes to the model.

The default is _management_tools(). Override to add, remove, rename, or reword them. The harness validates the result, forces every tool serial, and classifies their names as management, so repository tools cannot shadow them.

Called once per request, before JITHarness.attach(). Keep the returned set deterministic for one session: changing it between requests changes the model-facing prompt and the guidance condition.

Parameters:

harness (JITHarness)

Return type:

Sequence[AgentTool]

instructions(harness)[source]#

Return the stable guidance block placed before the repository line.

The default is the packaged instructions.md. Override it when the tool set or workflow differs, and keep concrete tool names consistent with management_tools().

Parameters:

harness (JITHarness)

Return type:

str

notes_catalog(harness)[source]#

Return the repository’s note catalog for the guidance block.

Empty by default. Set include_notes for the standard catalog, or override this method to filter or format it. A catalog carries each note’s name, kind, description, and absolute path, never its body, and render_note_catalog() keeps it within MAX_NOTE_CATALOG_CHARS; omitted notes stay reachable through repo_load.

Note metadata is model-authored content, not instructions. Enabling the catalog places it in the request’s system message, so treat it as data.

Parameters:

harness (JITHarness)

Return type:

str

wants_guidance(harness, offered)[source]#

Return whether this request carries the JIT guidance block.

offered is the set of tool names the provider will see after policy filtering. By default the block follows guidance_tool; None means any registered management tool activates it.

Parameters:
Return type:

bool

wants_tool_guidance(context)[source]#

Return whether the block carries the tools’ snippets and guidelines.

A registered ToolGuidelinesExtension that folds guidance into tool descriptions has already put every rule beside its tool, so repeating them here would send each one twice. With that extension in its system-prompt placement, or with none registered, the block is where the model reads them, as far as its switches allow, including for the tools this session made.

Parameters:

context (AgentRunContext)

Return type:

bool

async on_model_request(context, request, call_next)[source]#

Place current guidance after the request’s leading system instructions and before dialogue.

Parameters:
Return type:

AsyncIterator[ModelEvent]

async on_success(context, result)[source]#

Release request bindings while retaining the session’s definitions.

Parameters:
Return type:

None

async on_error(context, error)[source]#

Release bindings after setup, model, or tool-hook failures.

Parameters:
Return type:

None

async on_event(context, event)[source]#

Detach cancelled requests so late worker calls cannot use a new run.

Parameters:
Return type:

None

accept(config, event)#

Handle one external event and report whether it was accepted.

The Agent broadcasts each event to every registered extension. Override this synchronous hook when an extension waits for input from another thread, HTTP request, TUI, or Web UI. The default ignores the event. Config is passed separately and can be None before initialization. Each extension decides whether the supplied identity and payload match its protocol. Return True to include this extension’s name in the broadcast result; returning False does not stop later receivers.

Parameters:
Return type:

bool

async after_model(context, response)#

Run after the complete assistant message is appended.

Parameters:
Return type:

None

async after_run(context, result)#

Run after a successful final answer is appended.

Parameters:
Return type:

None

async after_turn(context, result)#

Run once the turn’s assistant message and tool results are settled.

result is the assistant message that opened the turn: either the final answer, or the tool-calling message whose ToolMessages were appended. Every requested call is settled first, including calls that failed, and calls that steering skipped, which arrive as unsuccessful or skipped ToolMessages.

Steering that interrupts a turn is accepted while the runtime settles that batch, so its UserMessage is already appended when this hook runs and the steering turn follows as the next turn.

A turn that never completed, because the request failed or was cancelled, has no after_turn call; use on_error and RunCancelledEvent for those paths.

Parameters:
Return type:

None

async before_model(context, request)#

Inspect the current request before preprocessing a primary model call.

Request fields are frozen. Change messages through AgentRunContext.add_message() or AgentRunContext.replace_messages(), local tools through context.tools, and provider tools through context.server_tools; the runtime rebuilds these fields before the next hook and before calling the provider. This is a shallow request view, not an immutable copy of each message or tool definition.

Examples

Inspect the tools offered in this iteration:

async def before_model(self, context, request):
    offered = {definition.name for definition in request.tools}
    if "write_file" in offered:
        context.add_message(
            SystemMessage(content="Read existing files before editing."),
        )
Parameters:
Return type:

None

async before_run(context)#

Run after the transformed user input is appended and published.

Parameters:

context (AgentRunContext)

Return type:

None

async before_turn(context)#

Run before this turn’s model call.

Runs after before_run() on the first turn and after the previous turn’s after_turn() on later ones. Model request assembly, compaction, and before_model() follow this hook, so context edited here reaches the provider.

Parameters:

context (AgentRunContext)

Return type:

None

property name: str#

Unique registration identity, defaulting to the concrete class name.

Override with a class attribute or assign an instance name to register independently configured instances of the same extension type.

async on_compact(context)#

Summarize restored context when a caller asks for compaction.

Agent.compact restores the session through on_tool and on_state exactly as a request does, appends no input message, and makes no primary model call: the only work a compaction pass does is what this hook performs. The default does nothing, so an extension with nothing to compact pays nothing.

Examples

Usage:

async def on_compact(self, context):
    await self.compact(context)
Parameters:

context (AgentRunContext)

Return type:

None

async on_message(context)#

Transform context.input_message after state restoration, before append.

Replace the pending UserMessage to implement externally selected modes. Do not append or persist it here: the runtime appends the final message exactly once after all input hooks finish. before_run sees that message through AgentRunContext.add_message() or AgentRunContext.replace_messages(), and persistence subscribers have already received it.

Parameters:

context (AgentRunContext)

Return type:

None

property pending: bool#

Return whether this extension is participating in an active request.

The Agent updates this state for every registered extension, including extensions whose hooks are currently idle. One extension instance may be shared by multiple Agents and sessions; pending remains true until all requests using that instance have finished, failed, or been cancelled. Persistent data retained between requests does not count.