Struct ToolCtx
pub struct ToolCtx { /* private fields */ }Expand description
What a tool sees of the run it executes in.
Owned and cheap to clone (the runtime’s Ctx is borrowed mutably while a
step runs, so a tool cannot hold it).
Implementations§
§impl ToolCtx
impl ToolCtx
pub fn with_events(self, events: impl IntoIterator<Item = EventSpec>) -> ToolCtx
pub fn with_events(self, events: impl IntoIterator<Item = EventSpec>) -> ToolCtx
Declare events on this context, with a budget of its own: for a context made outside a run
(a test of a tool that emits). The agent loop declares what the tool’s own
Tool::events and the agent say. Read what the call emitted with
emitted_events.
pub fn emit_event(&self, name: &str, data: Value) -> Result<(), EmitError>
pub fn emit_event(&self, name: &str, data: Value) -> Result<(), EmitError>
Emit the custom event name with data (ADR 0050, decision 6).
The event must be declared by this tool (Tool::events) or by the agent; data is scrubbed
like the rest of the call’s output and may serialize to at most 4 KiB; a call emits at most 16
events and a transition at most 256. An event that is refused is not recorded and is never
sent. An accepted one is recorded with the call’s result, and delivered from the record
after the step: to observers that subscribe to it, and, if it is declared for clients, to
them as a RunEvent::Custom. A replay that finds the step recorded delivers it again with the
same key and does not run the tool.
§Errors
EmitError, whose class is Invalid.
pub fn emitted_events(&self) -> Vec<RecordedEvent>
pub fn emitted_events(&self) -> Vec<RecordedEvent>
The events the call has emitted so far, in order (what the step will record).
pub fn with_image_limits(self, limits: ImageLimits) -> ToolCtx
pub fn with_image_limits(self, limits: ImageLimits) -> ToolCtx
Say that the model of the call sees images within limits, with an empty history and no room
to count in a run’s state: for a context made outside a run (a test of a tool that offers
images, keep_image). The agent loop does the same for every call, from
the model’s own word and what the history holds.
pub fn sees_images(&self) -> bool
pub fn sees_images(&self) -> bool
Whether the model of this run can see images at all: a tool that would read or fetch an image only to have it replaced by a line may say so instead, and not read it.
pub fn sees_images_from(&self, origin: ImageOrigin) -> bool
pub fn sees_images_from(&self, origin: ImageOrigin) -> bool
Whether the model sees images that come from origin: it sees them and the deployment
sends that source.
pub fn with_scrub(
self,
scrub: impl Fn(&str) -> String + Send + Sync + 'static,
) -> ToolCtx
pub fn with_scrub( self, scrub: impl Fn(&str) -> String + Send + Sync + 'static, ) -> ToolCtx
Give the call a function that scrubs secrets out of a text. A layer that scrubs the results
of the tools it wraps (the coder’s Redacting) sets it, so a tool can scrub before it
cuts, truncates, hashes or splits a text it makes: a secret cut in half is no longer a secret
the scrubber recognises, and the half that is left is durable. See scrub.
pub fn with_scrub_longest(
self,
scrub: impl Fn(&str) -> String + Send + Sync + 'static,
longest: impl Fn() -> usize + Send + Sync + 'static,
) -> ToolCtx
pub fn with_scrub_longest( self, scrub: impl Fn(&str) -> String + Send + Sync + 'static, longest: impl Fn() -> usize + Send + Sync + 'static, ) -> ToolCtx
with_scrub, and a function that says how long the longest value the
scrubber replaces is, in bytes. A tool that cuts a text it may only half have (the first part
of a result) keeps back scrub_margin bytes of its end: a scrubber
that holds a value longer than SCRUB_OVERLAP must say so here, and
one that does not is taken to hold none.
pub fn scrub_margin(&self) -> usize
pub fn scrub_margin(&self) -> usize
How many bytes at the open end of a cut text may be the start of a secret:
SCRUB_OVERLAP, or the longest value the scrubber says it holds when
that is more.
pub fn scrub(&self, text: &str) -> String
pub fn scrub(&self, text: &str) -> String
text with its secrets replaced, as the layer around this tool would; text itself when
there is no such layer.
The rule for a tool that shortens a text it puts in its result (a label cut to a limit, a line cut to a width): call this on the whole text first, then shorten what it returns. The layer scrubs the finished result as well, but only a secret still whole in it.
pub fn with_plan(self, plan: impl Into<Option<Plan>>) -> ToolCtx
pub fn with_plan(self, plan: impl Into<Option<Plan>>) -> ToolCtx
Give the call the plan the conversation has when it starts: what plan
answers. The agent does it for every call; a test of a plan tool does it to say what the
plan was.
pub fn with_loaded(self, loaded: impl Into<Arc<[Loaded]>>) -> ToolCtx
pub fn with_loaded(self, loaded: impl Into<Arc<[Loaded]>>) -> ToolCtx
Say what the run has loaded as this call starts (loaded); the agent loop
does it for every call.
pub fn with_removed_tools(self, removed: impl Into<Arc<[String]>>) -> ToolCtx
pub fn with_removed_tools(self, removed: impl Into<Arc<[String]>>) -> ToolCtx
Say which loaded tools a request did not carry
(Conversation::removed_tools); the agent loop does
it for every call.
pub fn with_task(self, task: Option<Arc<str>>) -> ToolCtx
pub fn with_task(self, task: Option<Arc<str>>) -> ToolCtx
Say what the run was started with (task); the agent loop does it for every
call.
pub fn plan(&self) -> Option<&Plan>
pub fn plan(&self) -> Option<&Plan>
The conversation’s plan as this call starts: the one a tool before it in the same turn left,
since calls run one after the other. None while there is none. Return the new plan with
ToolOutput::with_plan; this value is a copy, and changing nothing here changes nothing
there.
pub fn loaded(&self) -> &[Loaded]
pub fn loaded(&self) -> &[Loaded]
What the run has loaded as this call starts, in the order it loaded it
(Conversation::loaded): the whole list, not a change. A
loader reads it to refuse a second load, and a source that withholds a group’s tools reads
SourceCtx::loaded instead.
pub fn removed_tools(&self) -> &[String]
pub fn removed_tools(&self) -> &[String]
The loaded tools the run no longer holds
(Conversation::removed_tools): a member its group
shrank out of, or a task-loaded member the tier hid. A call to one is refused, and a loader
does not offer it again.
pub fn task(&self) -> Option<&str>
pub fn task(&self) -> Option<&str>
The words the run was started with (Conversation::task):
the first part of its first message, the same text at every call of the run.
pub fn kept_left(&self) -> usize
pub fn kept_left(&self) -> usize
The bytes a tool may still hand back in ToolOutput::kept: MAX_RUN_KEPT_BYTES
less what the run keeps already (none for a detached context).
pub fn kept_text(&self, id: &str) -> Option<&str>
pub fn kept_text(&self, id: &str) -> Option<&str>
The text the run keeps under the output id id in its own state.
pub fn with_files_left(self, bytes: u64) -> ToolCtx
pub fn with_files_left(self, bytes: u64) -> ToolCtx
Say how many bytes of files the run may still share: what files_left
answers. The agent loop does it for every call.
pub fn files_left(&self) -> u64
pub fn files_left(&self) -> u64
The bytes of files the run may still share: MAX_RUN_FILE_BYTES (6 MiB) less what it kept
so far, as the turn’s call began (the whole cap for a detached context). The loop refuses a
file of a result that would go over, but only after the result is journaled; a tool that
returns files it did not choose (an MCP server’s images, a remote agent’s file parts) keeps
its result within this, so that one journal entry stays within the run’s cap.
pub fn spend_files(&self, bytes: u64)
pub fn spend_files(&self, bytes: u64)
bytes of the room for files are taken: call it when the call decides to return files of
that size. The calls of one segment that run together share the room, so a call that starts
after this one reads a smaller files_left. The loop still refuses, when
the results are applied, a file that would go over the run’s cap.
pub fn try_spend_files(&self, bytes: u64) -> bool
pub fn try_spend_files(&self, bytes: u64) -> bool
Take bytes of the room for files if they fit, at once: false (and nothing taken) when
fewer are left. The calls of one segment share the room, so of two calls that both read
enough room before either took it, only one gets it.
pub fn spend_files_of(&self, output: &mut ToolOutput)
pub fn spend_files_of(&self, output: &mut ToolOutput)
Take the room for the files of output the moment the tool has them, file by file
(try_spend_files): a file that does not fit is dropped from the
output, which becomes an error result that says so, in the words the loop uses when it
refuses a file. What a tool that returns files it did not choose (an MCP server’s, a remote
agent’s) calls with its result, so that two calls that run together never journal more than
the run may share.
pub fn note(&self) -> Option<&ToolNote>
pub fn note(&self) -> Option<&ToolNote>
What the source that offered this tool said about it when it listed it: whether the system
behind the source reports each call as a step itself, and how long a call may run. None
for the agent’s own tools and when the listing said nothing.
pub fn under_step(self, parent: impl Into<String>) -> ToolCtx
pub fn under_step(self, parent: impl Into<String>) -> ToolCtx
Say that this call runs under the step parent (reported earlier): what
parent_step_id answers. For a call made on behalf of a step the caller
reported; a call of the model’s own, from the agent loop, has none.
pub fn parent_step_id(&self) -> Option<&str>
pub fn parent_step_id(&self) -> Option<&str>
The step this call runs under, if one was reported for it (under_step):
None for a call the model asked for, which is at the top.
pub fn detached(
tool_name: impl Into<String>,
call_id: impl Into<String>,
sink: Arc<dyn EventSink>,
) -> ToolCtx
pub fn detached( tool_name: impl Into<String>, call_id: impl Into<String>, sink: Arc<dyn EventSink>, ) -> ToolCtx
A context detached from any run, for unit-testing a tool: a fresh run
id, attempt 0, no conversation, and events sent to sink.
pub fn with_root_run(self, root: RunId) -> ToolCtx
pub fn with_root_run(self, root: RunId) -> ToolCtx
Make the context the one of a child run that works for root, as a run started with
start_child is. The workspace it reads is the root’s too, unless
with_workspace_run says otherwise (a session’s header does).
pub fn with_workspace_run(self, run: RunId) -> ToolCtx
pub fn with_workspace_run(self, run: RunId) -> ToolCtx
Say which run’s workspace this run reads, when it is not
root_run_id: the run a session’s header names (ADR 0045 slice 7), so
that a round a person started works in the worktree of the task it was opened in. The agent
does it for the calls of a round whose header says one; a test may set it on a detached
context.
pub fn model_run_id(&self) -> RunId
pub fn model_run_id(&self) -> RunId
The run this run’s model calls name (ModelRequest::run,
ADR 0067), which an injector in front of the model looks the run’s credential up by: the
root_run_id of a task, the root a session’s round names. A child this
call starts, and a session it opens or sends to, name it too.
pub fn with_context(self, context: Map<String, Value>) -> ToolCtx
pub fn with_context(self, context: Map<String, Value>) -> ToolCtx
Give the tool under test the inbound context of a run
(Conversation::context), as it would read it with
context in a real one.
pub fn with_state<T>(self, value: Arc<T>) -> ToolCtx
pub fn with_state<T>(self, value: Arc<T>) -> ToolCtx
Make value available to the tool under test through
state, as
LlmAgentBuilder::state does for a
real run.
pub fn with_cancel_token(self, cancel: CancelToken) -> ToolCtx
pub fn with_cancel_token(self, cancel: CancelToken) -> ToolCtx
Replace the cancellation token, so a test can fire it
([CancelToken::cancel]) and check that the tool stops. Contexts
built by the agent already carry the run’s own token.
pub fn run_id(&self) -> RunId
pub fn run_id(&self) -> RunId
The run this call belongs to.
pub fn root_run_id(&self) -> RunId
pub fn root_run_id(&self) -> RunId
The run whose work this one serves: the top of the chain of parents when this run is a child
started with start_child (a subagent), this run itself when it is
nobody’s child. A tool that keeps something for the whole task, such as a workspace or a
budget, keys it by this id, so that a subagent shares what its root run made.
The id travels in the child’s first message and its stored state, so it is the same after a restart and costs no store read.
pub fn workspace_run_id(&self) -> RunId
pub fn workspace_run_id(&self) -> RunId
The run whose workspace this run works in: what a tool that keeps a worktree, an environment
session or a scratch project keys by. It is root_run_id unless the
run’s session names another (SessionHeader::workspace),
which is how a round a person started reads the repository of the task it was opened in
(ADR 0045 slice 7).
The notes of the task — the checks, the budgets, the gates, the repositories a person
agreed to — stay on root_run_id: a helper writes none of them.
pub fn conversation_id(&self) -> Option<&str>
pub fn conversation_id(&self) -> Option<&str>
The conversation the run belongs to, if any.
pub fn attempt(&self) -> u32
pub fn attempt(&self) -> u32
How many earlier tries of the current transition failed transiently
(0 on the first try). See Ctx::attempt.
pub fn call_id(&self) -> &str
pub fn call_id(&self) -> &str
The model’s identifier for this call (ToolCall::id); stable across
retries and replays, so usable as an idempotency key.
pub fn child_run_id(&self) -> RunId
pub fn child_run_id(&self) -> RunId
The id of the child run this call starts: [adam_runtime::child_run_id] of this run and
call_id. The same on every replay of the call, so it is the id to pass to
Runtime::start_child and to ToolError::AwaitRun.
pub async fn start_child(
&self,
agent: &str,
message: &str,
) -> Result<RunId, ToolError>
pub async fn start_child( &self, agent: &str, message: &str, ) -> Result<RunId, ToolError>
Start agent as a child run of this run, with message as its first user message, under
child_run_id, and return that id: what to put in
ToolError::AwaitRun. The child starts on the runtime that steps this run, so the agent
must be registered on it (as an agent or a starter).
The first message also names the run and the step the child works under, the root run’s
(root_run_id, and this call’s own step when this run is the root): the
child reports its model calls to the root’s task under that step (usage/v1), and hands both
down to its own children.
Idempotent: a call that runs again (a replay, a retry) finds the child it started. One child per call: starting a second one from the same call would find the first.
§Errors
ToolError::Permanent for an agent the runtime does not know, and for a context made by
detached, which belongs to no runtime; ToolError::Transient for a
store failure worth retrying.
pub async fn start_child_within(
&self,
agent: &str,
message: &str,
within: Option<Duration>,
) -> Result<RunId, ToolError>
pub async fn start_child_within( &self, agent: &str, message: &str, within: Option<Duration>, ) -> Result<RunId, ToolError>
start_child for a child that must finish within within (None: no
limit). The runtime stores the deadline from its own clock; a child past it is failed with
cancelled: time limit: the run did not finish within N min, which the parent reads as the
child’s error (“the run failed: …”). See Runtime::start_child_within.
§Errors
As start_child.
pub fn context(&self, key: &str) -> Option<&Value>
pub fn context(&self, key: &str) -> Option<&Value>
A value of the run’s inbound context (Conversation::context):
what the caller said about itself in the messages it sent, under the key it used. The
context is the same for every call of one model turn and changes only when a message
arrives, so a tool that reads it is repeatable.
Treat a value as input from whoever sent the message, and a secret in it (a token) as a secret: do not put it in a result the model reads.
pub fn context_map(&self) -> &Map<String, Value>
pub fn context_map(&self) -> &Map<String, Value>
The whole inbound context, for a tool that wants more than one key.
pub fn require_state<T>(&self) -> Result<State<T>, ToolError>
pub fn require_state<T>(&self) -> Result<State<T>, ToolError>
Like state, but a missing value is a
ToolError::Permanent naming the type, for a tool that cannot go on
without it. A tool that lists the type in
Tool::required_state can only see this error when the agent was
built with build instead of
try_build.
pub fn is_cancelled(&self) -> bool
pub fn is_cancelled(&self) -> bool
Whether the run was cancelled (or finished by someone else) while this
call runs. See ToolCtx::cancelled.
pub async fn cancelled(&self)
pub async fn cancelled(&self)
Resolves when the run is cancelled; never resolves for a run that is
not. A tool with long-running work (a subprocess, a remote job, a
stream) select!s on it to stop early:
tokio::select! {
out = child.wait() => out,
() = ctx.cancelled() => { child.kill().await?; Err(ToolError::Permanent("cancelled".into())) }
}Cancelling commits the run as Failed, so whatever the tool returns
afterwards is dropped: stop fast, clean up, and return anything (an
Err(ToolError::Permanent(..)) reads best in logs). Nothing here
aborts the call; a tool that ignores the signal simply runs to its end.
See [adam_runtime::CancelToken].
pub fn cancel_token(&self) -> CancelToken
pub fn cancel_token(&self) -> CancelToken
The token behind cancelled, for handing to code
that takes one (for example a spawned task).
pub async fn emit_progress(&self, message: impl Into<String>)
pub async fn emit_progress(&self, message: impl Into<String>)
Say what the call is doing now: an update of its own step (step_id),
whose detail is message. Best effort and not durable, like every event. A client that
asked for steps gets a bounded number of them (the orchestration layer keeps a few updates
per step); one that did not gets message as a line of text, as it always did.
pub fn report_sandbox(&self, usage: &SandboxUsage)
pub fn report_sandbox(&self, usage: &SandboxUsage)
Report that this call’s commands ran in a sandbox (or that the run’s environment was asked for): the usage is added to what the call has reported so far.
The loop takes it when the call returns and adds it to the run’s
sandbox_usage, in the same commit as the result: a
result it journaled carries it (ToolOutput::sandbox), so it is counted once and kept
across a restart. A call that returns ToolError::Permanent (a cancel, for one) is counted
too; one that fails with ToolError::Transient is tried again and counts only the try that
is kept.
pub fn reported_sandbox(&self) -> SandboxUsage
pub fn reported_sandbox(&self) -> SandboxUsage
What the call has reported with report_sandbox so far.
pub fn step_id(&self) -> &str
pub fn step_id(&self) -> &str
The id of this call’s own step: tool:<call id>. The agent reports its start before the
tool runs and its end after, so a tool that wants to say more about its work reports steps
that run under it (report_step).
pub async fn report_step(&self, step: StepEvent)
pub async fn report_step(&self, step: StepEvent)
Report a step of the work this call does: a command it ran, a tool of the agent it drove.
It runs under this call’s step unless step says it runs under another one
(StepEvent::under) the call reported before. The first report of an id starts the step,
the ones after update it, and a report whose state ends it ends it; a step the call leaves
open when it returns is closed by whoever shows the tree.
Ids must be unique within the run: put the call id in them (acp:<call id>:<n>). Best effort
and not durable, like every event.
Trait Implementations§
Auto Trait Implementations§
impl !RefUnwindSafe for ToolCtx
impl !UnwindSafe for ToolCtx
impl Freeze for ToolCtx
impl Send for ToolCtx
impl Sync for ToolCtx
impl Unpin for ToolCtx
impl UnsafeUnpin for ToolCtx
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<T> Instrument for T
impl<T> Instrument for T
§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request§impl<L> LayerExt<L> for L
impl<L> LayerExt<L> for L
§fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>where
L: Layer<S>,
Layered].