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)[源代码]#
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 aharnessglobal into its modules, and registers every@toolit defines and lists its Markdown notes.- 参数:
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_sessionsNothing 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
ToolGuidelinesExtensiondecides 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, sowants_tool_guidance()leaves tool guidance out of the block instead of sending it twice.备注
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, andwants_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 overrideinstructions()to match.示例
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)[源代码]#
Return an existing session's toolbox for explicit inspection.
- 参数:
session_id (str)
- 返回类型:
- session_directory(session_id)[源代码]#
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.
- 参数:
session_id (str)
- 返回类型:
Path
- forget_session(session_id)[源代码]#
Release an idle in-memory toolbox; this does not delete its files.
- 参数:
session_id (str)
- 返回类型:
None
- async on_tool(context)[源代码]#
Rebind current base tools, mount wrappers, and remove unloaded tools.
- 参数:
context (AgentRunContext)
- 返回类型:
None
- async on_state(context)[源代码]#
Adopt tools registered by later setup hooks before context loading.
- 参数:
context (AgentRunContext)
- 返回类型:
None
- async on_tool_call(context, call, call_next)[源代码]#
Adopt late before-tool registrations before handler middleware runs.
- 参数:
context (AgentRunContext)
call (ToolCall)
call_next (ToolCallNext)
- 返回类型:
- async before_tool(context, call)[源代码]#
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.
- 参数:
context (AgentRunContext)
call (ToolCall)
- 返回类型:
None
- async after_tool(context, call, result, error)[源代码]#
Report the outcome of a management or dynamic tool call.
- 参数:
context (AgentRunContext)
call (ToolCall)
result (ToolMessage)
error (Exception | None)
- 返回类型:
None
- management_tools(harness)[源代码]#
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.- 参数:
harness (JITHarness)
- 返回类型:
Sequence[AgentTool]
- instructions(harness)[源代码]#
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 withmanagement_tools().- 参数:
harness (JITHarness)
- 返回类型:
str
- notes_catalog(harness)[源代码]#
Return the repository's note catalog for the guidance block.
Empty by default. Set
include_notesfor 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, andrender_note_catalog()keeps it withinMAX_NOTE_CATALOG_CHARS; omitted notes stay reachable throughrepo_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.
- 参数:
harness (JITHarness)
- 返回类型:
str
- wants_guidance(harness, offered)[源代码]#
Return whether this request carries the JIT guidance block.
offeredis the set of tool names the provider will see after policy filtering. By default the block followsguidance_tool; None means any registered management tool activates it.- 参数:
harness (JITHarness)
offered (set[str])
- 返回类型:
bool
- wants_tool_guidance(context)[源代码]#
Return whether the block carries the tools' snippets and guidelines.
A registered
ToolGuidelinesExtensionthat 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.- 参数:
context (AgentRunContext)
- 返回类型:
bool
- async on_model_request(context, request, call_next)[源代码]#
Place current guidance after the request's leading system instructions and before dialogue.
- 参数:
context (AgentRunContext)
request (ModelRequest)
call_next (ModelRequestNext)
- 返回类型:
AsyncIterator[ModelEvent]
- async on_success(context, result)[源代码]#
Release request bindings while retaining the session's definitions.
- 参数:
context (AgentRunContext)
result (AssistantMessage)
- 返回类型:
None
- async on_error(context, error)[源代码]#
Release bindings after setup, model, or tool-hook failures.
- 参数:
context (AgentRunContext)
error (Exception)
- 返回类型:
None
- async on_event(context, event)[源代码]#
Detach cancelled requests so late worker calls cannot use a new run.
- 参数:
context (AgentRunContext)
event (ExtensionEvent)
- 返回类型:
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.
- 参数:
config (AgentRunConfig | None)
event (ExternalEvent)
- 返回类型:
bool
- async after_model(context, response)#
Run after the complete assistant message is appended.
- 参数:
context (AgentRunContext)
response (ModelResponse)
- 返回类型:
None
- async after_run(context, result)#
Run after a successful final answer is appended.
- 参数:
context (AgentRunContext)
result (AssistantMessage)
- 返回类型:
None
- async after_turn(context, result)#
Run once the turn's assistant message and tool results are settled.
resultis 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.
- 参数:
context (AgentRunContext)
result (AssistantMessage)
- 返回类型:
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()orAgentRunContext.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.示例
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."), )
- 参数:
context (AgentRunContext)
request (ModelRequest)
- 返回类型:
None
- async before_run(context)#
Run after the transformed user input is appended and published.
- 参数:
context (AgentRunContext)
- 返回类型:
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.
- 参数:
context (AgentRunContext)
- 返回类型:
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.compactrestores the session throughon_toolandon_stateexactly 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.示例
Usage:
async def on_compact(self, context): await self.compact(context)
- 参数:
context (AgentRunContext)
- 返回类型:
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()orAgentRunContext.replace_messages(), and persistence subscribers have already received it.- 参数:
context (AgentRunContext)
- 返回类型:
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;
pendingremains true until all requests using that instance have finished, failed, or been cancelled. Persistent data retained between requests does not count.