Skip to content

jaz.hooks.effects

New to JAZ? This is generated API reference. Start with the docs and the concepts overview.

Public API of the jaz.hooks.effects submodule (import from jaz.hooks.effects, e.g. from jaz.hooks.effects import ...).

An effect is what a hook handler returns to influence the run — see jaz.hooks.Hook. Each class below documents the events it is valid at and how multiple instances of it compose; an effect returned at an event that does not accept it raises InvalidEffectError (out-of-stage effects are hook bugs and fail loudly, never silently no-op). The effects every hook returns at an event are composed together before they are applied.

Where each effect composes, per pipeline stage (see jaz.hooks.events for the Enter → Send → Complete → Exit pipeline itself):

Enter (edit the proposal) InvokeEnter: AddInputs, DropInputs, DisableRecursion,
WithholdREPLHistory
LLMQueryEnter: AddMessages, DropMessages
REPLExecEnter: AddToNamespace, DropFromNamespace, InsertCode, DeleteCode
Send (supply the result, LLMQuerySend: SupplyLLMResponse
skipping the work) REPLExecSend: SupplyExecResult
InvokeSend: SupplyInvokeResult
Complete (transform the raw REPLExecComplete: ModifyExecResult
result) InvokeComplete: ModifyInvokeResult
LLMQueryComplete: ModifyLLMResponse
Exit (observe the outcome) LLMQueryExit / REPLExecExit: Abort (every arm)
InvokeExit: (observation-only)

Abort is additionally valid at every Enter/Send/Complete above, and — for the per-turn spans only — at LLMQueryExit / REPLExecExit on every arm (to stop the run on the post-transform result/response, the one the *Complete transform can’t yet see; on the Aborted / Failed arms the abort is folded into the already-unwinding exception via an ExceptionGroup rather than replacing it). InvokeExit stays observation-only. BlackboardWrite is valid at every event including every Exit.

Base class for all effects — the values a hook handler returns to influence the run.

Each subclass documents the events it is valid at and how multiple instances of it compose. An effect returned at an event that does not accept it raises InvalidEffectError — out-of-stage effects fail loudly rather than silently no-op.

Effects are frozen: a hook constructs one to declare an intent, and it is only ever read from there on.

__init__() -> None

Bases: Effect

Supply a result in place of running the turn’s code.

Valid at REPLExecSend only — the committed code is in view and a result must not yet exist to be supplied. The code is not executed and the carried result becomes the turn’s outcome.

Composition: multiple supplies fold. Kind precedence is Raise > Return > Continue — when supplies of different kinds meet, the highest present wins and the lower ones drop. Within one kind: two Continue results concatenate their outputs and group their exceptions; two distinct Return values raise ReturnValueConflictError (identical values coalesce); two Raise results group their exceptions. A Abort supersedes the whole fold.

Because only the output field of Continue is shown to the agent, a supplied Continue should render any error into its output field, otherwise the agent does not see it — e.g. Continue(output=summarize_exception(exc), exception=exc).

Attributes

__init__(result: ExecResult) -> None

Bases: Effect

Replace a result that already exists with the carried one.

Valid at REPLExecComplete only — the REPL transform boundary, where a result exists to replace. The invoke transform boundary (InvokeComplete) takes ModifyInvokeResult instead, since an invoke completes only on a terminal result.

Composition: multiple transforms fold by carried kind. Kind precedence is Raise > Return > Continue — when transforms of different kinds meet, the highest present wins and the lower ones drop. Within one kind: a Continue concatenates its output onto the original’s and groups its exception; two distinct Return values raise ReturnValueConflictError (identical values coalesce); two Raise results group theirs. A Abort supersedes the fold.

Because only the output field of Continue is shown to the agent, a carried Continue should render any error into its output field, otherwise the agent does not see it — e.g. Continue(output=summarize_exception(exc), exception=exc).

Attributes

__init__(result: ExecResult) -> None

Bases: Effect

Replace an invoke’s terminal result with the carried one.

Valid at InvokeComplete only — the invoke transform boundary. The carried result must be terminal (a Return or a Raise): the agent loop has already finished, so — unlike ModifyExecResult at REPLExecComplete — there is no next turn a Continue could resume, and one is rejected at construction.

Composition: multiple transforms fold by carried kind, exactly as ModifyExecResult does, but the fold can only ever yield a Return or Raise here because no Continue can be carried. Kind precedence is Raise > Return; two distinct Return values raise ReturnValueConflictError (identical values coalesce). A Abort supersedes the fold.

Attributes

  • result (TerminalExecResult) — The Return / Raise to replace the invoke’s terminal result with.

Raises

  • TypeError — At construction, if result is a Continue.
__init__(result: TerminalExecResult) -> None

Bases: Effect

Supply an invoke’s terminal result, skipping the entire agent loop.

Valid at InvokeSend only — the supplier sees the invoke’s committed inputs and no work has run yet. The agent loop (its REPL turns and LLM calls) is not executed and the carried result becomes the invoke’s outcome. The invoke transform boundary still fires, so a ModifyInvokeResult — and the ReturnType / ValidateReturn backstops — still apply to the supplied result (mirroring how a SupplyExecResult still flows through REPLExecComplete).

The carried result must be terminal (a Return or a Raise): an invoke never completes on a Continue, so there is no Continue to supply in place of running it, and one is rejected at construction (as with ModifyInvokeResult).

Composition: multiple supplies fold among themselves, exactly as SupplyExecResult does at REPLExecSend but on terminal results only — a Raise supersedes a Return; two distinct Return values raise ReturnValueConflictError (identical values coalesce). A Abort supersedes the whole fold.

Attributes

  • result (TerminalExecResult) — The Return / Raise to use instead of running the invoke.

Raises

  • TypeError — At construction, if result is a Continue.
__init__(result: TerminalExecResult) -> None

Bases: Effect

Abort this invoke: error propagates out of jaz.invoke() as a raised exception.

Valid at every control event — the *Enter, *Send, and *Complete events of all three spans — and, for the per-turn spans, at LLMQueryExit / REPLExecExit on every arm (Completed is the post-transform, pre-act point; on the Aborted / Failed arms an exception is already unwinding, so the abort is folded into it via an ExceptionGroup rather than replacing it). InvokeExit stays observation-only.

At LLMQueryComplete the query has already completed and been paid for; the abort stops the turn before the agent acts on the response, so the code the model proposed never runs.

Abort is a mechanism, and its scope is exactly the invoke it fires in: the invoke ends by raising the carried exception, and the aborting invoke’s spans close with an Aborted outcome on their *Exit events. How far the stop travels is decided by the carried exception’s category, not by this effect: a parent invoke observes an aborted child as an ordinary recoverable error in its REPL (a raising call it can catch and proceed past) — UNLESS the carried exception is FatalError-category, which no agent contains: the framework re-raises it past every agent in the tree, and only human-authored code (the top-level caller included) catches it normally. The containment boundary is authorship, not tree depth.

Composition: it has the highest precedence wherever it co-occurs with the result effects, superseding both SupplyExecResult and ModifyExecResult. Multiple aborts group their exceptions into an ExceptionGroup.

Attributes

  • error (Exception) — The exception to abort the invoke with.
__init__(error: Exception) -> None

Bases: Effect

Write a key/value into the per-invoke blackboard.

The blackboard is a small shared scratch space — a key/value store that every hook active for an invoke can read and write — through which hooks pass per-invoke data to one another and to the caller without calling each other directly.

Valid at any event — the blackboard spans the whole invoke rather than one context. Writes are applied at the event boundary after every hook has run, so a write is invisible to the event that produced it and surfaces to the next one. That is what lets a producer and a consumer hook coordinate without depending on dispatch order.

Composition: within one event, identical writes coalesce and two writes to the same key with different values raise BlackboardWriteConflictError.

Attributes

  • key (str) — The blackboard key to write.
  • value (object) — The value to publish under that key.

Examples

# A tracking hook publishes accumulated cost for a forcing hook to read next event.
BlackboardWrite(key="cost", value=0.05)
__init__(key: str, value: object) -> None

Bases: Effect

Withhold the recursive invoke tool from this invoke.

Valid at InvokeEnter only.

Composition: a pure signal carrying no fields, so emitting it more than once is the same as emitting it once.

__init__() -> None

Bases: Effect

Withhold __history__ from this invoke: the REPL does not bind it, and the prompt does not describe it.

Valid at InvokeEnter only.

Composition: a pure signal carrying no fields, so emitting it more than once is the same as emitting it once.

__init__() -> None

Bases: Effect

Add inputs to the invoke, equivalent to adding more name=value pairs as keyword arguments to jaz.invoke.

Valid at InvokeEnter only. Each entry both renders in the user prompt and binds as a REPL variable. For a namespace-only binding that leaves the prompt alone, use AddToNamespace.

Composition: all inputs are unioned; the same key with the same value coalesces, and with a different value raises REPLInputConflictError, so no hook silently overwrites another. A key colliding with an input or scope entry passed to the invoke also raises — unless a DropInputs at the same invoke names that key, which clears it first and makes the pair a replacement. (That drop only works on a key the invoke was passed; one that another hook merely adds raises MissingDropTargetError instead.) Naming __builtins__ raises KeyEditDeniedError. An add always wins over a DropInputs of the same key: drops are applied first.

Values bind under their own names, exactly as a top-level input does.

Attributes

  • inputs (dict[str, object]) — Name-to-value pairs to add; each renders in the prompt and binds in the REPL.

Examples

AddInputs({"config": {"api_key": "abc"}})
__init__(inputs: dict[str, object]) -> None

Bases: Effect

Un-pass invoke inputs by name, equivalent to removing name=value keyword arguments from jaz.invoke.

Valid at InvokeEnter only. Each listed name is removed as if it had never been passed to jaz.invoke, so it is removed from both the prompt and the REPL. Contrast DropFromNamespace, which unbinds a REPL name only and leaves the prompt rendering intact. A jaz.scope value is not an input: naming one is dropping a name the invoke never received (below), and no effect edits scope.

Composition: names are unioned across all drops, order-independently. Drops are applied before any AddInputs, so dropping and adding the same name replaces it provided that name was passed to the invoke, and a drop can only remove what the invoke was passed — never an input another hook added.

Dropping a name the invoke never received raises MissingDropTargetError — a typo or a re-drop-every-turn pattern is a hook bug. A name that only an AddInputs provides counts as never received. Set allow_missing=True for a defensive drop that tolerates the name already being absent; it is tracked per-name, so one tolerant hook suffices. Note that this silences the error without making the drop remove an added name — the add still wins.

Attributes

  • names (set[str]) — The input names to un-pass.
  • allow_missing (bool) — Whether dropping an absent name is tolerated rather than an error.

Examples

DropInputs({"secret_token"})
DropInputs({"maybe_absent"}, allow_missing=True)
__init__(names: set[str], allow_missing: bool = False) -> None

Bases: Effect

Bind names into the agent’s REPL namespace before a turn’s code runs.

Valid at REPLExecEnter only. Each name is bound as a REPL variable; the prompt is untouched, so the agent is not told the name exists.

It is therefore not how an input is added: an input binds in the REPL and renders in the user prompt, and adding one is AddInputs, at InvokeEnter. Nor is it how the framework’s invoke and __history__ are provided: each is bound and described in the system prompt together unless DisableRecursion or WithholdREPLHistory withholds it, and binding either name here gives the agent a value the prompt describes differently or not at all.

Composition: all entries are unioned; identical (name, value) coalesces and a divergent value for the same name raises REPLInputConflictError. Binding a name already present in the namespace also raises rather than clobbering it. A name that lives only in __builtins__ — an allowed builtin such as len, or what the framework provides there, such as __history__ or invoke — is not bound, so adding it succeeds and shadows what was there, as an assignment in the agent’s code would. Naming __builtins__ itself raises KeyEditDeniedError.

Drops are applied before adds, so pairing a DropFromNamespace with an add re-binds a name, and an add wins over a drop of the same name in the same turn. Pair with DropFromNamespace(..., allow_missing=True) whenever the name may not be bound yet — on the turn it is still unbound, a strict drop raises MissingDropTargetError before the add ever runs.

Attributes

  • entries (dict[str, object]) — Name-to-value pairs to bind in the REPL namespace.

Examples

AddToNamespace({"scratch": {}})
__init__(entries: dict[str, object]) -> None

Bases: Effect

Remove names from the agent’s REPL namespace before a turn’s code runs.

Valid at REPLExecEnter only. Each listed name is deleted before the turn’s code executes, as del name in the agent’s code would. It reaches any name bound in the namespace, whatever put it there — an invoke input, a hook’s binding, a variable an earlier turn assigned. What __builtins__ holds (an allowed builtin such as len, or the framework’s __history__ and invoke) is not bound unless a variable shadows it, so naming it is a missing target, as del len raises NameError; dropping a shadow removes only the shadow, and the original shows again.

The prompt is untouched, so this is not how an input, invoke or __history__ is taken away: each is described in the prompt, and dropping the binding alone leaves the agent told about a name that raises NameError. Un-passing an input is DropInputs, which removes it from the user prompt and the REPL together, at InvokeEnter; withholding invoke or __history__ is DisableRecursion or WithholdREPLHistory, which the system prompt follows likewise. Use this effect for names the prompt does not describe.

Composition: every drop’s names are combined into one set and applied once, so the outcome does not depend on hook order. Two hooks naming the same bound name therefore produce a single deletion.

Dropping a name that is not bound raises MissingDropTargetError. Pass allow_missing=True to ignore names that are not bound rather than raising; if an unbound name is dropped by both a DropFromNamespace(..., allow_missing=True) and a DropFromNamespace(..., allow_missing=False), then the drop is ignored and will not raise — one tolerant drop exempts the name for every hook naming it. Naming __builtins__ always raises KeyEditDeniedError, which allow_missing cannot suppress. A drop that raises removes nothing.

Drops are applied before any AddToNamespace, so pairing the two re-binds a name, and a drop only removes what was bound before the turn — never a name an add supplies. If the name may not be bound yet, the drop needs allow_missing=True, or it raises before the paired add can bind it.

Attributes

  • names (set[str]) — The REPL names to unbind.
  • allow_missing (bool) — Whether dropping an unbound name is tolerated rather than an error.

Examples

# Unbind a variable an earlier turn assigned, before this turn's code runs.
DropFromNamespace({"scratch"})
# Unbind a name that may not have been bound yet, without raising.
DropFromNamespace({"scratch"}, allow_missing=True)
__init__(names: set[str], allow_missing: bool = False) -> None

Bases: Effect

Insert source into the proposed REPL code, before it runs.

Valid at REPLExecEnter only — the “edit the proposal” stage, alongside AddToNamespace / DropFromNamespace (which edit the namespace, not the code). The LLM-message twin is AddMessages.

The offset is a character position in the ORIGINAL proposed code (REPLExecEnter’s code), so composition is order-independent — every effect names a position in the code the hook saw, not in the post-edit string. Two inserts at the same offset both apply, in hook order; an insert whose offset falls inside a DeleteCode range still inserts (new content survives a delete — this is how a hook replaces a span: delete it and insert at the same offset).

A code edit is observable through the events — REPLExecEnter carries the original proposal and REPLExecSend the committed (edited) code — but the agent’s __history__ records the LLM’s raw response, not the parsed/edited code, so the edit is not reflected there.

Attributes

  • text (str) — The source to insert.
  • at (int) — Character offset to insert before, in [0, len] of the original code; a negative offset counts from the end (-1 = before the last character), matching list semantics. An out-of-range offset raises CodeEditOffsetError.
__init__(text: str, at: int) -> None

Bases: Effect

Delete a character range from the proposed REPL code, before it runs.

Valid at REPLExecEnter only — the “edit the proposal” stage. The LLM-message twin is DropMessages.

The range [start, end) is resolved against the ORIGINAL proposed code’s offsets, so composition is order-independent. Overlapping ranges from multiple hooks union: each resolves to the set of character positions it covers, and the sets union exactly as DropMessages unions its indices — so no two deletes ever conflict.

Attributes

  • start (int) — First offset to delete (inclusive). Negative counts from the end.
  • end (int) — Offset one past the last character to delete (exclusive). Negative counts from the end; start == end deletes nothing. Both offsets lie in [0, len] of the original code and start <= end after resolution, else CodeEditOffsetError is raised.
__init__(start: int, end: int) -> None

Bases: Effect

Drop messages by index from the list sent to the model.

Valid at LLMQueryEnter only. indices are positions into the message list as seen on that event. Indices follow list semantics: a negative index counts from the end, and an out-of-range one raises MessageEditIndexError.

Composition: multiple drops compose by union of their indices, so the result is independent of hook order and no hook can corrupt another’s view — hooks only mark positions, and the message list is never mutated mid-composition.

Attributes

  • indices (set[int]) — Positions to drop from the message list.
  • persistent (bool) — False (default) applies the drop to this turn’s message list only; True makes the drop survive into later turns.
__init__(indices: set[int], persistent: bool = False) -> None

Bases: Effect

Insert messages into the conversation before an LLM query.

Valid at LLMQueryEnter only. Messages are inserted before slot index of the list as seen on that event; omitting index appends. An explicit out-of-range index raises MessageEditIndexError.

Composition is a pure function of the set of adds plus hook order: adds at distinct slots are independent, and adds landing in the same slot apply in the fold’s order: persistent adds first, then this turn’s transient ones, each in hook order. Identical adds from two hooks both appear; they are not coalesced, and adjacent same-role adds are not merged.

Attributes

  • messages (list[dict[str, Any]]) — The messages to insert, each an OpenAI-shaped mapping — {"role": ..., "content": ...} — plus any extra keys the configured provider accepts.
  • index (int | None) — Slot to insert before; None (default) appends. Negative counts from the end.
  • persistent (bool) — False (default) applies the add to this turn’s message list only; True makes the add survive into later turns.
__init__(messages: list[dict[str, Any]], index: int | None = None, persistent: bool = False) -> None

Bases: Effect

Supply a pre-computed LLM response, skipping the API call.

Valid at LLMQuerySend only — the supplier sees the committed post-edit message list. The content, token counts, and cost are used exactly as if they came from a live call, including cost tracking and budget enforcement — the query completes normally, so LLMQueryComplete and LLMQueryExit still fire.

Composition: identical overrides compose to one; two distinct overrides raise LLMResponseConflictError.

The fields mirror LLMResponse one-to-one — the supplier constructs a whole response, so each field is a direct value (None means the constructed response carries None there, not “keep”, since a supply has no original). extra defaults to an empty dict.

Attributes

  • content (str | None) — The response text, or None.
  • prompt_tokens (int | None) — Input token count to record, if known.
  • completion_tokens (int | None) — Output token count to record, if known.
  • cached_tokens (int | None) — Cached-input token count (subset of prompt_tokens), if known.
  • cost_usd (float | None) — Cost in US dollars to record for this call, if known.
  • extra (dict[str, Any] | None) — Provider-specific metrics (e.g. reasoning_tokens); None ⇒ empty dict.
  • raw_response (Any) — The raw provider payload a protocol may read (tool calls / finish reason).
  • tokens (TurnRecord | None) — Per-turn token record for a token-native backend, if any.
__init__(content: str | None, prompt_tokens: int | None = None, completion_tokens: int | None = None, cached_tokens: int | None = None, cost_usd: float | None = None, extra: dict[str, Any] | None = None, raw_response: Any = None, tokens: TurnRecord | None = None) -> None

Bases: Effect

Transform the LLM response after the call returned, before the agent acts on it.

Valid at LLMQueryComplete only — the response-transform boundary, the LLM-query twin of ModifyExecResult at REPLExecComplete. The transform is authoritative: the modified response is what the agent parses into its next REPL turn and what LLMQueryExit observers and cost accounting (BudgetPool) see — so a content rewrite changes the agent’s behavior, not just the record.

A partial override over LLMResponse’s full field set: each field defaults to UNSET meaning “leave the original’s value untouched”; any other value — including None — replaces that field. The UNSET sentinel (not None) marks “keep” precisely because None is a legitimate value for content / raw_response / tokens (a refusal has content is None), so this effect can set them to None. A field left UNSET is preserved from the original via dataclasses.replace — so a content rewrite keeps the real provider payload, tokens, and cost intact, and a re-price keeps the content.

Composition: field-wise merge. Multiple effects compose by taking, for each field, whichever value is not UNSET; two effects setting the same field to different values raise LLMResponseConflictError (identical values coalesce). This is order-independent — a content-redacting hook and a re-pricing hook compose cleanly because they touch disjoint fields. A Abort supersedes the whole merge.

Attributes

  • content (str | None | UnsetType) — Replacement response text (UNSET = keep; None sets a null completion).
  • prompt_tokens (int | None | UnsetType) — Replacement input token count (UNSET = keep).
  • completion_tokens (int | None | UnsetType) — Replacement output token count (UNSET = keep).
  • cached_tokens (int | None | UnsetType) — Replacement cached-input token count (UNSET = keep).
  • cost_usd (float | None | UnsetType) — Replacement cost in US dollars (UNSET = keep). Re-prices the cost booked at LLMQueryExit, including for a turn the backend priced at None — whether or not it promised a cost via can_report_cost. The one turn it cannot re-price is one that never runs: a BudgetPool carrying a cost_budget aborts pre-flight when the backend says up front it cannot report a cost.
  • extra (dict[str, Any] | UnsetType) — Replacement provider-metrics dict (UNSET = keep; replaces wholesale).
  • raw_response (Any) — Replacement raw provider payload (UNSET = keep; None clears it).
  • tokens (TurnRecord | None | UnsetType) — Replacement per-turn token record (UNSET = keep; None clears it).
__init__(content: str | None | UnsetType = UNSET, prompt_tokens: int | None | UnsetType = UNSET, completion_tokens: int | None | UnsetType = UNSET, cached_tokens: int | None | UnsetType = UNSET, cost_usd: float | None | UnsetType = UNSET, extra: dict[str, Any] | UnsetType = UNSET, raw_response: Any = UNSET, tokens: TurnRecord | None | UnsetType = UNSET) -> None