greentic_aw_runtime/lib.rs
1//! Greentic Agentic Worker Runtime — library crate.
2//!
3//! See `docs/superpowers/specs/2026-05-22-enterprise-aw-runtime-design.md`
4//! for the full design spec. This crate exposes the [`AgentRuntime`] entry
5//! point and the trait surface (`AgentStateStore`, `ConfigProvider`,
6//! `LlmBackend`, `Telemetry`) that the production runner-host and the
7//! designer playground both consume.
8//!
9//! The [`graph`] module provides durable multi-agent graph execution
10//! (`GraphExecutor`, `GraphConfig`, `CheckpointStore`); see
11//! `docs/superpowers/specs/2026-06-06-runtime-agent-graph-execution-design.md`.
12
13#![deny(unsafe_code)]
14#![warn(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
15
16pub mod a2a_source;
17pub mod artifact_door;
18pub mod artifact_reader;
19pub mod attachment_guard;
20pub mod attachments;
21pub mod attachments_materialize;
22mod background;
23pub mod billing;
24pub mod component_source;
25pub mod config;
26pub mod config_provider;
27pub mod cost;
28pub mod dispatch_ledger;
29pub mod dw;
30pub mod end_conversation;
31pub mod error;
32pub mod flow_source;
33mod flow_suspend;
34pub mod graph;
35pub mod guardrail;
36pub mod guardrail_provider;
37pub mod http_provider;
38pub mod knowledge;
39pub mod kv;
40pub mod layered_provider;
41pub mod llm;
42pub mod llm_credential;
43pub mod llm_extension;
44#[cfg(feature = "greentic-llm-backend")]
45pub mod llm_greentic;
46pub mod llm_openai;
47mod lock_keepalive;
48pub mod long_term;
49pub mod r#loop;
50pub mod manifest_provider;
51pub mod manifest_tools;
52pub mod mcp_local;
53pub mod mcp_scope;
54pub mod mcp_secrets;
55pub mod mcp_source;
56pub mod mcp_store_pull;
57pub mod memory;
58pub mod oauth;
59pub mod outbound_guard;
60pub mod playbook_source;
61pub mod run_trace;
62pub mod scoped_secrets;
63pub mod share_policy;
64pub mod short_term;
65pub mod sorla_source;
66pub mod state;
67pub mod state_kv;
68pub mod state_redis;
69pub mod telemetry;
70pub mod tenant;
71pub mod tool_call_frame;
72pub mod tool_session;
73pub mod tool_wire_name;
74pub mod tools;
75pub mod url_redact;
76pub mod user_ledger;
77
78#[cfg(feature = "test-mock")]
79pub mod mock;
80
81#[cfg(feature = "serve")]
82pub mod serve;
83
84pub use a2a_source::{A2aRoute, A2aToolCatalog, A2aToolEntry, A2aToolSource};
85pub use artifact_door::{DOOR_ATTEMPTS, DOOR_CONCURRENCY, DoorReply, DoorRetry, DoorSendError};
86pub use artifact_reader::{
87 ArtifactBytes, ArtifactClientError, ArtifactError, ArtifactReader, HttpArtifactReader, door_url,
88};
89pub use attachments::{AttachmentKind, AttachmentRef, is_artifact_ref};
90pub use component_source::{
91 ComponentInvoker, ComponentOperation, ComponentToolCatalog, ComponentToolEntry,
92 ComponentToolSource,
93};
94pub use config::{
95 AgentConfig, AgentLimits, LlmProviderRef, MemoryProviderRef, MemorySettings, ParkedTextPolicy,
96 ToolRef,
97};
98pub use config_provider::{CachingConfigProvider, ConfigProvider, InMemoryConfigProvider};
99#[cfg(feature = "test-mock")]
100pub use cost::MockTokenMeter;
101pub use cost::{KvTokenMeter, RedisTokenMeter, TokenMeter};
102pub use dispatch_ledger::{DispatchLedger, NoopDispatchLedger, RedisDispatchLedger};
103pub use error::{AgentError, ConfigError, LlmError, MemoryError, StateError, TerminationReason};
104pub use flow_source::{
105 FlowInvokeOutcome, FlowInvoker, FlowOperation, FlowToolCatalog, FlowToolEntry, FlowToolSource,
106};
107pub use graph::http_provider::{CachingGraphProvider, HttpGraphProvider};
108pub use http_provider::HttpConfigProvider;
109#[cfg(feature = "state-disk")]
110pub use kv::RedbKv;
111pub use kv::{AwKv, MemoryKv};
112pub use layered_provider::LayeredConfigProvider;
113pub use llm::{LlmBackend, LlmRequest, LlmResponse, RetryingLlmBackend};
114pub use llm_extension::{
115 BridgeCredential, ExtensionLlmBackend, LlmExtensionInvoker, RuntimeInvoker,
116};
117#[cfg(feature = "greentic-llm-backend")]
118pub use llm_greentic::GreenticLlmBackend;
119pub use llm_openai::{OpenAiLlmBackend, encode_tool_name, split_tool_name};
120pub use long_term::{
121 EpisodeIngest, EpisodeSource, IngestOutcome, LongTermMemory, LongTermMemoryError, RecallQuery,
122 RecalledFact,
123};
124pub use manifest_provider::ManifestToolOverlayProvider;
125pub use mcp_source::{
126 MCP_ROLE_AGENTIC_WORKER, MCP_ROLE_FLOW_EDITOR, McpCallerIdentity, McpPackRoute, McpRoute,
127 McpToolCatalog, McpToolEntry, McpToolSource, dispatch_route,
128};
129pub use memory::{InMemoryMemoryProvider, MemoryProvider, MemoryQuery, MemoryRecord};
130pub use playbook_source::{
131 PlaybookLlmCapability, PlaybookLlmRequirement, PlaybookLlmTier, PlaybookOperation,
132 PlaybookSource, PlaybookToolCatalog, PlaybookToolEntry, PlaybookToolSource, PlaybookTurnFn,
133 PlaybookTurnRequest, PlaybookTurnResult,
134};
135/// The `reqwest` the door helpers ([`DoorRetry`]) speak. A door client in
136/// another crate builds its `reqwest::Client` from this one, so the two never
137/// disagree on the version.
138pub use reqwest as door_reqwest;
139pub use run_trace::{RunContext, RunTrace, StepId, ToolOutcome};
140pub use share_policy::{BindingModes, ShareMode, SharePolicy};
141pub use sorla_source::{
142 SorlaToolCatalog, SorlaToolEntry, SorlaToolSource, SorxInvoker, SorxOperation,
143};
144pub use state::{AgentStateStore, ChatMessage, ConversationState, SessionLock};
145pub use state_kv::KvAgentStateStore;
146pub use state_redis::RedisAgentStateStore;
147pub use telemetry::{OtelTelemetry, StepTelemetryCtx, Telemetry};
148pub use tenant::{TenantContext, VerifiedCaller};
149pub use tool_call_frame::{ToolCallFrame, current_tool_call};
150pub use tool_session::{ToolSession, ToolSessionError, ToolSessionSchema};
151pub use tool_wire_name::{ToolNameCodec, is_wire_safe, wire_tool_name};
152pub use tools::{KvToolLedger, RedisToolLedger, ToolLedger};
153pub use user_ledger::{UserLedgerBinding, UserLedgerTarget};
154
155use std::sync::Arc;
156
157/// Observer for incremental step progress: token deltas as the LLM streams
158/// its reply, and tool-call activity as the loop dispatches tools.
159///
160/// All methods have no-op default bodies, so callers implement only the
161/// hooks they consume and the non-streaming [`AgentRuntime::step`] path
162/// (which uses [`NoopStepObserver`]) costs nothing.
163///
164/// **Extending this trait:** add new capabilities as NEW defaulted methods
165/// (e.g. `fn on_iteration_started(&self, _iter: u32) {}`) rather than
166/// changing an existing signature. The current `on_token_delta(&self,
167/// chunk: &str)` is deliberately minimal; per-iteration context must arrive
168/// through an additional hook so existing implementors keep compiling.
169pub trait StepObserver: Send + Sync {
170 /// Whether this observer wants token-level streaming. Defaults to
171 /// `false` so the non-streaming [`AgentRuntime::step`] path calls
172 /// [`LlmBackend::complete`] and preserves the exact request wire shape
173 /// (no `stream: true`) every existing caller relied on before streaming
174 /// existed. A streaming consumer overrides this to `true`, which makes
175 /// [`r#loop::run_step`] use [`LlmBackend::complete_streaming`] and drive
176 /// [`StepObserver::on_token_delta`].
177 fn wants_streaming(&self) -> bool {
178 false
179 }
180 /// Called with each incremental text chunk of the assistant reply.
181 /// Only invoked when [`StepObserver::wants_streaming`] returns `true`.
182 fn on_token_delta(&self, _chunk: &str) {}
183 /// Called just before a tool is dispatched, with its arguments.
184 fn on_tool_call(&self, _name: &str, _call_id: &str, _args: &serde_json::Value) {}
185 /// Called after a tool dispatch succeeds, with the tool's result.
186 fn on_tool_result(&self, _name: &str, _call_id: &str, _result: &serde_json::Value) {}
187 /// Called after a tool dispatch fails or is blocked (e.g. not in the
188 /// agent's allow-list), with the error/reason payload. Additive hook —
189 /// see the "Extending this trait" note above.
190 fn on_tool_failed(&self, _name: &str, _call_id: &str, _error: &serde_json::Value) {}
191 /// Called after each LLM iteration completes, with that call's token usage.
192 /// Additive hook — lets a streaming consumer surface a per-message LLM/token
193 /// trace even for turns that call no tools (the token trail is otherwise
194 /// only in the final `AgentOutput.trail`, which the SSE stream omits).
195 fn on_llm_call(&self, _tokens_in: u64, _tokens_out: u64) {}
196 /// Called for every guardrail denial — blocked (Enforce) or merely recorded
197 /// (Monitor). Default no-op: only the audit observer forwards these.
198 /// Additive hook — see the "Extending this trait" note above.
199 fn on_guardrail(&self, _obs: &crate::guardrail::GuardrailObservation) {}
200}
201
202/// No-op observer used by the non-streaming [`AgentRuntime::step`].
203pub struct NoopStepObserver;
204impl StepObserver for NoopStepObserver {}
205
206/// The main entry point for executing a single agentic step.
207///
208/// Construct via [`AgentRuntime::new`] with the trait objects (config,
209/// state, LLM, telemetry, token_meter, ledger) plus a shared
210/// `Arc<ExtensionRuntime>` for tool dispatch. Call [`AgentRuntime::step`]
211/// per inbound user message.
212pub struct AgentRuntime {
213 pub(crate) config_provider: Arc<dyn ConfigProvider>,
214 pub(crate) state_store: Arc<dyn AgentStateStore>,
215 pub(crate) ext_runtime: Arc<greentic_ext_runtime::ExtensionRuntime>,
216 pub(crate) llm: Arc<dyn LlmBackend>,
217 pub(crate) telemetry: Arc<dyn Telemetry>,
218 pub(crate) token_meter: Arc<dyn TokenMeter>,
219 pub(crate) billing_meter: Arc<dyn crate::billing::BillingMeter>,
220 pub(crate) ledger: Arc<dyn ToolLedger>,
221 /// Per-tenant agentic-worker MCP tool source. `None` disables MCP tools
222 /// entirely (`mcp:`-prefixed tool refs then resolve to nothing). The real
223 /// per-operator wiring lives in the runner host; tests and non-MCP callers
224 /// pass `None`.
225 pub(crate) mcp: Option<Arc<crate::mcp_source::McpToolSource>>,
226 /// Policy that supplies platform/tenant-wide mandatory guardrail refs.
227 /// Defaults to [`crate::guardrail::NoMandatoryGuardrails`] (no platform
228 /// enforcement). Replaced by a real policy during runner-host wiring.
229 pub(crate) guardrail_policy: Arc<dyn crate::guardrail::GuardrailPolicy>,
230 /// Evaluator that invokes guardrail WASM extensions.
231 /// Defaults to [`crate::guardrail::AcceptAllEvaluator`] until Task 7
232 /// wires in the real extension-backed evaluator.
233 pub(crate) guardrail_evaluator: Arc<dyn crate::guardrail::GuardrailEvaluator>,
234 /// Per-tenant agentic-worker component tool source. `None` disables
235 /// component tools entirely (`component:`-prefixed tool refs then resolve to
236 /// nothing). Set via [`AgentRuntime::with_component_source`]; the concrete
237 /// invoker (over the runner-host `PackRuntime` component host) is injected
238 /// at the runner-host edge, never compiled in.
239 pub(crate) components: Option<Arc<crate::component_source::ComponentToolSource>>,
240 /// Per-tenant agentic-worker flow tool source. `None` disables flow tools
241 /// entirely (`flow:`-prefixed tool refs then resolve to nothing). Set via
242 /// [`AgentRuntime::with_flow_source`]; the concrete invoker (over the
243 /// runner-host pack flow runtime) is injected at the runner-host edge, never
244 /// compiled in.
245 pub(crate) flows: Option<Arc<crate::flow_source::FlowToolSource>>,
246 /// Set by [`AgentRuntime::with_playbook_source`]; the pack reader and the
247 /// turn effect both live in the host (see `playbook_source`'s header for
248 /// why the turn cannot be resolved here).
249 pub(crate) playbooks: Option<Arc<crate::playbook_source::PlaybookToolSource>>,
250 /// Per-tenant agentic-worker SoRLa SoR tool source. `None` disables sorla
251 /// tools entirely (`sorla:`-prefixed tool refs then resolve to nothing).
252 /// Set via [`AgentRuntime::with_sorla_source`]; the concrete invoker (over
253 /// the host SoRX interact client) is injected at the runner-host edge,
254 /// never compiled in.
255 pub(crate) sorla: Option<Arc<crate::sorla_source::SorlaToolSource>>,
256 /// Agentic-worker A2A tool source. `None` disables A2A tools entirely
257 /// (`a2a:`-prefixed tool refs are then dropped from the tool list and
258 /// reported by the preflight check). Set via
259 /// [`AgentRuntime::with_a2a_source`]. Unlike the flow and component
260 /// sources this one owns its transport, since an A2A agent is plain
261 /// HTTP(S) reachable from here.
262 pub(crate) a2a: Option<Arc<crate::a2a_source::A2aToolSource>>,
263 /// Episodic long-term memory backend (e.g. Chronicle). `None` disables the
264 /// long-term tier. Set via [`AgentRuntime::with_long_term_memory`]; the
265 /// concrete backend is injected at the runner-host edge, never compiled in.
266 pub(crate) long_term_memory: Option<Arc<dyn long_term::LongTermMemory>>,
267 /// Knowledge / RAG (document-corpus) backend (e.g. Chronicle doc-RAG).
268 /// `None` disables the knowledge tier. Set via [`AgentRuntime::with_knowledge`];
269 /// the concrete backend is injected at the runner-host edge, never compiled in.
270 pub(crate) knowledge: Option<Arc<dyn knowledge::Knowledge>>,
271 /// Short-term ("working") memory backend, scoped per `(tenant, session, key)`.
272 /// `None` disables the short-term tier. Set via
273 /// [`AgentRuntime::with_short_term_memory`]; the host attaches the always-
274 /// available in-memory provider, and the tools are gated by
275 /// `config.memory.short_term`.
276 pub(crate) short_term_memory: Option<Arc<dyn crate::memory::MemoryProvider>>,
277 /// Per-binding sharing modes from the pack's `assets/run-context.json`
278 /// (shared context, Phase A2). `None` means every NESTED binding is `none`
279 /// (a top-level turn under an open context still injects and records).
280 pub(crate) share_policy: Option<Arc<crate::share_policy::SharePolicy>>,
281 /// The user ledger (shared context, Phase C): a durable, per verified
282 /// end-user history shared by the environment's units. `None` = off.
283 pub(crate) user_ledger: Option<Arc<crate::user_ledger::UserLedgerBinding>>,
284}
285
286impl AgentRuntime {
287 // Each argument is a distinct injected dependency (config, state, ext,
288 // llm, telemetry, token-meter, ledger, mcp); a builder would add ceremony
289 // without removing the coupling, so the wide constructor is intentional.
290 #[allow(clippy::too_many_arguments)]
291 pub fn new(
292 config_provider: Arc<dyn ConfigProvider>,
293 state_store: Arc<dyn AgentStateStore>,
294 ext_runtime: Arc<greentic_ext_runtime::ExtensionRuntime>,
295 llm: Arc<dyn LlmBackend>,
296 telemetry: Arc<dyn Telemetry>,
297 token_meter: Arc<dyn TokenMeter>,
298 ledger: Arc<dyn ToolLedger>,
299 mcp: Option<Arc<crate::mcp_source::McpToolSource>>,
300 ) -> Self {
301 Self {
302 config_provider,
303 state_store,
304 ext_runtime,
305 llm,
306 telemetry,
307 token_meter,
308 billing_meter: Arc::new(crate::billing::NoopBillingMeter),
309 ledger,
310 mcp,
311 guardrail_policy: Arc::new(crate::guardrail::NoMandatoryGuardrails),
312 guardrail_evaluator: Arc::new(crate::guardrail::AcceptAllEvaluator),
313 components: None,
314 flows: None,
315 playbooks: None,
316 sorla: None,
317 a2a: None,
318 long_term_memory: None,
319 knowledge: None,
320 short_term_memory: None,
321 share_policy: None,
322 user_ledger: None,
323 }
324 }
325
326 /// Override the guardrail policy and evaluator after construction.
327 ///
328 /// Available in all builds (including production runner-host) so the
329 /// runner can inject the real `ExtRuntimeGuardrailEvaluator` +
330 /// `StaticGuardrailPolicy` without requiring `test-mock`.
331 pub fn with_guardrails(
332 mut self,
333 policy: Arc<dyn crate::guardrail::GuardrailPolicy>,
334 evaluator: Arc<dyn crate::guardrail::GuardrailEvaluator>,
335 ) -> Self {
336 self.guardrail_policy = policy;
337 self.guardrail_evaluator = evaluator;
338 self
339 }
340
341 /// Install a billing sink. Defaults to [`crate::billing::NoopBillingMeter`]
342 /// (no-op, billing disabled); the host calls this when
343 /// `GREENTIC_BILLING_BASE_URL` and `GREENTIC_BILLING_SERVICE_SECRET` are
344 /// configured. The setter is intentionally separate from [`AgentRuntime::new`]
345 /// so the constructor signature remains stable across all consumers.
346 #[must_use]
347 pub fn with_billing_meter(mut self, meter: Arc<dyn crate::billing::BillingMeter>) -> Self {
348 self.billing_meter = meter;
349 self
350 }
351
352 /// Wire the component tool source so `component:`-prefixed tool refs resolve
353 /// to greentic `.gtpack` components invoked over the host component runtime.
354 /// Coexists with the MCP/extension tool surfaces; defaults off when not set.
355 #[must_use]
356 pub fn with_component_source(
357 mut self,
358 components: Option<Arc<crate::component_source::ComponentToolSource>>,
359 ) -> Self {
360 self.components = components;
361 self
362 }
363
364 /// Wire the flow tool source so `flow:`-prefixed tool refs resolve to pack
365 /// flows invoked over the host flow runtime. Coexists with the
366 /// MCP/extension/component tool surfaces; defaults off when not set.
367 #[must_use]
368 pub fn with_flow_source(
369 mut self,
370 flows: Option<Arc<crate::flow_source::FlowToolSource>>,
371 ) -> Self {
372 self.flows = flows;
373 self
374 }
375
376 /// Wire the playbook tool source so `playbook:`-prefixed tool refs resolve
377 /// to the playbooks the loaded packs carry. Defaults off when not set.
378 ///
379 /// Unlike every sibling source this one carries a TURN EFFECT as well as a
380 /// reader, because running a playbook is an LLM turn rather than an outbound
381 /// call — see `playbook_source`'s header.
382 #[must_use]
383 pub fn with_playbook_source(
384 mut self,
385 playbooks: Option<Arc<crate::playbook_source::PlaybookToolSource>>,
386 ) -> Self {
387 self.playbooks = playbooks;
388 self
389 }
390
391 /// Install the pack-carried sharing policy (`assets/run-context.json`).
392 /// Defaults off: with no policy every nested call shares nothing.
393 #[must_use]
394 pub fn with_share_policy(
395 mut self,
396 policy: Option<Arc<crate::share_policy::SharePolicy>>,
397 ) -> Self {
398 self.share_policy = policy;
399 self
400 }
401
402 /// The installed sharing policy, if any.
403 pub fn share_policy(&self) -> Option<&Arc<crate::share_policy::SharePolicy>> {
404 self.share_policy.as_ref()
405 }
406
407 /// Install the user ledger. Defaults off; the runner host installs one
408 /// only when the embedding host passed a door target AND a pack names the
409 /// agent (`assets/user-ledger.json`).
410 #[must_use]
411 pub fn with_user_ledger(
412 mut self,
413 binding: Option<Arc<crate::user_ledger::UserLedgerBinding>>,
414 ) -> Self {
415 self.user_ledger = binding;
416 self
417 }
418
419 /// The installed user ledger, if any.
420 pub fn user_ledger(&self) -> Option<&Arc<crate::user_ledger::UserLedgerBinding>> {
421 self.user_ledger.as_ref()
422 }
423
424 pub(crate) fn share_modes_for(
425 &self,
426 agent_id: &str,
427 ) -> Option<Arc<crate::share_policy::BindingModes>> {
428 self.share_policy
429 .as_ref()
430 .and_then(|p| p.for_agent(agent_id))
431 }
432
433 /// Attach a per-tenant SoRLa SoR tool source: `sorla:<pack>` tool refs
434 /// resolve to a SoR BusinessAction invoked over the host SoRX interact
435 /// client. Coexists with the mcp/component/flow sources.
436 #[must_use]
437 pub fn with_sorla_source(
438 mut self,
439 sorla: Option<Arc<crate::sorla_source::SorlaToolSource>>,
440 ) -> Self {
441 self.sorla = sorla;
442 self
443 }
444
445 /// Wire the A2A tool source so `a2a:`-prefixed tool refs resolve to
446 /// external A2A agents invoked over HTTP(S). Coexists with the
447 /// mcp/component/flow/sorla sources; defaults off when not set.
448 #[must_use]
449 pub fn with_a2a_source(mut self, a2a: Option<Arc<crate::a2a_source::A2aToolSource>>) -> Self {
450 self.a2a = a2a;
451 self
452 }
453
454 /// Wire the episodic long-term memory backend (e.g. Chronicle). Coexists
455 /// with the short-term/working memory; defaults off when not set.
456 #[must_use]
457 pub fn with_long_term_memory(mut self, memory: Arc<dyn long_term::LongTermMemory>) -> Self {
458 self.long_term_memory = Some(memory);
459 self
460 }
461
462 /// Wire the short-term ("working") memory backend. Coexists with the
463 /// long-term tier; defaults off when not set. The MVP host attaches the
464 /// in-memory provider unconditionally; the `remember`/`recall` tools are
465 /// advertised only when `config.memory.short_term` is set.
466 #[must_use]
467 pub fn with_short_term_memory(
468 mut self,
469 memory: Arc<dyn crate::memory::MemoryProvider>,
470 ) -> Self {
471 self.short_term_memory = Some(memory);
472 self
473 }
474
475 /// Ingest one episode (conversation turn, document, event) into long-term
476 /// memory. Returns [`LongTermMemoryError::NotConfigured`] when no long-term
477 /// backend is wired.
478 pub async fn remember_episode(
479 &self,
480 tenant: &TenantContext,
481 episode: long_term::EpisodeIngest,
482 ) -> Result<long_term::IngestOutcome, long_term::LongTermMemoryError> {
483 let memory = self.long_term_memory.as_ref().ok_or_else(|| {
484 long_term::LongTermMemoryError::NotConfigured("long-term memory not wired".into())
485 })?;
486 let ctx = long_term::to_types_tenant(tenant)?;
487 memory.ingest_episode(&ctx, episode).await
488 }
489
490 /// Semantic recall over long-term memory. Returns
491 /// [`LongTermMemoryError::NotConfigured`] when no long-term backend is wired.
492 pub async fn recall_long_term(
493 &self,
494 tenant: &TenantContext,
495 query: long_term::RecallQuery,
496 ) -> Result<Vec<long_term::RecalledFact>, long_term::LongTermMemoryError> {
497 let memory = self.long_term_memory.as_ref().ok_or_else(|| {
498 long_term::LongTermMemoryError::NotConfigured("long-term memory not wired".into())
499 })?;
500 let ctx = long_term::to_types_tenant(tenant)?;
501 memory.recall(&ctx, query).await
502 }
503
504 /// Wire the knowledge / RAG backend (e.g. Chronicle doc-RAG). Coexists with
505 /// the memory tiers (distinct `cap://dw.knowledge` capability); defaults off.
506 #[must_use]
507 pub fn with_knowledge(mut self, knowledge: Arc<dyn knowledge::Knowledge>) -> Self {
508 self.knowledge = Some(knowledge);
509 self
510 }
511
512 /// Whether a knowledge / RAG backend is mounted. Mirrors the check
513 /// [`knowledge::knowledge_active`] applies against `runtime.knowledge` in the
514 /// agentic loop, exposed so hosts and tests can confirm the seam is wired
515 /// without issuing a (network-bound) [`Self::search_knowledge`] call.
516 ///
517 /// This answers "can retrieval be attempted at all", NOT "is a corpus
518 /// mounted": a host may mount a backend that delegates elsewhere per turn,
519 /// in which case this is true with no corpus behind it. Ask
520 /// [`knowledge::Knowledge::wrapped_backend`] for that, via
521 /// [`Self::knowledge_backend`].
522 #[must_use]
523 pub fn has_knowledge(&self) -> bool {
524 self.knowledge.is_some()
525 }
526
527 /// Whether an A2A tool source is wired, so `a2a:` refs can resolve.
528 ///
529 /// Exposed for the host's wiring regression test. The runtime is built in
530 /// runner-host, where this field is not visible, and a dropped
531 /// `with_a2a_source` call otherwise fails only as "the tool vanished" at
532 /// run time.
533 #[must_use]
534 pub fn has_a2a_source(&self) -> bool {
535 self.a2a.is_some()
536 }
537
538 /// The mounted knowledge backend, if any.
539 ///
540 /// Exposed so a host that mounts a SECOND backend can wrap the first
541 /// instead of replacing it: [`Self::with_knowledge`] overwrites the field,
542 /// and two mounts that each assume they are the only one would silently
543 /// disable whichever ran first.
544 #[must_use]
545 pub fn knowledge_backend(&self) -> Option<Arc<dyn knowledge::Knowledge>> {
546 self.knowledge.clone()
547 }
548
549 /// Hybrid retrieval over the agent's knowledge corpus. Returns
550 /// [`knowledge::KnowledgeError::NotConfigured`] when no backend is wired.
551 ///
552 /// `binding` is the agent's own `config.knowledge.knowledge` provider ref
553 /// for this turn. It is threaded through because a backend may delegate to
554 /// a target named in the binding's `params` — see
555 /// [`knowledge::Knowledge::search_bound`] for why that cannot ride on the
556 /// runtime-level field or inside [`knowledge::KnowledgeQuery`].
557 pub async fn search_knowledge(
558 &self,
559 tenant: &TenantContext,
560 query: knowledge::KnowledgeQuery,
561 binding: Option<&config::MemoryProviderRef>,
562 ) -> knowledge::KnowledgeResult<Vec<knowledge::RetrievedChunk>> {
563 let kb = self
564 .knowledge
565 .as_ref()
566 .ok_or(knowledge::KnowledgeError::NotConfigured)?;
567 let ctx = knowledge::to_types_tenant(tenant)?;
568 kb.search_bound(&ctx, query, binding).await
569 }
570
571 /// The card of the session's live parked `flow:` tool, if any. A host uses
572 /// it to keep the card on offer when a turn fails after the park was kept
573 /// (an LLM error or a lock timeout during a side turn), so the user's next
574 /// submit is not lost. `None` when nothing is parked, the park expired, or
575 /// the state cannot be read.
576 pub async fn parked_card(
577 &self,
578 tenant: &TenantContext,
579 session_id: &str,
580 ) -> Option<serde_json::Value> {
581 let state = self.state_store.load(tenant, session_id).await.ok()?;
582 let pending = state.pending_tool?;
583 if pending.is_expired(chrono::Utc::now()) {
584 return None;
585 }
586 pending.presentation
587 }
588
589 /// Execute one agentic step against the given session.
590 /// Implementation lives in [`r#loop::run_step`].
591 pub async fn step(
592 &self,
593 tenant: TenantContext,
594 session_id: &str,
595 agent_id: &str,
596 message: AgentInput,
597 ) -> Result<AgentOutput, AgentError> {
598 self.step_with_observer(
599 tenant,
600 session_id,
601 agent_id,
602 message,
603 Arc::new(NoopStepObserver),
604 )
605 .await
606 }
607
608 /// Execute one agentic step while reporting incremental progress to
609 /// `observer` (streamed token deltas + tool-call activity).
610 /// [`AgentRuntime::step`] delegates here with a [`NoopStepObserver`].
611 pub async fn step_with_observer(
612 &self,
613 tenant: TenantContext,
614 session_id: &str,
615 agent_id: &str,
616 message: AgentInput,
617 observer: Arc<dyn StepObserver>,
618 ) -> Result<AgentOutput, AgentError> {
619 r#loop::run_step(self, tenant, session_id, agent_id, message, observer).await
620 }
621}
622
623/// Inbound user message handed to [`AgentRuntime::step`].
624#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
625pub struct AgentInput {
626 pub text: String,
627 /// Whether THIS invocation is a conversational segment. Set from the flow
628 /// node's `conversational` flag so a node marked conversational makes the
629 /// agent's host `end_conversation` tool available (and the closing prompt
630 /// note) even when the agent's own [`AgentConfig::conversational`] default
631 /// is false — the node, not just the agent config, can opt in. OR-ed with
632 /// the agent config in the loop.
633 #[serde(default)]
634 pub conversational: bool,
635 /// The user's answer to a flow tool that parked this agent on a card
636 /// ([`TerminationReason::AwaitingToolInput`]) — typically the card's
637 /// submit. `Some` resumes the pending tool flow with it; `None` while a
638 /// tool is pending cancels that tool and treats `text` as an ordinary
639 /// message. Ignored when no tool is pending.
640 ///
641 /// [`TerminationReason::AwaitingToolInput`]: crate::error::TerminationReason::AwaitingToolInput
642 #[serde(default, skip_serializing_if = "Option::is_none")]
643 pub resume_payload: Option<serde_json::Value>,
644 /// Attachments of THIS message (references only; see [`attachments`]).
645 ///
646 /// Adding this field made `AgentInput { .. }` literals without a base fail
647 /// to compile; downstream constructors use `..Default::default()` rather
648 /// than the struct being `#[non_exhaustive]`.
649 #[serde(default, skip_serializing_if = "Vec::is_empty")]
650 pub attachments: Vec<AttachmentRef>,
651}
652
653/// Token + iteration accounting for one [`AgentRuntime::step`]. Surfaced on
654/// [`AgentOutput`] so a caller (e.g. the designer's Run Demo trace) can show
655/// per-turn LLM usage without a separate telemetry channel.
656#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
657pub struct StepUsage {
658 /// Prompt tokens summed across every LLM call in this step.
659 pub tokens_in: u64,
660 /// Completion tokens summed across every LLM call in this step.
661 pub tokens_out: u64,
662 /// Plan-Act-Observe iterations the loop ran this step.
663 pub iterations: u32,
664}
665
666/// Outbound reply produced by [`AgentRuntime::step`].
667#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
668pub struct AgentOutput {
669 pub reply: String,
670 pub trail: Vec<AgentStep>,
671 pub terminated_by: TerminationReason,
672 /// Per-step token + iteration usage (default zero for callers that don't
673 /// track it, e.g. mocks).
674 #[serde(default)]
675 pub usage: StepUsage,
676 /// What to show the user while the agent waits on a flow tool — set only
677 /// when `terminated_by` is [`TerminationReason::AwaitingToolInput`]. It is
678 /// the parked flow's own output at its park point (typically an Adaptive
679 /// Card), rendered in place of `reply`.
680 ///
681 /// [`TerminationReason::AwaitingToolInput`]: crate::error::TerminationReason::AwaitingToolInput
682 #[serde(default, skip_serializing_if = "Option::is_none")]
683 pub pending_presentation: Option<serde_json::Value>,
684 /// True when this turn answered a typed message as a side turn while the
685 /// flow tool stayed parked; `reply` is the answer and
686 /// `pending_presentation` the card re-offered after it.
687 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
688 pub side_turn: bool,
689}
690
691/// One iteration of the Plan-Act-Observe loop, surfaced in the audit
692/// trail (`AgentOutput.trail`). Caller decides whether to persist or
693/// display.
694#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
695#[serde(tag = "kind", rename_all = "snake_case")]
696pub enum AgentStep {
697 /// One LLM iteration's assistant output + token cost, recorded before that
698 /// iteration's tool calls. Lets a caller show a per-message breakdown (each
699 /// model call), not just the aggregate `AgentOutput.usage`. `content` is the
700 /// assistant text for the turn (empty when the model only emitted tool calls).
701 LlmCall {
702 content: String,
703 tokens_in: u64,
704 tokens_out: u64,
705 },
706 ToolCall {
707 name: String,
708 call_id: String,
709 /// The arguments the model passed to the tool (its input). Lets a caller
710 /// show what was actually requested, not just the tool name. Defaults to
711 /// `null` for older trails that predate this field.
712 #[serde(default)]
713 args: serde_json::Value,
714 result: serde_json::Value,
715 /// Wall-clock time spent dispatching this tool call, in milliseconds.
716 /// `0` for host built-ins that resolve instantly and for older trails.
717 #[serde(default)]
718 duration_ms: u64,
719 },
720 ToolCallReused {
721 name: String,
722 call_id: String,
723 },
724 ToolCallBlocked {
725 name: String,
726 reason: String,
727 },
728 Reply {
729 text: String,
730 },
731 /// The worker's BUILT-IN knowledge base (`KnowledgeSettings`) was searched
732 /// for this turn and returned `chunks`, which were injected into the system
733 /// prompt before the first LLM call. Recorded once per step, ahead of every
734 /// `LlmCall`, and only when retrieval succeeded with at least one chunk — a
735 /// failed or empty retrieval injects nothing and so has nothing to cite.
736 ///
737 /// This is NOT a tool call: the model did not ask for it, the loop ran it.
738 /// Recording it as a synthetic `ToolCall` would inflate tool-call counts and
739 /// anything metering them. It exists so a trail consumer (greentic-start's
740 /// `agent_provenance`) can cite what a knowledge-grounded answer drew on.
741 ///
742 /// The chunks are recorded faithfully, text included: the trail is
743 /// server-side data. Whether a chunk's text may reach an end user's
744 /// browser is the CONSUMER's disclosure decision, not the runtime's.
745 ///
746 /// Adding a variant to this `#[serde(tag = "kind")]` enum is a contract
747 /// change: a strict `Vec<AgentStep>` deserialiser built against an older
748 /// runtime rejects `"kind": "knowledge_retrieval"`. Readers must skip kinds
749 /// they do not know.
750 KnowledgeRetrieval {
751 chunks: Vec<knowledge::RetrievedChunk>,
752 },
753}