pub struct Runtime {
pub watcher_exit_path: Option<PathBuf>,
/* private fields */
}Fields§
§watcher_exit_path: Option<PathBuf>Path for watcher_exit tool to write handoff state (agent mode only)
Implementations§
Source§impl Runtime
impl Runtime
pub async fn new() -> Result<Self>
pub fn set_system_prompt(&mut self, prompt: String)
pub fn system_prompt(&self) -> Option<&str>
Sourcepub async fn effective_system_prompt(&self) -> Option<String>
pub async fn effective_system_prompt(&self) -> Option<String>
The system prompt that actually goes on the wire for the next
request: the configured base plus any builtin orchestration adapter
(see agent_core::prompt::builtin_orchestration_adapters) selected
by the current model identity, so the doctrine follows mid-session
model switches. Composition is skipped when:
- a typed prompt manifest is active — the manifest author owns the full stack;
- the runtime exposes no subagent tools (worker runtimes) — the doctrine would be unactionable noise;
- the model identity cannot be canonicalized — fail closed to the unmodified base.
pub fn effective_prompt(&self) -> Option<&PromptStack>
pub fn prompt_generation(&self) -> u64
pub fn retain_prompt_reload_source( &mut self, manifest: PathBuf, context: SelectionContext, user_module: Option<PromptModule>, delegation_policy_digest: Option<String>, )
Sourcepub fn reload_prompt(&mut self) -> Result<u64, PromptError>
pub fn reload_prompt(&mut self) -> Result<u64, PromptError>
Recompile retained manifest inputs, validate, then atomically install the candidate.
Sourcepub fn apply_prompt_stack(
&mut self,
candidate: PromptStack,
) -> Result<u64, PromptError>
pub fn apply_prompt_stack( &mut self, candidate: PromptStack, ) -> Result<u64, PromptError>
Atomically validate and install a compiled stack. Failed validation leaves all state intact.
pub fn prompt_inspection_json(&self) -> Option<String>
Sourcepub fn install_mcp_runtime(&mut self, manager: Arc<McpRuntimeManager>)
pub fn install_mcp_runtime(&mut self, manager: Arc<McpRuntimeManager>)
Install the shared exact MCP lease manager (Task 19, engine boot). Also mints ONE durable session-scope guard for the runtime’s tool session, shared by every clone and stream; only the LAST owner’s drop terminates leases.
Sourcepub fn set_turn_budget(&mut self, budget: TurnBudget)
pub fn set_turn_budget(&mut self, budget: TurnBudget)
Set this runtime’s per-turn budget (Task 23). The engine resolves role + typed config at boot; subagent/watcher constructions pass their role’s budget explicitly.
Sourcepub fn turn_budget(&self) -> &TurnBudget
pub fn turn_budget(&self) -> &TurnBudget
The currently configured per-turn budget.
Sourcepub fn install_extension_runtime(
&mut self,
manager: Arc<ExtensionRuntimeManager>,
)
pub fn install_extension_runtime( &mut self, manager: Arc<ExtensionRuntimeManager>, )
Install the shared exact EXTENSION lease manager (Task 20, engine boot). Also mints ONE durable session-scope guard for the runtime’s tool session, shared by every clone and stream; only the LAST owner’s drop terminates leases.
pub fn install_orchestration(&mut self, runtime: Arc<OrchestrationRuntime>)
Sourcepub fn install_worker_orchestration(
&mut self,
runtime: Arc<OrchestrationRuntime>,
)
pub fn install_worker_orchestration( &mut self, runtime: Arc<OrchestrationRuntime>, )
A runtime spawned for a worker shares only this session’s bounded dispatch/tree authority. It must not replay process-global favorite models: doing so would turn a child construction into a fresh grant source. The child can dispatch only identities already authorized by this installed session policy.
pub fn set_delegation_parent(&mut self, parent: Option<String>)
pub fn orchestration(&self) -> Option<&Arc<OrchestrationRuntime>>
Sourcepub fn grant_worker_model(&self, model: &str) -> Result<(), String>
pub fn grant_worker_model(&self, model: &str) -> Result<(), String>
Extends the live session delegation policy with one explicitly user-trusted worker model (e.g. favorited mid-session in the models picker). Mid-session trust grants were always meant to be honored; the policy snapshot is not pinned against user decisions.
Sourcepub fn set_model(&mut self, model: String) -> Option<ReasoningClamp>
pub fn set_model(&mut self, model: String) -> Option<ReasoningClamp>
Infallible model change. Returns the reasoning clamp applied (if any)
when the current level is not supported by the new model; errors from
try_set_model are swallowed (model left unchanged).
Sourcepub fn try_set_model(
&mut self,
model: String,
) -> Result<Option<ReasoningClamp>, String>
pub fn try_set_model( &mut self, model: String, ) -> Result<Option<ReasoningClamp>, String>
Apply a model change while preserving orchestration lifecycle invariants.
Returns an error instead of mutating either model or policy when active
workers still require collection/reconciliation or when the replacement
foreground cannot produce a trusted manifestless policy snapshot.
On success, returns Some(ReasoningClamp) when an explicit reasoning
level had to be substituted because the new model does not support it.
pub fn set_tools(&mut self, tools: ToolRegistry)
pub fn subagent_registry(&self) -> &Arc<Mutex<SubagentRegistry>> ⓘ
pub fn event_queue(&self) -> &Arc<EventQueue> ⓘ
Sourcepub fn host_tool_session_id(&self) -> &SessionId
pub fn host_tool_session_id(&self) -> &SessionId
Runtime-scoped tool-session identity used by the stream execution
gate (Task 16). Shared by clones (which share the tool registry);
fresh per independently constructed Runtime.
Get a shared reference to the tool registry (for MCP lazy loading).
pub fn model(&self) -> &str
pub fn http_client(&self) -> &Client
pub fn set_thinking_budget(&mut self, budget: u32)
Sourcepub fn set_reasoning_level(&mut self, level: ReasoningLevel)
pub fn set_reasoning_level(&mut self, level: ReasoningLevel)
Set the named reasoning level (config/restore path). Updates
thinking_budget from the level’s canonical budget when one exists;
for Max/Ultra (no numeric budget), leaves thinking_budget unchanged.
Marks explicit_reasoning = false — use set_reasoning_level_explicit
for user commands and settings.
Sourcepub fn set_reasoning_level_explicit(&mut self, level: ReasoningLevel)
pub fn set_reasoning_level_explicit(&mut self, level: ReasoningLevel)
Set the named reasoning level as an explicit user choice (slash
commands, settings panel). Identical to set_reasoning_level but sets
explicit_reasoning = true so that a subsequent set_model call does
not overwrite the level with the new model’s default.
Sourcepub fn restore_session_reasoning(
&mut self,
thinking_level: &str,
) -> Option<ReasoningClamp>
pub fn restore_session_reasoning( &mut self, thinking_level: &str, ) -> Option<ReasoningClamp>
Restore a saved session’s thinking_level string as an explicit user
choice, then clamp it against the current model. Call after
set_model(session.model): re-applying the saved level would otherwise
undo the clamp set_model performed (old grok+xhigh session files).
Returns the clamp applied, if any, so callers can surface it.
Sourcepub fn set_thinking_budget_explicit(&mut self, budget: u32)
pub fn set_thinking_budget_explicit(&mut self, budget: u32)
Set a custom numeric thinking budget as an explicit user choice
(e.g. /thinking 8192). Retains the exact budget in thinking_budget
while syncing named_level to the nearest named level for display.
Sets explicit_reasoning = true.
Sourcepub fn is_reasoning_explicit(&self) -> bool
pub fn is_reasoning_explicit(&self) -> bool
Expose the explicit_reasoning provenance flag (test/introspection).
Sourcepub fn thinking_budget_raw(&self) -> u32
pub fn thinking_budget_raw(&self) -> u32
Raw thinking budget value (for testing and legacy request building).
Sourcepub fn set_reasoning_level_checked(
&mut self,
level: ReasoningLevel,
) -> Result<(), String>
pub fn set_reasoning_level_checked( &mut self, level: ReasoningLevel, ) -> Result<(), String>
Validate level against the current model’s capability metadata via
the shared per-provider validator (cache then exact static tables),
then apply it. Returns Err(user-facing message) and leaves runtime
state unchanged if the level is unsupported.
Sourcepub fn set_thinking_budget_checked(&mut self, budget: u32) -> Result<(), String>
pub fn set_thinking_budget_checked(&mut self, budget: u32) -> Result<(), String>
Validate then apply a custom numeric thinking budget (/thinking <N>).
The budget’s derived ReasoningLevel runs through the same exact-model
mutation validator as named levels (Anthropic fixed-budget models pass:
derived levels never exceed XHigh and thinking-capable descriptors
accept them). On Ok the exact budget is retained — never downgraded
to a named-level canonical budget. On Err state is unchanged.
pub fn reasoning_level(&self) -> ReasoningLevel
pub fn set_compaction_model(&mut self, model: Option<String>)
Sourcepub fn set_compaction_mode(&mut self, mode: CompactionMode)
pub fn set_compaction_mode(&mut self, mode: CompactionMode)
Set where compaction summarization runs (spec §9.4).
Sourcepub fn set_compaction_exclusions(&mut self, exclude: Vec<ContentClass>)
pub fn set_compaction_exclusions(&mut self, exclude: Vec<ContentClass>)
Set the content classes withheld from remote compaction disclosure.
Sourcepub fn remote_summarization_attempts(&self) -> u64
pub fn remote_summarization_attempts(&self) -> u64
Number of times the remote-summarization transport seam was entered (CP-12 M3). Local-only compaction must leave this at zero.
Sourcepub fn compaction_policy(&self) -> DisclosurePolicy
pub fn compaction_policy(&self) -> DisclosurePolicy
The session’s compaction disclosure policy (spec §9.4) — consumed by
runtime::compaction for both the preview and the dispatch path.
pub fn set_context_window(&mut self, window: Option<u64>)
Sourcepub fn compaction_model(&self) -> &str
pub fn compaction_model(&self) -> &str
Effective context window for the current model — user override if set,
otherwise the model’s native window from models::context_window_for_model.
pub fn context_window(&self) -> u64
Sourcepub async fn assess_context(
&self,
messages: &[SharedMessage],
) -> ContextAssessment
pub async fn assess_context( &self, messages: &[SharedMessage], ) -> ContextAssessment
Task 29 (spec §9.1): the ONE request-aware context assessment every frontend consumes on its compaction trigger path. Reads the segments the next request will actually carry — the effective system prompt, the exposed tool-schema set, the supplied history — and the runtime’s configured reserves (thinking budget, tool-result cap, model output reserve, provider window with the documented safety margin).
Skill bodies that reach the request do so through the system prompt
or history today, so they are already accounted there; the skill lane
is fed once loaders hand the engine distinct segments. The memory
lane is live as of task A7: a validated recall segment held for the
current turn is charged to ContextBreakdown::memory_tokens (spec
§10.3 — memory competes for budget headroom only, never reserves).
Sourcepub fn memory_recall_why(&self) -> Option<RecallTurnMetadata>
pub fn memory_recall_why(&self) -> Option<RecallTurnMetadata>
Task B4 (spec §10.4): explainability metadata retained for the
current turn’s accepted recall, if any. Metadata only — selected IDs,
source classes, rank reasons, byte/token accounting, latency, and
withheld/skipped counts; never memory content. Rendered for
/memory why by memory_context::render_recall_why (task B5).
Sourcepub fn apply_config(&mut self, config: &SynapsConfig)
pub fn apply_config(&mut self, config: &SynapsConfig)
Apply a parsed config file to this runtime (model, thinking budget, etc.)
Sourcepub fn apply_auth_config(&mut self, config: &SynapsConfig)
pub fn apply_auth_config(&mut self, config: &SynapsConfig)
Apply only the credential-source portion of config. Used by subagent
spawns that build a fresh Runtime::new() (which defaults to Local) and
must inherit the user’s Remote/broker setup. (#158 A3)
A6: invalidates the token cache if the source/endpoint changed.
A2: scrubs AuthState when Remote so no local auth.json credential is
used or held (invariant 1).
pub fn thinking_budget(&self) -> u32
pub fn max_tool_output(&self) -> usize
pub fn bash_timeout(&self) -> u64
pub fn bash_max_timeout(&self) -> u64
pub fn subagent_timeout(&self) -> u64
pub fn api_retries(&self) -> u32
pub fn set_max_tool_output(&mut self, v: usize)
pub fn set_bash_timeout(&mut self, v: u64)
pub fn set_bash_max_timeout(&mut self, v: u64)
pub fn set_subagent_timeout(&mut self, v: u64)
pub fn set_api_retries(&mut self, v: u32)
pub fn telemetry_level(&self) -> TelemetryLevel
pub fn set_telemetry_level(&mut self, level: TelemetryLevel)
Sourcepub fn trace_context(&self) -> TraceContext
pub fn trace_context(&self) -> TraceContext
The session trace context handed to every request (cheap clone).
Sourcepub fn trace_arm_next(&self, with_content: bool)
pub fn trace_arm_next(&self, with_content: bool)
Arm tracing for exactly the next outgoing provider request
(/trace next; with_content adds the one-request redacted
content capture for /trace next content).
Sourcepub fn trace_status(&self) -> TraceStatusReport
pub fn trace_status(&self) -> TraceStatusReport
Metadata-only /trace status report: mode, persistence path,
counters. Never secrets or content. Also performs the opportunistic
expired-capture sweep (B2): status is a trace interaction, so stale
content-capture bundles are physically removed here too.
Sourcepub fn memory_context_status(&self) -> MemoryContextStatus
pub fn memory_context_status(&self) -> MemoryContextStatus
Typed /memory status snapshot — metadata-only, never spawns a
provider process (spec §7.2 “status does not spawn”).
Sourcepub fn memory_context_disable(&self) -> MemoryContextStatus
pub fn memory_context_disable(&self) -> MemoryContextStatus
Revoke this session’s memory context (/memory off). Always locally
allowed (spec §7.2); idempotent — disabling an already-off session
reports Off.
Task A6 revocation wiring: after the session state transition, the
extension runtime lease backing each bound provider is defensively
revoked through the SAME ExtensionRuntimeManager mechanism the
deferred tool/handler lifecycle uses (Self::install_extension_runtime
/ ExtensionSessionEndGuard). While Phase A never spawns, this is an
idempotent no-op; once Phase B routes real recall/capture calls under
this runtime’s tool session, disable reaps the provider child exactly.
Sourcepub fn memory_history_preview(
&self,
) -> Result<HistoryImportPreview, HistoryImportError>
pub fn memory_history_preview( &self, ) -> Result<HistoryImportPreview, HistoryImportError>
Return the history-import disclosure preview. This is D1’s production entry point: metadata is scanned, but session bodies and Axel are never opened. All frontends share this runtime implementation.
Sourcepub fn context_report(&self, history: Option<&[SharedMessage]>) -> ContextReport
pub fn context_report(&self, history: Option<&[SharedMessage]>) -> ContextReport
Structured /context report (Task 12): counts, byte lengths, cache
change/reuse estimates, and writer counters — never content.
history is the conversation owned by the calling surface (TUI /
headless); when it is not provided the history lines honestly read
unavailable rather than fabricating zeros. Loaded skills/memories
are session-surface state the runtime cannot enumerate, so they are
reported unavailable with that provenance.
Sourcepub fn telemetry_writer(&self) -> Option<TelemetryWriter>
pub fn telemetry_writer(&self) -> Option<TelemetryWriter>
The shared observability writer, when telemetry is enabled.
Sourcepub fn shutdown_observability(
&self,
timeout: Duration,
) -> Option<ShutdownOutcome>
pub fn shutdown_observability( &self, timeout: Duration, ) -> Option<ShutdownOutcome>
Bounded shutdown flush of the observability writer: stop intake,
drain until timeout, return typed stats (None when telemetry is
off). Sync and bounded — safe from shutdown paths that cannot await;
async callers should use Self::shutdown_observability_async.
Semantics (Task 11):
- telemetry
off→ no writer exists →None, a true no-op; - “flushed” means every queued record was appended into OS file
buffers (
write(2)returned) — deliberately nofsync, these are best-effort diagnostic logs; - on timeout the worker stays detached and keeps draining in the background; the caller logs metadata-only stats and continues — trace loss must never fail or abort a clean exit.
Sourcepub async fn shutdown_observability_async(
&self,
timeout: Duration,
) -> Option<ShutdownOutcome>
pub async fn shutdown_observability_async( &self, timeout: Duration, ) -> Option<ShutdownOutcome>
Async epilogue helper for every clean process/runtime exit path that
owns a Runtime (headless chat, TUI teardown, autonomous agent,
RPC/server graceful shutdown): clones the writer handle and runs the
bounded Self::shutdown_observability on the blocking pool, so an
executor thread is never parked. Same None/no-fsync/timeout
semantics as the sync variant. Idempotent — a second call finds the
intake already closed and returns immediately.
Note: the writer is shared across Runtime clones (subagents). Call
this only from the session owner’s exit epilogue, after in-flight
work has drained — cloned runtimes still serving requests would see
their subsequent records counted as drops.
pub fn cache_diagnostics(&self) -> bool
pub fn set_cache_diagnostics(&mut self, v: bool)
pub fn cache_ttl(&self) -> CacheTtl
Sourcepub fn set_cache_ttl(&mut self, ttl: CacheTtl)
pub fn set_cache_ttl(&mut self, ttl: CacheTtl)
Change the cache TTL strategy mid-session. The next request re-marks with the new TTL; the old prefix expires naturally (single-last strategy never prunes old markers, so no invalidation logic needed).
pub fn thinking_level(&self) -> &str
Sourcepub async fn refresh_if_needed(&self) -> Result<()>
pub async fn refresh_if_needed(&self) -> Result<()>
Check if the OAuth token is expired and refresh it if needed.
Sourcepub async fn compact_call(&self, messages: Vec<SharedMessage>) -> Result<String>
pub async fn compact_call(&self, messages: Vec<SharedMessage>) -> Result<String>
Make a simple non-streaming API call for compaction (no tools).
Uses a dedicated summarization system prompt (not the user’s), omits all tools, and returns the raw text response. Caller supplies the full message array including the serialized conversation.
Sourcepub async fn run_single(&self, prompt: &str) -> Result<String>
pub async fn run_single(&self, prompt: &str) -> Result<String>
Run a single prompt synchronously (non-streaming). Handles tool execution internally, looping until the model produces a final text response.
Sourcepub async fn run_stream(
&self,
prompt: String,
cancel: CancellationToken,
) -> Pin<Box<dyn Stream<Item = StreamEvent> + Send>>
pub async fn run_stream( &self, prompt: String, cancel: CancellationToken, ) -> Pin<Box<dyn Stream<Item = StreamEvent> + Send>>
Run a prompt as a cancellable stream of StreamEvents. Convenience wrapper
around [run_stream_with_messages] for single-turn usage.
Sourcepub async fn run_stream_with_messages(
&self,
messages: Vec<SharedMessage>,
cancel: CancellationToken,
steering_rx: Option<UnboundedReceiver<String>>,
secret_prompt: Option<SecretPromptHandle>,
auto_approve_confirms: bool,
) -> Pin<Box<dyn Stream<Item = StreamEvent> + Send>>
pub async fn run_stream_with_messages( &self, messages: Vec<SharedMessage>, cancel: CancellationToken, steering_rx: Option<UnboundedReceiver<String>>, secret_prompt: Option<SecretPromptHandle>, auto_approve_confirms: bool, ) -> Pin<Box<dyn Stream<Item = StreamEvent> + Send>>
Run a multi-turn conversation as a cancellable stream of StreamEvents.
This is the main entry point for chat UIs and agents. Handles tool execution,
API retries, and dynamic tool registration (MCP) internally.
Trait Implementations§
Auto Trait Implementations§
impl !RefUnwindSafe for Runtime
impl !UnwindSafe for Runtime
impl Freeze for Runtime
impl Send for Runtime
impl Sync for Runtime
impl Unpin for Runtime
impl UnsafeUnpin for Runtime
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,
Source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
Source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can
then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.Source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be
further downcast into Rc<ConcreteType> where ConcreteType implements Trait.Source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &Any’s vtable from &Trait’s.Source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot
generate &mut Any’s vtable from &mut Trait’s.